lichtung-plot 0.3.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
//! Typed ordinary-bar inputs and generated error-bar specifications.

use super::estimate::Bounds;
use crate::{CategoryValues, Error, NumericValues};

const DEFAULT_LEVEL: f64 = 0.95;
const DEFAULT_RESAMPLES: usize = 1_000;
const MAX_RESAMPLES: usize = 1_000_000;

/// Closed owned input for an ordinary vertical or horizontal bar plot.
#[derive(Debug, Clone)]
pub struct BarInput {
    pub(crate) source: BarSource,
}

#[derive(Debug, Clone)]
pub(crate) enum BarSource {
    Samples {
        values: NumericValues,
        error_bar: ErrorBar,
    },
    Estimates {
        values: NumericValues,
        bounds: Option<Bounds>,
    },
}

impl BarInput {
    /// Use raw observations, rendering each cell's arithmetic mean.
    ///
    /// The default error bar is a deterministic two-sided 95% percentile
    /// bootstrap confidence interval with 1,000 resamples and seed zero.
    #[must_use]
    pub fn samples(values: NumericValues) -> BarSamples {
        BarSamples {
            values,
            error_bar: ErrorBar::confidence_interval().into(),
        }
    }

    /// Use one precomputed estimate per category, group, and facet cell.
    #[must_use]
    pub fn estimates(values: NumericValues) -> Self {
        Self {
            source: BarSource::Estimates {
                values,
                bounds: None,
            },
        }
    }

    /// Use one precomputed estimate and explicit drawable bounds per cell.
    #[must_use]
    pub fn estimates_with_error_bars(values: NumericValues, bounds: Bounds) -> Self {
        Self {
            source: BarSource::Estimates {
                values,
                bounds: Some(bounds),
            },
        }
    }

    pub(crate) const fn values(&self) -> &NumericValues {
        match &self.source {
            BarSource::Samples { values, .. } | BarSource::Estimates { values, .. } => values,
        }
    }

    pub(crate) const fn bounds(&self) -> Option<&Bounds> {
        match &self.source {
            BarSource::Samples { .. } | BarSource::Estimates { bounds: None, .. } => None,
            BarSource::Estimates {
                bounds: Some(bounds),
                ..
            } => Some(bounds),
        }
    }

    pub(crate) const fn error_bar(&self) -> Option<&ErrorBar> {
        match &self.source {
            BarSource::Samples { error_bar, .. } => Some(error_bar),
            BarSource::Estimates { .. } => None,
        }
    }

    pub(crate) const fn is_samples(&self) -> bool {
        matches!(&self.source, BarSource::Samples { .. })
    }
}

/// Raw bar samples with sample-only generated error-bar configuration.
#[derive(Debug, Clone)]
pub struct BarSamples {
    values: NumericValues,
    error_bar: ErrorBar,
}

impl BarSamples {
    /// Replace the generated error-bar specification while retaining raw samples.
    #[must_use]
    pub fn error_bar(mut self, error_bar: impl Into<ErrorBar>) -> Self {
        self.error_bar = error_bar.into();
        self
    }
}

impl From<BarSamples> for BarInput {
    fn from(samples: BarSamples) -> Self {
        Self {
            source: BarSource::Samples {
                values: samples.values,
                error_bar: samples.error_bar,
            },
        }
    }
}

/// Closed generated error-bar taxonomy for raw bar samples.
#[derive(Debug, Clone)]
pub struct ErrorBar(pub(crate) ErrorBarKind);

#[derive(Debug, Clone)]
pub(crate) enum ErrorBarKind {
    Hidden,
    StandardDeviation(StandardDeviation),
    PercentileInterval(PercentileInterval),
    StandardError(StandardError),
    ConfidenceInterval(ConfidenceInterval),
}

impl ErrorBar {
    /// Draw no generated error bar.
    #[must_use]
    pub const fn hidden() -> Self {
        Self(ErrorBarKind::Hidden)
    }

    /// Configure sample standard-deviation error bars with scale one.
    #[must_use]
    pub const fn standard_deviation() -> StandardDeviation {
        StandardDeviation { scale: 1.0 }
    }

    /// Configure a central percentile interval of the original observations.
    #[must_use]
    pub const fn percentile_interval() -> PercentileInterval {
        PercentileInterval {
            level: DEFAULT_LEVEL,
        }
    }

    /// Configure sample standard-error bars with scale one.
    #[must_use]
    pub const fn standard_error() -> StandardError {
        StandardError { scale: 1.0 }
    }

    /// Configure a two-sided confidence interval with the default bootstrap.
    #[must_use]
    pub const fn confidence_interval() -> ConfidenceInterval {
        ConfidenceInterval {
            level: DEFAULT_LEVEL,
            algorithm: ConfidenceIntervalAlgorithm::Bootstrap(Bootstrap::new()),
        }
    }

    pub(crate) const fn kind(&self) -> &ErrorBarKind {
        &self.0
    }
}

impl Default for ErrorBar {
    fn default() -> Self {
        Self::confidence_interval().into()
    }
}

/// Standard-deviation error-bar configuration.
#[derive(Debug, Clone, Copy)]
pub struct StandardDeviation {
    pub(crate) scale: f64,
}

impl StandardDeviation {
    /// Read the configured standard-deviation multiplier.
    #[must_use]
    pub const fn get_scale(&self) -> f64 {
        self.scale
    }

    /// Set the positive finite standard-deviation multiplier.
    pub fn scale(mut self, scale: f64) -> Result<Self, Error> {
        validate_positive_finite(scale, "standard-deviation scale")?;
        self.scale = scale;
        Ok(self)
    }
}

impl From<StandardDeviation> for ErrorBar {
    fn from(spec: StandardDeviation) -> Self {
        Self(ErrorBarKind::StandardDeviation(spec))
    }
}

/// Central percentile interval configuration for original observations.
#[derive(Debug, Clone, Copy)]
pub struct PercentileInterval {
    pub(crate) level: f64,
}

impl PercentileInterval {
    /// Read the configured central coverage fraction.
    #[must_use]
    pub const fn get_level(&self) -> f64 {
        self.level
    }

    /// Set coverage as a fraction strictly between zero and one.
    pub fn level(mut self, level: f64) -> Result<Self, Error> {
        validate_level(level)?;
        self.level = level;
        Ok(self)
    }
}

impl From<PercentileInterval> for ErrorBar {
    fn from(spec: PercentileInterval) -> Self {
        Self(ErrorBarKind::PercentileInterval(spec))
    }
}

/// Standard-error error-bar configuration.
#[derive(Debug, Clone, Copy)]
pub struct StandardError {
    pub(crate) scale: f64,
}

impl StandardError {
    /// Read the configured standard-error multiplier.
    #[must_use]
    pub const fn get_scale(&self) -> f64 {
        self.scale
    }

    /// Set the positive finite standard-error multiplier.
    pub fn scale(mut self, scale: f64) -> Result<Self, Error> {
        validate_positive_finite(scale, "standard-error scale")?;
        self.scale = scale;
        Ok(self)
    }
}

impl From<StandardError> for ErrorBar {
    fn from(spec: StandardError) -> Self {
        Self(ErrorBarKind::StandardError(spec))
    }
}

/// Two-sided confidence-interval configuration.
///
/// Algorithm selection is available only through [`Self::bootstrap`] and
/// [`Self::student_t`].
///
/// ```compile_fail
/// use lichtung_plot::ConfidenceIntervalAlgorithm;
/// ```
#[derive(Debug, Clone)]
pub struct ConfidenceInterval {
    pub(crate) level: f64,
    pub(crate) algorithm: ConfidenceIntervalAlgorithm,
}

impl ConfidenceInterval {
    /// Read the configured two-sided coverage fraction.
    #[must_use]
    pub const fn get_level(&self) -> f64 {
        self.level
    }

    /// Borrow the current bootstrap, or return `None` for a Student-t interval.
    #[must_use]
    pub const fn get_bootstrap(&self) -> Option<&Bootstrap> {
        match &self.algorithm {
            ConfidenceIntervalAlgorithm::Bootstrap(bootstrap) => Some(bootstrap),
            ConfidenceIntervalAlgorithm::StudentT => None,
        }
    }

    /// Set coverage as a fraction strictly between zero and one.
    pub fn level(mut self, level: f64) -> Result<Self, Error> {
        validate_level(level)?;
        self.level = level;
        Ok(self)
    }

    /// Select a percentile bootstrap with the supplied resampling specification.
    #[must_use]
    pub fn bootstrap(mut self, bootstrap: Bootstrap) -> Self {
        self.algorithm = ConfidenceIntervalAlgorithm::Bootstrap(bootstrap);
        self
    }

    /// Select an exact two-sided Student-t interval for the sample mean.
    #[must_use]
    pub fn student_t(mut self) -> Self {
        self.algorithm = ConfidenceIntervalAlgorithm::StudentT;
        self
    }
}

impl Default for ConfidenceInterval {
    fn default() -> Self {
        ErrorBar::confidence_interval()
    }
}

impl From<ConfidenceInterval> for ErrorBar {
    fn from(spec: ConfidenceInterval) -> Self {
        Self(ErrorBarKind::ConfidenceInterval(spec))
    }
}

/// Closed algorithm selection owned by a confidence interval.
#[derive(Debug, Clone)]
pub(crate) enum ConfidenceIntervalAlgorithm {
    /// Percentile bootstrap of resampled means.
    Bootstrap(Bootstrap),
    /// Exact Student-t interval around the sample mean.
    StudentT,
}

/// Percentile-bootstrap resampling specification.
#[derive(Debug, Clone)]
pub struct Bootstrap {
    pub(crate) resamples: usize,
    pub(crate) seed: u64,
    pub(crate) units: Option<CategoryValues>,
}

impl Bootstrap {
    /// Construct the default 1,000-resample, seed-zero bootstrap.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            resamples: DEFAULT_RESAMPLES,
            seed: 0,
            units: None,
        }
    }

    /// Read the configured number of resamples.
    #[must_use]
    pub const fn get_resamples(&self) -> usize {
        self.resamples
    }

    /// Read the configured deterministic root seed.
    #[must_use]
    pub const fn get_seed(&self) -> u64 {
        self.seed
    }

    /// Set the positive resample count, up to one million.
    pub fn resamples(mut self, resamples: usize) -> Result<Self, Error> {
        if !(1..=MAX_RESAMPLES).contains(&resamples) {
            return Err(Error::Data(
                format!(
                    "bootstrap resamples must be between 1 and {MAX_RESAMPLES}, got {resamples}"
                )
                .into(),
            ));
        }
        self.resamples = resamples;
        Ok(self)
    }

    /// Set the deterministic root seed.
    #[must_use]
    pub const fn seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    /// Set aligned sampling-unit identities for multilevel bootstrap resampling.
    #[must_use]
    pub fn units(mut self, units: CategoryValues) -> Self {
        self.units = Some(units);
        self
    }
}

impl Default for Bootstrap {
    fn default() -> Self {
        Self::new()
    }
}

fn validate_level(level: f64) -> Result<(), Error> {
    if !level.is_finite() || level <= 0.0 || level >= 1.0 {
        return Err(Error::Data(
            format!("error-bar level must be finite and strictly between 0 and 1, got {level}")
                .into(),
        ));
    }
    Ok(())
}

fn validate_positive_finite(value: f64, role: &str) -> Result<(), Error> {
    if !value.is_finite() || value <= 0.0 {
        return Err(Error::Data(
            format!("{role} must be finite and greater than zero, got {value}").into(),
        ));
    }
    Ok(())
}