Skip to main content

lichtung_plot/spec/
bar.rs

1//! Typed ordinary-bar inputs and generated error-bar specifications.
2
3use super::estimate::Bounds;
4use crate::{CategoryValues, Error, NumericValues};
5
6const DEFAULT_LEVEL: f64 = 0.95;
7const DEFAULT_RESAMPLES: usize = 1_000;
8const MAX_RESAMPLES: usize = 1_000_000;
9
10/// Closed owned input for an ordinary vertical or horizontal bar plot.
11#[derive(Debug, Clone)]
12pub struct BarInput {
13    pub(crate) source: BarSource,
14}
15
16#[derive(Debug, Clone)]
17pub(crate) enum BarSource {
18    Samples {
19        values: NumericValues,
20        error_bar: ErrorBar,
21    },
22    Estimates {
23        values: NumericValues,
24        bounds: Option<Bounds>,
25    },
26}
27
28impl BarInput {
29    /// Use raw observations, rendering each cell's arithmetic mean.
30    ///
31    /// The default error bar is a deterministic two-sided 95% percentile
32    /// bootstrap confidence interval with 1,000 resamples and seed zero.
33    #[must_use]
34    pub fn samples(values: NumericValues) -> BarSamples {
35        BarSamples {
36            values,
37            error_bar: ErrorBar::confidence_interval().into(),
38        }
39    }
40
41    /// Use one precomputed estimate per category, group, and facet cell.
42    #[must_use]
43    pub fn estimates(values: NumericValues) -> Self {
44        Self {
45            source: BarSource::Estimates {
46                values,
47                bounds: None,
48            },
49        }
50    }
51
52    /// Use one precomputed estimate and explicit drawable bounds per cell.
53    #[must_use]
54    pub fn estimates_with_error_bars(values: NumericValues, bounds: Bounds) -> Self {
55        Self {
56            source: BarSource::Estimates {
57                values,
58                bounds: Some(bounds),
59            },
60        }
61    }
62
63    pub(crate) const fn values(&self) -> &NumericValues {
64        match &self.source {
65            BarSource::Samples { values, .. } | BarSource::Estimates { values, .. } => values,
66        }
67    }
68
69    pub(crate) const fn bounds(&self) -> Option<&Bounds> {
70        match &self.source {
71            BarSource::Samples { .. } | BarSource::Estimates { bounds: None, .. } => None,
72            BarSource::Estimates {
73                bounds: Some(bounds),
74                ..
75            } => Some(bounds),
76        }
77    }
78
79    pub(crate) const fn error_bar(&self) -> Option<&ErrorBar> {
80        match &self.source {
81            BarSource::Samples { error_bar, .. } => Some(error_bar),
82            BarSource::Estimates { .. } => None,
83        }
84    }
85
86    pub(crate) const fn is_samples(&self) -> bool {
87        matches!(&self.source, BarSource::Samples { .. })
88    }
89}
90
91/// Raw bar samples with sample-only generated error-bar configuration.
92#[derive(Debug, Clone)]
93pub struct BarSamples {
94    values: NumericValues,
95    error_bar: ErrorBar,
96}
97
98impl BarSamples {
99    /// Replace the generated error-bar specification while retaining raw samples.
100    #[must_use]
101    pub fn error_bar(mut self, error_bar: impl Into<ErrorBar>) -> Self {
102        self.error_bar = error_bar.into();
103        self
104    }
105}
106
107impl From<BarSamples> for BarInput {
108    fn from(samples: BarSamples) -> Self {
109        Self {
110            source: BarSource::Samples {
111                values: samples.values,
112                error_bar: samples.error_bar,
113            },
114        }
115    }
116}
117
118/// Closed generated error-bar taxonomy for raw bar samples.
119#[derive(Debug, Clone)]
120pub struct ErrorBar(pub(crate) ErrorBarKind);
121
122#[derive(Debug, Clone)]
123pub(crate) enum ErrorBarKind {
124    Hidden,
125    StandardDeviation(StandardDeviation),
126    PercentileInterval(PercentileInterval),
127    StandardError(StandardError),
128    ConfidenceInterval(ConfidenceInterval),
129}
130
131impl ErrorBar {
132    /// Draw no generated error bar.
133    #[must_use]
134    pub const fn hidden() -> Self {
135        Self(ErrorBarKind::Hidden)
136    }
137
138    /// Configure sample standard-deviation error bars with scale one.
139    #[must_use]
140    pub const fn standard_deviation() -> StandardDeviation {
141        StandardDeviation { scale: 1.0 }
142    }
143
144    /// Configure a central percentile interval of the original observations.
145    #[must_use]
146    pub const fn percentile_interval() -> PercentileInterval {
147        PercentileInterval {
148            level: DEFAULT_LEVEL,
149        }
150    }
151
152    /// Configure sample standard-error bars with scale one.
153    #[must_use]
154    pub const fn standard_error() -> StandardError {
155        StandardError { scale: 1.0 }
156    }
157
158    /// Configure a two-sided confidence interval with the default bootstrap.
159    #[must_use]
160    pub const fn confidence_interval() -> ConfidenceInterval {
161        ConfidenceInterval {
162            level: DEFAULT_LEVEL,
163            algorithm: ConfidenceIntervalAlgorithm::Bootstrap(Bootstrap::new()),
164        }
165    }
166
167    pub(crate) const fn kind(&self) -> &ErrorBarKind {
168        &self.0
169    }
170}
171
172impl Default for ErrorBar {
173    fn default() -> Self {
174        Self::confidence_interval().into()
175    }
176}
177
178/// Standard-deviation error-bar configuration.
179#[derive(Debug, Clone, Copy)]
180pub struct StandardDeviation {
181    pub(crate) scale: f64,
182}
183
184impl StandardDeviation {
185    /// Read the configured standard-deviation multiplier.
186    #[must_use]
187    pub const fn get_scale(&self) -> f64 {
188        self.scale
189    }
190
191    /// Set the positive finite standard-deviation multiplier.
192    pub fn scale(mut self, scale: f64) -> Result<Self, Error> {
193        validate_positive_finite(scale, "standard-deviation scale")?;
194        self.scale = scale;
195        Ok(self)
196    }
197}
198
199impl From<StandardDeviation> for ErrorBar {
200    fn from(spec: StandardDeviation) -> Self {
201        Self(ErrorBarKind::StandardDeviation(spec))
202    }
203}
204
205/// Central percentile interval configuration for original observations.
206#[derive(Debug, Clone, Copy)]
207pub struct PercentileInterval {
208    pub(crate) level: f64,
209}
210
211impl PercentileInterval {
212    /// Read the configured central coverage fraction.
213    #[must_use]
214    pub const fn get_level(&self) -> f64 {
215        self.level
216    }
217
218    /// Set coverage as a fraction strictly between zero and one.
219    pub fn level(mut self, level: f64) -> Result<Self, Error> {
220        validate_level(level)?;
221        self.level = level;
222        Ok(self)
223    }
224}
225
226impl From<PercentileInterval> for ErrorBar {
227    fn from(spec: PercentileInterval) -> Self {
228        Self(ErrorBarKind::PercentileInterval(spec))
229    }
230}
231
232/// Standard-error error-bar configuration.
233#[derive(Debug, Clone, Copy)]
234pub struct StandardError {
235    pub(crate) scale: f64,
236}
237
238impl StandardError {
239    /// Read the configured standard-error multiplier.
240    #[must_use]
241    pub const fn get_scale(&self) -> f64 {
242        self.scale
243    }
244
245    /// Set the positive finite standard-error multiplier.
246    pub fn scale(mut self, scale: f64) -> Result<Self, Error> {
247        validate_positive_finite(scale, "standard-error scale")?;
248        self.scale = scale;
249        Ok(self)
250    }
251}
252
253impl From<StandardError> for ErrorBar {
254    fn from(spec: StandardError) -> Self {
255        Self(ErrorBarKind::StandardError(spec))
256    }
257}
258
259/// Two-sided confidence-interval configuration.
260///
261/// Algorithm selection is available only through [`Self::bootstrap`] and
262/// [`Self::student_t`].
263///
264/// ```compile_fail
265/// use lichtung_plot::ConfidenceIntervalAlgorithm;
266/// ```
267#[derive(Debug, Clone)]
268pub struct ConfidenceInterval {
269    pub(crate) level: f64,
270    pub(crate) algorithm: ConfidenceIntervalAlgorithm,
271}
272
273impl ConfidenceInterval {
274    /// Read the configured two-sided coverage fraction.
275    #[must_use]
276    pub const fn get_level(&self) -> f64 {
277        self.level
278    }
279
280    /// Borrow the current bootstrap, or return `None` for a Student-t interval.
281    #[must_use]
282    pub const fn get_bootstrap(&self) -> Option<&Bootstrap> {
283        match &self.algorithm {
284            ConfidenceIntervalAlgorithm::Bootstrap(bootstrap) => Some(bootstrap),
285            ConfidenceIntervalAlgorithm::StudentT => None,
286        }
287    }
288
289    /// Set coverage as a fraction strictly between zero and one.
290    pub fn level(mut self, level: f64) -> Result<Self, Error> {
291        validate_level(level)?;
292        self.level = level;
293        Ok(self)
294    }
295
296    /// Select a percentile bootstrap with the supplied resampling specification.
297    #[must_use]
298    pub fn bootstrap(mut self, bootstrap: Bootstrap) -> Self {
299        self.algorithm = ConfidenceIntervalAlgorithm::Bootstrap(bootstrap);
300        self
301    }
302
303    /// Select an exact two-sided Student-t interval for the sample mean.
304    #[must_use]
305    pub fn student_t(mut self) -> Self {
306        self.algorithm = ConfidenceIntervalAlgorithm::StudentT;
307        self
308    }
309}
310
311impl Default for ConfidenceInterval {
312    fn default() -> Self {
313        ErrorBar::confidence_interval()
314    }
315}
316
317impl From<ConfidenceInterval> for ErrorBar {
318    fn from(spec: ConfidenceInterval) -> Self {
319        Self(ErrorBarKind::ConfidenceInterval(spec))
320    }
321}
322
323/// Closed algorithm selection owned by a confidence interval.
324#[derive(Debug, Clone)]
325pub(crate) enum ConfidenceIntervalAlgorithm {
326    /// Percentile bootstrap of resampled means.
327    Bootstrap(Bootstrap),
328    /// Exact Student-t interval around the sample mean.
329    StudentT,
330}
331
332/// Percentile-bootstrap resampling specification.
333#[derive(Debug, Clone)]
334pub struct Bootstrap {
335    pub(crate) resamples: usize,
336    pub(crate) seed: u64,
337    pub(crate) units: Option<CategoryValues>,
338}
339
340impl Bootstrap {
341    /// Construct the default 1,000-resample, seed-zero bootstrap.
342    #[must_use]
343    pub const fn new() -> Self {
344        Self {
345            resamples: DEFAULT_RESAMPLES,
346            seed: 0,
347            units: None,
348        }
349    }
350
351    /// Read the configured number of resamples.
352    #[must_use]
353    pub const fn get_resamples(&self) -> usize {
354        self.resamples
355    }
356
357    /// Read the configured deterministic root seed.
358    #[must_use]
359    pub const fn get_seed(&self) -> u64 {
360        self.seed
361    }
362
363    /// Set the positive resample count, up to one million.
364    pub fn resamples(mut self, resamples: usize) -> Result<Self, Error> {
365        if !(1..=MAX_RESAMPLES).contains(&resamples) {
366            return Err(Error::Data(
367                format!(
368                    "bootstrap resamples must be between 1 and {MAX_RESAMPLES}, got {resamples}"
369                )
370                .into(),
371            ));
372        }
373        self.resamples = resamples;
374        Ok(self)
375    }
376
377    /// Set the deterministic root seed.
378    #[must_use]
379    pub const fn seed(mut self, seed: u64) -> Self {
380        self.seed = seed;
381        self
382    }
383
384    /// Set aligned sampling-unit identities for multilevel bootstrap resampling.
385    #[must_use]
386    pub fn units(mut self, units: CategoryValues) -> Self {
387        self.units = Some(units);
388        self
389    }
390}
391
392impl Default for Bootstrap {
393    fn default() -> Self {
394        Self::new()
395    }
396}
397
398fn validate_level(level: f64) -> Result<(), Error> {
399    if !level.is_finite() || level <= 0.0 || level >= 1.0 {
400        return Err(Error::Data(
401            format!("error-bar level must be finite and strictly between 0 and 1, got {level}")
402                .into(),
403        ));
404    }
405    Ok(())
406}
407
408fn validate_positive_finite(value: f64, role: &str) -> Result<(), Error> {
409    if !value.is_finite() || value <= 0.0 {
410        return Err(Error::Data(
411            format!("{role} must be finite and greater than zero, got {value}").into(),
412        ));
413    }
414    Ok(())
415}