lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Display-only distribution primitives.
//!
//! KDE primitives support violin and standalone density plots. Type-7 sample
//! quantiles support box, violin, and Q-Q reference geometry; standard-normal
//! quantiles provide deterministic Q-Q theoretical positions.

/// Kernel density estimate using a Gaussian kernel and
/// Scott's rule bandwidth.
///
/// `kde(samples, grid_points)` evaluates the KDE at each
/// point in `grid_points` and returns the density values
/// (one per grid point). The bandwidth is computed from
/// `samples` via Scott's rule (`h = n^(-1/5) * std(samples)`);
/// all grid points share the same bandwidth.
///
/// # Errors
///
/// Returns `Error::Data` if samples, grid points, or the derived
/// bandwidth cannot produce finite density values.
///
/// # Examples
///
/// ```
/// use lichtung_plot::stats::distribution::kde;
///
/// let samples = vec![0.0, 1.0, 2.0, 3.0, 4.0];
/// let grid = vec![0.0, 1.0, 2.0, 3.0, 4.0];
/// let densities = kde(&samples, &grid).unwrap();
/// // The density is highest at the center (2.0) and
/// // falls off symmetrically.
/// assert!(densities[2] > densities[0]);
/// assert!(densities[2] > densities[4]);
/// ```
pub fn kde(samples: &[f64], grid_points: &[f64]) -> Result<Vec<f64>, crate::Error> {
    kde_with_operation(
        samples,
        grid_points,
        &crate::operation::OperationOptions::default(),
    )
}

/// Evaluate the same KDE with a per-call cancellation and resource budget.
pub fn kde_with_operation(
    samples: &[f64],
    grid_points: &[f64],
    options: &crate::operation::OperationOptions,
) -> Result<Vec<f64>, crate::Error> {
    crate::operation::run_scientific(options, || {
        crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
        let densities = kde_in_operation(samples, grid_points)?;
        crate::operation::checkpoint()?;
        Ok(densities)
    })
}

pub(crate) fn kde_in_operation(
    samples: &[f64],
    grid_points: &[f64],
) -> Result<Vec<f64>, crate::Error> {
    Ok(kde_with_bandwidth(samples, grid_points)?.0)
}

/// Retain the exact bandwidth used by the same evaluation pass.
pub(crate) fn kde_with_bandwidth(
    samples: &[f64],
    grid_points: &[f64],
) -> Result<(Vec<f64>, f64), crate::Error> {
    let bandwidth = kde_bandwidth(samples)?;
    Ok((gaussian_kde(samples, grid_points, bandwidth)?, bandwidth))
}

#[cfg(test)]
thread_local! {
    pub(crate) static KDE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Evaluate a Gaussian KDE with an already validated bandwidth.
pub(crate) fn gaussian_kde(
    samples: &[f64],
    grid_points: &[f64],
    bandwidth: f64,
) -> Result<Vec<f64>, crate::Error> {
    use crate::Error;
    #[cfg(test)]
    KDE_CALLS.with(|count| count.set(count.get() + 1));
    if samples.is_empty() || !bandwidth.is_finite() || bandwidth <= 0.0 {
        return Err(Error::Data(
            "kde: samples and a positive finite bandwidth are required".into(),
        ));
    }

    for chunk in samples.chunks(1024).chain(grid_points.chunks(1024)) {
        crate::operation::checkpoint()?;
        crate::operation::scientific_work(chunk.len())?;
        if chunk.iter().any(|value| !value.is_finite()) {
            return Err(Error::Data(
                "kde: samples and grid points must be finite".into(),
            ));
        }
    }
    #[allow(clippy::cast_precision_loss)]
    let n = samples.len() as f64;
    let normal_factor = (2.0 * std::f64::consts::PI).sqrt();
    let mut densities = Vec::new();
    crate::data::source::reserve_source(&mut densities, grid_points.len())?;
    for &x in grid_points {
        let mut sum = 0.0;
        for chunk in samples.chunks(1024) {
            crate::operation::checkpoint()?;
            crate::operation::scientific_work(chunk.len())?;
            for &s in chunk {
                let difference = x - s;
                let z = if difference.is_finite() {
                    difference / bandwidth
                } else {
                    x / bandwidth - s / bandwidth
                };
                sum += (-0.5 * z * z).exp();
            }
        }
        let density = ((sum / n) / normal_factor) / bandwidth;
        if !density.is_finite() {
            return Err(Error::Data("kde: computed a non-finite density".into()));
        }
        densities.push(density);
    }
    Ok(densities)
}

/// The actual zero-valued endpoints of a closed painted density profile.
pub(crate) fn closed_density(
    values: &[f64],
) -> impl DoubleEndedIterator<Item = f64> + ExactSizeIterator + '_ {
    values.iter().enumerate().map(|(index, &density)| {
        if index == 0 || index == values.len() - 1 {
            0.
        } else {
            density
        }
    })
}

/// Strict, scale-robust Scott bandwidth for standalone density plots.
pub(crate) fn strict_scott_bandwidth(samples: &[f64]) -> Result<f64, crate::Error> {
    scott_bandwidth(samples, true)
}

/// Display distributions retain the original positive bandwidth floor.
pub(crate) fn kde_bandwidth(samples: &[f64]) -> Result<f64, crate::Error> {
    scott_bandwidth(samples, false)
}

#[allow(clippy::cast_precision_loss)]
fn scott_bandwidth(samples: &[f64], strict: bool) -> Result<f64, crate::Error> {
    use crate::Error;
    if samples.is_empty() || (strict && samples.len() < 2) {
        return Err(Error::Data(
            if strict {
                "requires at least 2 observations for Scott bandwidth"
            } else {
                "kde: samples is empty; bandwidth is undefined"
            }
            .into(),
        ));
    }
    let mut minimum = f64::INFINITY;
    let mut maximum = f64::NEG_INFINITY;
    for chunk in samples.chunks(1024) {
        crate::operation::checkpoint()?;
        crate::operation::scientific_work(chunk.len())?;
        for &value in chunk {
            if !value.is_finite() {
                return Err(Error::Data("kde: samples must be finite".into()));
            }
            minimum = minimum.min(value);
            maximum = maximum.max(value);
        }
    }
    if minimum >= maximum {
        return if strict {
            Err(Error::Data(
                "has constant values; Scott bandwidth requires nonzero scale".into(),
            ))
        } else {
            Ok(1e-6)
        };
    }
    // Center before scaling: adjacent finite observations at a large offset
    // must not lose their variance when divided by the offset itself.
    let center = minimum.midpoint(maximum);
    let scale = (maximum - center).max(center - minimum);
    let mut mean = 0.0;
    let mut sum_squared_deviations = 0.0;
    for (index, value) in samples.iter().copied().enumerate() {
        if index.is_multiple_of(1024) {
            crate::operation::checkpoint()?;
        }
        crate::operation::scientific_work(1)?;
        let normalized = (value - center) / scale;
        let count = (index + 1) as f64;
        let delta = normalized - mean;
        mean += delta / count;
        sum_squared_deviations += delta * (normalized - mean);
    }
    let variance = sum_squared_deviations / (samples.len() - 1) as f64;
    let bandwidth = variance.sqrt() * (samples.len() as f64).powf(-0.2) * scale;
    if !bandwidth.is_finite() || (strict && bandwidth <= 0.0) {
        return Err(Error::Data(
            "has nonzero scale but Scott bandwidth is not representable".into(),
        ));
    }
    Ok(if strict {
        bandwidth
    } else {
        bandwidth.max(1e-6)
    })
}

/// Union KDE support for one or more sample groups.
pub(crate) fn kde_support_range<'a>(
    groups: impl IntoIterator<Item = &'a [f64]>,
    cut: f64,
) -> Result<Option<(f64, f64)>, crate::Error> {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for samples in groups {
        if samples.is_empty() {
            continue;
        }
        let bandwidth = kde_bandwidth(samples)?;
        let mut group_lo = f64::INFINITY;
        let mut group_hi = f64::NEG_INFINITY;
        for chunk in samples.chunks(1024) {
            crate::operation::checkpoint()?;
            crate::operation::scientific_work(chunk.len())?;
            for &value in chunk {
                group_lo = group_lo.min(value);
                group_hi = group_hi.max(value);
            }
        }
        lo = lo.min(group_lo - cut * bandwidth);
        hi = hi.max(group_hi + cut * bandwidth);
    }
    if !(lo.is_finite() && hi.is_finite()) {
        return Ok(None);
    }
    Ok(Some(if (hi - lo).abs() < f64::EPSILON {
        (lo - 1.0, hi + 1.0)
    } else {
        (lo, hi)
    }))
}

/// Actual distinct binary64 nodes of the nominal uniform grid. Exact affine
/// rounding neither overflows between finite endpoints nor repeats a rounded
/// coordinate that the supplying geometry would reject.
pub(crate) fn representable_grid(
    range: (f64, f64),
    count: usize,
) -> Result<Vec<f64>, crate::Error> {
    if count < 2 || !range.0.is_finite() || !range.1.is_finite() || range.0 >= range.1 {
        return Err(crate::Error::Data(
            "KDE requires a finite increasing support".into(),
        ));
    }
    let mut grid = Vec::new();
    crate::data::source::reserve_source(&mut grid, count)?;
    for index in 0..count - 1 {
        if index.is_multiple_of(64) {
            crate::operation::checkpoint()?;
        }
        crate::operation::scientific_work(1)?;
        let point = crate::numeric::binary::affine(range.0, range.1, index, count - 1)?;
        if point < range.1 && grid.last().is_none_or(|previous| *previous < point) {
            grid.push(point);
        }
    }
    crate::operation::scientific_work(1)?;
    grid.push(range.1);
    Ok(grid)
}

pub(crate) fn tukey_fences(q1: f64, q3: f64) -> Result<(f64, f64), crate::Error> {
    let iqr = q3 - q1;
    let lower = q1 - 1.5 * iqr;
    let upper = q3 + 1.5 * iqr;
    if !lower.is_finite() || !upper.is_finite() {
        return Err(crate::Error::Data(
            "Tukey fences exceed finite binary64 representation".into(),
        ));
    }
    Ok((lower, upper))
}

/// Quantile (q-th percentile) of `samples`.
///
/// Returns the value below which `q * 100%` of the
/// `samples` lie, using linear interpolation between
/// order statistics (the "Type 7" quantile method in
/// Hyndman & Fan, the same convention as R's default
/// `quantile(type=7)` and NumPy's default
/// `numpy.quantile(method='linear')`).
///
/// `q` must be in `[0.0, 1.0]`.
///
/// # Errors
///
/// Returns `Error::Data` if `samples` is empty, `q` is non-finite or
/// outside `[0, 1]`, or any sample is non-finite.
///
/// # Examples
///
/// ```
/// use lichtung_plot::stats::distribution::quantile;
///
/// let samples = vec![1.0, 2.0, 3.0, 4.0, 5.0];
/// assert!((quantile(&samples, 0.5).unwrap() - 3.0).abs() < 1e-9);
/// assert!((quantile(&samples, 0.0).unwrap() - 1.0).abs() < 1e-9);
/// assert!((quantile(&samples, 1.0).unwrap() - 5.0).abs() < 1e-9);
/// ```
pub fn quantile(samples: &[f64], q: f64) -> Result<f64, crate::Error> {
    quantile_with_operation(samples, q, &crate::operation::OperationOptions::default())
}

/// Compute the Type-7 quantile using this call's operation options.
pub fn quantile_with_operation(
    samples: &[f64],
    q: f64,
    options: &crate::operation::OperationOptions,
) -> Result<f64, crate::Error> {
    crate::operation::run_scientific(options, || {
        crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
        let result = quantile_in_operation(samples, q)?;
        crate::operation::checkpoint()?;
        Ok(result)
    })
}

fn quantile_in_operation(samples: &[f64], q: f64) -> Result<f64, crate::Error> {
    use crate::Error;
    if samples.is_empty() {
        return Err(Error::Data("quantile: samples is empty".into()));
    }
    if !q.is_finite() || !(0.0..=1.0).contains(&q) {
        return Err(Error::Data(
            format!("quantile: q must be finite and in [0, 1], got {q}").into(),
        ));
    }
    for (chunk_index, chunk) in samples.chunks(1024).enumerate() {
        crate::operation::checkpoint()?;
        crate::operation::scientific_work(chunk.len())?;
        if let Some((index, value)) = chunk
            .iter()
            .copied()
            .enumerate()
            .find(|(_, value)| !value.is_finite())
        {
            let index = chunk_index * 1024 + index;
            return Err(Error::Data(
                format!("quantile: sample at index {index} must be finite, got {value}").into(),
            ));
        }
    }
    let mut sorted = Vec::new();
    crate::data::source::reserve_source(&mut sorted, samples.len())?;
    sorted.extend_from_slice(samples);
    crate::data::source::sort_numeric_source(&mut sorted)?;
    Ok(sorted_quantile(&sorted, q))
}

/// Type-7 interpolation for a nonempty sorted finite sample and a validated q.
pub(crate) fn sorted_quantile(sorted: &[f64], q: f64) -> f64 {
    let n = sorted.len();
    if n == 1 || q == 0.0 {
        return sorted[0];
    }
    if q.to_bits() == 1.0_f64.to_bits() {
        return sorted[n - 1];
    }
    // Type 7 quantile: h = (n - 1) * q; index = floor(h);
    // fraction = h - index; result = sorted[index] +
    // fraction * (sorted[index + 1] - sorted[index]).
    // Casts are intentional: n is small (≤ thousands)
    // and fits in f64 without loss; h is non-negative
    // and < n - 1 (because q < 1), so the index cast
    // is in range.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss
    )]
    let h = (n - 1) as f64 * q;
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let index = h.floor() as usize;
    #[allow(clippy::cast_precision_loss)]
    let fraction = h - index as f64;
    if index >= n - 1 {
        return sorted[n - 1];
    }
    if fraction == 0.0 {
        return sorted[index];
    }
    let lower = sorted[index];
    let upper = sorted[index + 1];
    let difference = upper - lower;
    if difference.is_finite() {
        lower + fraction * difference
    } else {
        // Center/half-span form is algebraically equivalent when the direct
        // difference overflows for finite opposite-sign endpoints.
        let midpoint = f64::midpoint(lower, upper);
        let half_span = upper / 2.0 - lower / 2.0;
        midpoint + (2.0 * fraction - 1.0) * half_span
    }
}

/// Inverse CDF of the standard normal distribution.
///
/// Uses Peter J. Acklam's rational approximation and is intended for
/// deterministic display statistics such as normal Q-Q plots. The tested
/// absolute error is below `1e-7` across central and representable lower-tail
/// probabilities; this API does not claim full-f64 inverse-CDF accuracy.
///
/// # Errors
///
/// Returns `Error::Data` unless `probability` is finite and strictly
/// between zero and one.
pub fn standard_normal_quantile(probability: f64) -> Result<f64, crate::Error> {
    use crate::Error;
    const A: [f64; 6] = [
        -3.969_683_028_665_376e1,
        2.209_460_984_245_205e2,
        -2.759_285_104_469_687e2,
        1.383_577_518_672_69e2,
        -3.066_479_806_614_716e1,
        2.506_628_277_459_239,
    ];
    const B: [f64; 5] = [
        -5.447_609_879_822_406e1,
        1.615_858_368_580_409e2,
        -1.556_989_798_598_866e2,
        6.680_131_188_771_972e1,
        -1.328_068_155_288_572e1,
    ];
    const C: [f64; 6] = [
        -7.784_894_002_430_293e-3,
        -3.223_964_580_411_365e-1,
        -2.400_758_277_161_838,
        -2.549_732_539_343_734,
        4.374_664_141_464_968,
        2.938_163_982_698_783,
    ];
    const D: [f64; 4] = [
        7.784_695_709_041_462e-3,
        3.224_671_290_700_398e-1,
        2.445_134_137_142_996,
        3.754_408_661_907_416,
    ];
    const LOWER: f64 = 0.024_25;
    const UPPER: f64 = 1.0 - LOWER;

    if !probability.is_finite() || probability <= 0.0 || probability >= 1.0 {
        return Err(Error::Data(
            format!(
            "standard normal quantile: probability must be finite and in (0, 1), got {probability}"
        )
            .into(),
        ));
    }

    let quantile = if probability < LOWER {
        let q = (-2.0 * probability.ln()).sqrt();
        (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
    } else if probability <= UPPER {
        let q = probability - 0.5;
        let r = q * q;
        (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q
            / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0)
    } else {
        let q = (-2.0 * (1.0 - probability).ln()).sqrt();
        -(((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
    };
    if quantile.is_finite() {
        Ok(quantile)
    } else {
        Err(Error::Data(
            "standard normal quantile: approximation produced a non-finite value".into(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- kde ----

    #[test]
    fn kde_integrates_to_approximately_one() {
        // The KDE integrates to 1 over the real line
        // (it's a probability density). With Scott's
        // rule bandwidth and a fine grid, the
        // trapezoidal sum should be ≈ 1.
        let samples: Vec<f64> = (0..100).map(f64::from).map(|i| i / 10.0).collect();
        let grid: Vec<f64> = (-50..=150).map(f64::from).map(|i| i / 10.0).collect();
        let d = kde(&samples, &grid).unwrap();
        let dx = grid[1] - grid[0];
        let integral: f64 = d.iter().sum::<f64>() * dx;
        // Looser tolerance because the trapezoidal
        // rule is approximate and Scott's bandwidth
        // is itself approximate.
        assert!(
            (integral - 1.0).abs() < 0.1,
            "KDE integral should be ≈ 1.0, got {integral}"
        );
    }

    #[test]
    fn strict_scott_bandwidth_rejects_small_and_constant_samples() {
        assert!(strict_scott_bandwidth(&[1.0]).is_err());
        assert!(strict_scott_bandwidth(&[2.0, 2.0]).is_err());
    }

    #[test]
    fn scott_bandwidth_and_kernel_preserve_large_finite_scales() {
        let bandwidth = strict_scott_bandwidth(&[1e16, 1e16 + 2.0]).unwrap();
        let expected = 2_f64.powf(-0.2) * 2_f64.sqrt();
        assert!((bandwidth - expected).abs() < 1e-14);
        let samples = [-1e308, 1e308];
        let grid = [-1e308, 0.0, 1e308];
        let densities = kde(&samples, &grid).unwrap();
        assert!(densities
            .iter()
            .all(|value| value.is_finite() && *value > 0.0));
        assert_eq!(densities[0].to_bits(), densities[2].to_bits());
    }

    // ---- quantile ----

    fn quartiles(samples: &[f64]) -> [f64; 3] {
        [
            quantile(samples, 0.25).unwrap(),
            quantile(samples, 0.5).unwrap(),
            quantile(samples, 0.75).unwrap(),
        ]
    }

    fn bits<const N: usize>(values: [f64; N]) -> [u64; N] {
        values.map(f64::to_bits)
    }

    #[test]
    fn quantile_type_7_quartiles_are_exact_for_two_samples() {
        assert_eq!(bits(quartiles(&[0.0, 4.0])), bits([1.0, 2.0, 3.0]));
    }

    #[test]
    fn quantile_type_7_interpolates_opposite_extreme_finite_values_without_overflow() {
        let samples = [-f64::MAX, f64::MAX];

        assert_eq!(
            bits([
                quantile(&samples, 0.25).unwrap(),
                quantile(&samples, 0.5).unwrap(),
                quantile(&samples, 0.75).unwrap(),
            ]),
            bits([-f64::MAX / 2.0, 0.0, f64::MAX / 2.0])
        );
    }

    #[test]
    fn quantile_rejects_each_non_finite_sample_exactly() {
        for value in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY] {
            let error = quantile(&[1.0, value, 3.0], 0.5).unwrap_err();

            assert_eq!(
                error.to_string(),
                format!("data error: quantile: sample at index 1 must be finite, got {value}")
            );
        }
    }

    #[test]
    fn standard_normal_quantile_matches_central_tail_and_subnormal_references() {
        let references = [
            (0.1, -1.281_551_565_544_600_4),
            (0.9, 1.281_551_565_544_600_4),
            (1e-10, -6.361_340_902_404_056),
            (1e-50, -14.933_337_534_788_487),
            (f64::MIN_POSITIVE, -37.519_379_347_144_5),
            (f64::from_bits(1), -38.467_405_617_144_344),
        ];

        for (probability, expected) in references {
            let actual = standard_normal_quantile(probability).unwrap();
            assert!(
                (actual - expected).abs() < 1e-7,
                "p={probability}: {actual}"
            );
        }
    }
}