Skip to main content

lichtung_plot/geometry/
histogram.rs

1use super::{aligned, dimension, finite};
2use crate::{plots::HistogramKde, stats::HistogramStat, Error, NumericValues};
3
4const MAX_BINS: usize = 1_000_000;
5const MAX_KDE_POINTS: usize = 2_048;
6const MAX_RUGS: usize = 1_000_000;
7
8/// The caller's aligned histogram bin edges and heights, in supplied order.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct HistogramBinsData {
11    lower: NumericValues,
12    upper: NumericValues,
13    height: NumericValues,
14    stat: HistogramStat,
15}
16
17impl HistogramBinsData {
18    /// Original lower bin edges.
19    pub const fn bin_lower(&self) -> &NumericValues {
20        &self.lower
21    }
22
23    /// Original upper bin edges.
24    pub const fn bin_upper(&self) -> &NumericValues {
25        &self.upper
26    }
27
28    /// Original bin heights, without any computed normalization.
29    pub const fn bin_height(&self) -> &NumericValues {
30        &self.height
31    }
32
33    /// Scientific meaning of the supplied heights.
34    pub const fn bin_stat(&self) -> HistogramStat {
35        self.stat
36    }
37
38    fn validate(&self) -> Result<(f64, f64), Error> {
39        aligned(
40            "histogram bins",
41            self.lower.len(),
42            &[
43                ("bin_upper", self.upper.len()),
44                ("bin_height", self.height.len()),
45            ],
46        )?;
47        if self.lower.is_empty() || self.lower.len() > MAX_BINS {
48            return Err(Error::Data(
49                format!("histogram geometry requires 1..={MAX_BINS} bins").into(),
50            ));
51        }
52        let mut previous = None;
53        for row in 0..self.lower.len() {
54            let lower = finite(&self.lower, row, "histogram bin lower")?;
55            let upper = finite(&self.upper, row, "histogram bin upper")?;
56            let height = finite(&self.height, row, "histogram bin height")?;
57            if lower >= upper || height < 0.0 {
58                return Err(Error::Data(
59                    format!("histogram bin {row} requires lower < upper and nonnegative height")
60                        .into(),
61                ));
62            }
63            if previous.is_some_and(|previous| {
64                lower.partial_cmp(&previous) != Some(std::cmp::Ordering::Equal)
65            }) {
66                return Err(Error::Data(
67                    format!("histogram bins must be ordered and contiguous at bin {row}").into(),
68                ));
69            }
70            previous = Some(upper);
71        }
72        Ok((
73            finite(&self.lower, 0, "histogram bin lower")?,
74            finite(&self.upper, self.upper.len() - 1, "histogram bin upper")?,
75        ))
76    }
77}
78
79/// Supplied rug geometry in its own observation domain.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct HistogramRugData {
82    x: NumericValues,
83    baseline: NumericValues,
84    top: NumericValues,
85}
86
87impl HistogramRugData {
88    /// Original positions, including repeats.
89    pub const fn rug_x(&self) -> &NumericValues {
90        &self.x
91    }
92
93    /// Original segment baselines.
94    pub const fn rug_baseline(&self) -> &NumericValues {
95        &self.baseline
96    }
97
98    /// Original segment tops.
99    pub const fn rug_top(&self) -> &NumericValues {
100        &self.top
101    }
102
103    fn validate(&self, range: (f64, f64)) -> Result<(), Error> {
104        aligned(
105            "histogram rug",
106            self.x.len(),
107            &[
108                ("rug_baseline", self.baseline.len()),
109                ("rug_top", self.top.len()),
110            ],
111        )?;
112        validate_rug_count(self.x.len())?;
113        for row in 0..self.x.len() {
114            let x = finite(&self.x, row, "histogram rug x")?;
115            let baseline = finite(&self.baseline, row, "histogram rug baseline")?;
116            let top = finite(&self.top, row, "histogram rug top")?;
117            if !(range.0..=range.1).contains(&x) || baseline < 0.0 || baseline >= top {
118                return Err(Error::Data(
119                    format!(
120                        "histogram rug {row} requires x within bin support and 0 <= baseline < top"
121                    )
122                    .into(),
123                ));
124            }
125        }
126        Ok(())
127    }
128}
129
130/// Caller-computed histogram bins, with independently optional KDE and rug.
131///
132/// Each component owns its original columns in its own alignment domain.
133/// Scientific validation occurs at preparation; no component is estimated,
134/// normalized or borrowed from another domain.
135#[derive(Debug, Clone, PartialEq)]
136pub struct HistogramGeometry {
137    bins: HistogramBinsData,
138    kde: Option<HistogramKde>,
139    rug: Option<HistogramRugData>,
140    value_dimension: Option<String>,
141    height_dimension: Option<String>,
142}
143
144impl HistogramGeometry {
145    /// Supply ordered, contiguous bin edges and their already computed heights.
146    ///
147    /// The declared statistic is the meaning of those heights. It is never
148    /// used to recompute them.
149    #[must_use]
150    pub fn bins(
151        lower: NumericValues,
152        upper: NumericValues,
153        height: NumericValues,
154        stat: HistogramStat,
155    ) -> Self {
156        Self {
157            bins: HistogramBinsData {
158                lower,
159                upper,
160                height,
161                stat,
162            },
163            kde: None,
164            rug: None,
165            value_dimension: None,
166            height_dimension: None,
167        }
168    }
169
170    /// Add or replace a supplied density curve.
171    #[must_use]
172    pub fn kde(mut self, x: NumericValues, density: NumericValues) -> Self {
173        self.set_kde(x, density);
174        self
175    }
176
177    pub(crate) fn set_kde(&mut self, x: NumericValues, density: NumericValues) {
178        self.kde = Some(HistogramKde::Precomputed { x, y: density });
179    }
180
181    /// Add or replace independently supplied rug segments.
182    #[must_use]
183    pub fn rug(mut self, x: NumericValues, baseline: NumericValues, top: NumericValues) -> Self {
184        self.set_rug(x, baseline, top);
185        self
186    }
187
188    pub(crate) fn set_rug(
189        &mut self,
190        x: NumericValues,
191        baseline: NumericValues,
192        top: NumericValues,
193    ) {
194        self.rug = Some(HistogramRugData { x, baseline, top });
195    }
196
197    /// Set the original scientific x dimension, independently of its display label.
198    #[must_use]
199    pub fn value_dimension(mut self, name: impl Into<String>) -> Self {
200        self.set_value_dimension(name.into());
201        self
202    }
203
204    pub(crate) fn set_value_dimension(&mut self, name: String) {
205        self.value_dimension = Some(name);
206    }
207
208    /// Set the original scientific height dimension, independently of its display label.
209    #[must_use]
210    pub fn height_dimension(mut self, name: impl Into<String>) -> Self {
211        self.set_height_dimension(name.into());
212        self
213    }
214
215    pub(crate) fn set_height_dimension(&mut self, name: String) {
216        self.height_dimension = Some(name);
217    }
218
219    /// Borrow the complete original bin declaration.
220    pub const fn get_bins(&self) -> &HistogramBinsData {
221        &self.bins
222    }
223
224    /// Borrow the actual precomputed curve, if supplied.
225    pub const fn get_kde(&self) -> Option<&HistogramKde> {
226        self.kde.as_ref()
227    }
228
229    /// Borrow the actual rug declaration, if supplied.
230    pub const fn get_rug(&self) -> Option<&HistogramRugData> {
231        self.rug.as_ref()
232    }
233
234    /// Resolve the scientific x dimension from its explicit name or the original rug x name.
235    pub fn get_value_dimension(&self) -> &str {
236        self.value_dimension.as_deref().unwrap_or_else(|| {
237            self.rug
238                .as_ref()
239                .map(|rug| rug.x.name())
240                .filter(|name| !name.trim().is_empty())
241                .unwrap_or("value")
242        })
243    }
244
245    /// Resolve the scientific y dimension from its explicit name or the original bin height name.
246    pub fn get_height_dimension(&self) -> &str {
247        self.height_dimension.as_deref().unwrap_or_else(|| {
248            let name = self.bins.height.name();
249            if name.trim().is_empty() {
250                self.bins.stat.name()
251            } else {
252                name
253            }
254        })
255    }
256
257    pub(crate) fn validate(&self) -> Result<(f64, f64), Error> {
258        dimension(self.get_value_dimension(), "histogram value dimension")?;
259        dimension(self.get_height_dimension(), "histogram height dimension")?;
260        let range = self.bins.validate()?;
261        if let Some(kde) = self.get_kde() {
262            if self.bins.stat != HistogramStat::Density {
263                return Err(Error::Data(
264                    "histogram: a supplied KDE density curve requires density bin heights".into(),
265                ));
266            }
267            let (x, y) = kde
268                .get_precomputed()
269                .expect("supplied curve always owns its columns");
270            validate_kde(x, y, range)?;
271        }
272        if let Some(rug) = self.get_rug() {
273            rug.validate(range)?;
274        }
275        Ok(range)
276    }
277}
278
279pub(crate) fn validate_kde(
280    x: &NumericValues,
281    y: &NumericValues,
282    range: (f64, f64),
283) -> Result<(), Error> {
284    aligned("histogram KDE", x.len(), &[("y", y.len())])?;
285    if x.len() < 2 {
286        return Err(Error::Data(
287            "histogram KDE: a precomputed curve requires at least two points".into(),
288        ));
289    }
290    if x.len() > MAX_KDE_POINTS {
291        return Err(Error::Data(
292            format!("histogram supplied KDE exceeds its {MAX_KDE_POINTS} point limit").into(),
293        ));
294    }
295    let mut previous = None;
296    let mut positive = false;
297    for row in 0..x.len() {
298        let x = finite(x, row, "histogram KDE finite x")?;
299        let y = finite(y, row, "histogram KDE nonnegative finite density")?;
300        if y < 0.0 {
301            return Err(Error::Data(
302                format!(
303                    "histogram KDE: precomputed point {row} requires nonnegative finite density"
304                )
305                .into(),
306            ));
307        }
308        if !(range.0..=range.1).contains(&x) {
309            return Err(Error::Data(format!("histogram KDE: precomputed x {x} at point {row} lies outside histogram bin range {}..{}", range.0, range.1).into()));
310        }
311        if previous.is_some_and(|previous| x <= previous) {
312            return Err(Error::Data(
313                "histogram KDE: precomputed x values must be strictly increasing".into(),
314            ));
315        }
316        previous = Some(x);
317        positive |= y > 0.0;
318    }
319    if !positive {
320        return Err(Error::Data(
321            "histogram KDE: a precomputed density curve must contain a positive density".into(),
322        ));
323    }
324    Ok(())
325}
326
327pub(crate) fn validate_rug_count(count: usize) -> Result<(), Error> {
328    if count == 0 || count > MAX_RUGS {
329        return Err(Error::Data(
330            format!("histogram rug requires 1..={MAX_RUGS} segments").into(),
331        ));
332    }
333    Ok(())
334}