Skip to main content

lichtung_plot/
geometry.rs

1//! Caller-computed columnar geometry accepted by distribution renderers.
2
3use crate::{CategoryValues, Error, NumericValues};
4
5mod histogram;
6mod raincloud;
7
8pub(crate) use histogram::validate_kde;
9
10/// Complete supplied raincloud geometry in three independently aligned domains.
11///
12/// Summary row order determines group order. Density and point rows name their
13/// summary group by raw category/hue strings and retain their relative order.
14#[derive(Debug, Clone)]
15pub struct RaincloudGeometry {
16    /// Scientific category dimension, also used for the inferred x-axis title.
17    pub category_dimension: String,
18    /// Scientific value dimension, also used for the inferred y-axis title.
19    pub value_dimension: String,
20    /// Scientific hue dimension; present together with all three hue columns.
21    pub hue_dimension: Option<String>,
22    /// One category per summary row.
23    pub category: CategoryValues,
24    /// One hue per summary row when hue is present.
25    pub hue: Option<CategoryValues>,
26    /// First quartiles aligned with summary categories.
27    pub q1: NumericValues,
28    /// Medians aligned with summary categories.
29    pub median: NumericValues,
30    /// Third quartiles aligned with summary categories.
31    pub q3: NumericValues,
32    /// Category keys for density rows.
33    pub density_category: CategoryValues,
34    /// Hue keys for density rows when hue is present.
35    pub density_hue: Option<CategoryValues>,
36    /// Density support coordinates, strictly increasing within each group.
37    pub density_y: NumericValues,
38    /// Density widths in the inclusive range `[0, 1]`.
39    pub normalized_width: NumericValues,
40    /// Category keys for raw-point rows.
41    pub point_category: CategoryValues,
42    /// Hue keys for raw-point rows when hue is present.
43    pub point_hue: Option<CategoryValues>,
44    /// Raw-point data-space coordinates.
45    pub point_y: NumericValues,
46    /// Raw-point strip coordinates in the inclusive range `[0, 1]`.
47    pub normalized_strip: NumericValues,
48}
49
50/// Complete supplied density-axis histogram geometry.
51///
52/// Bins, KDE and rugs are independent alignment domains. All components are
53/// required; the renderer never estimates missing supplied components.
54#[derive(Debug, Clone)]
55pub struct HistogramGeometry {
56    /// Scientific value dimension, also used for the inferred x-axis title.
57    pub value_dimension: String,
58    /// Scientific density dimension, also used for the inferred y-axis title.
59    pub density_dimension: String,
60    /// Lower bin edges in increasing, contiguous bin order.
61    pub bin_lower: NumericValues,
62    /// Upper bin edges aligned with lower edges.
63    pub bin_upper: NumericValues,
64    /// Nonnegative bin densities aligned with lower/upper edges.
65    pub bin_density: NumericValues,
66    /// Strictly increasing KDE coordinates within the bin support.
67    pub kde_x: NumericValues,
68    /// Nonnegative KDE densities aligned with KDE x.
69    pub kde_y: NumericValues,
70    /// Rug x coordinates in caller-supplied order, including duplicates.
71    pub rug_x: NumericValues,
72    /// Nonnegative rug baselines aligned with rug x.
73    pub rug_baseline: NumericValues,
74    /// Rug tops, strictly above their aligned baselines.
75    pub rug_top: NumericValues,
76}
77
78impl PartialEq for HistogramGeometry {
79    fn eq(&self, other: &Self) -> bool {
80        self.value_dimension == other.value_dimension
81            && self.density_dimension == other.density_dimension
82            && [
83                (&self.bin_lower, &other.bin_lower),
84                (&self.bin_upper, &other.bin_upper),
85                (&self.bin_density, &other.bin_density),
86                (&self.kde_x, &other.kde_x),
87                (&self.kde_y, &other.kde_y),
88                (&self.rug_x, &other.rug_x),
89                (&self.rug_baseline, &other.rug_baseline),
90                (&self.rug_top, &other.rug_top),
91            ]
92            .into_iter()
93            .all(|(left, right)| numeric_equal(left, right))
94    }
95}
96
97impl PartialEq for RaincloudGeometry {
98    fn eq(&self, other: &Self) -> bool {
99        self.category_dimension == other.category_dimension
100            && self.value_dimension == other.value_dimension
101            && self.hue_dimension == other.hue_dimension
102            && [
103                (&self.category, &other.category),
104                (&self.density_category, &other.density_category),
105                (&self.point_category, &other.point_category),
106            ]
107            .into_iter()
108            .all(|(left, right)| category_equal(left, right))
109            && [
110                (&self.hue, &other.hue),
111                (&self.density_hue, &other.density_hue),
112                (&self.point_hue, &other.point_hue),
113            ]
114            .into_iter()
115            .all(|(left, right)| match (left, right) {
116                (Some(left), Some(right)) => category_equal(left, right),
117                (None, None) => true,
118                _ => false,
119            })
120            && [
121                (&self.q1, &other.q1),
122                (&self.median, &other.median),
123                (&self.q3, &other.q3),
124                (&self.density_y, &other.density_y),
125                (&self.normalized_width, &other.normalized_width),
126                (&self.point_y, &other.point_y),
127                (&self.normalized_strip, &other.normalized_strip),
128            ]
129            .into_iter()
130            .all(|(left, right)| numeric_equal(left, right))
131    }
132}
133
134pub(crate) fn numeric_equal(left: &NumericValues, right: &NumericValues) -> bool {
135    left.name() == right.name()
136        && left.len() == right.len()
137        && (0..left.len()).all(|row| left.get(row) == right.get(row))
138}
139
140fn category_equal(left: &CategoryValues, right: &CategoryValues) -> bool {
141    left.name() == right.name()
142        && left.len() == right.len()
143        && (0..left.len()).all(|row| left.get(row) == right.get(row))
144}
145
146fn dimension(value: &str, role: &str) -> Result<(), Error> {
147    if value.trim().is_empty() {
148        Err(Error::Data(format!("{role} must be nonempty")))
149    } else {
150        Ok(())
151    }
152}
153
154fn aligned(domain: &str, expected: usize, columns: &[(&str, usize)]) -> Result<(), Error> {
155    for &(name, actual) in columns {
156        if actual != expected {
157            return Err(Error::Data(format!(
158                "{domain} column {name:?} has {actual} rows; expected {expected}"
159            )));
160        }
161    }
162    Ok(())
163}
164
165pub(crate) fn finite(values: &NumericValues, row: usize, role: &str) -> Result<f64, Error> {
166    values
167        .get(row)
168        .flatten()
169        .filter(|value| value.is_finite())
170        .ok_or_else(|| {
171            Error::Data(format!(
172                "{role} column {:?} requires a present finite value at row {row}",
173                values.name()
174            ))
175        })
176}
177
178pub(crate) fn category_value<'a>(
179    values: &'a CategoryValues,
180    row: usize,
181    role: &str,
182) -> Result<&'a str, Error> {
183    let value = values.get(row).flatten().ok_or_else(|| {
184        Error::Data(format!(
185            "{role} column {:?} has a missing key at row {row}",
186            values.name()
187        ))
188    })?;
189    dimension(value, role)?;
190    Ok(value)
191}
192
193#[cfg(test)]
194mod validation_tests;