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    pub(crate) fn authored_value_dimension(&self) -> Option<&str> {
146        self.value_dimension.as_deref()
147    }
148
149    pub(crate) fn authored_height_dimension(&self) -> Option<&str> {
150        self.height_dimension.as_deref()
151    }
152    /// Supply ordered, contiguous bin edges and their already computed heights.
153    ///
154    /// The declared statistic is the meaning of those heights. It is never
155    /// used to recompute them.
156    #[must_use]
157    pub fn bins(
158        lower: NumericValues,
159        upper: NumericValues,
160        height: NumericValues,
161        stat: HistogramStat,
162    ) -> Self {
163        Self {
164            bins: HistogramBinsData {
165                lower,
166                upper,
167                height,
168                stat,
169            },
170            kde: None,
171            rug: None,
172            value_dimension: None,
173            height_dimension: None,
174        }
175    }
176
177    /// Add or replace a supplied density curve.
178    #[must_use]
179    pub fn kde(mut self, x: NumericValues, density: NumericValues) -> Self {
180        self.set_kde(x, density);
181        self
182    }
183
184    pub(crate) fn set_kde(&mut self, x: NumericValues, density: NumericValues) {
185        self.kde = Some(HistogramKde::Precomputed { x, y: density });
186    }
187
188    /// Add or replace independently supplied rug segments.
189    #[must_use]
190    pub fn rug(mut self, x: NumericValues, baseline: NumericValues, top: NumericValues) -> Self {
191        self.set_rug(x, baseline, top);
192        self
193    }
194
195    pub(crate) fn set_rug(
196        &mut self,
197        x: NumericValues,
198        baseline: NumericValues,
199        top: NumericValues,
200    ) {
201        self.rug = Some(HistogramRugData { x, baseline, top });
202    }
203
204    /// Set the original scientific x dimension, independently of its display label.
205    #[must_use]
206    pub fn value_dimension(mut self, name: impl Into<String>) -> Self {
207        self.set_value_dimension(name.into());
208        self
209    }
210
211    pub(crate) fn set_value_dimension(&mut self, name: String) {
212        self.value_dimension = Some(name);
213    }
214
215    /// Set the original scientific height dimension, independently of its display label.
216    #[must_use]
217    pub fn height_dimension(mut self, name: impl Into<String>) -> Self {
218        self.set_height_dimension(name.into());
219        self
220    }
221
222    pub(crate) fn set_height_dimension(&mut self, name: String) {
223        self.height_dimension = Some(name);
224    }
225
226    /// Borrow the complete original bin declaration.
227    pub const fn get_bins(&self) -> &HistogramBinsData {
228        &self.bins
229    }
230
231    /// Borrow the actual precomputed curve, if supplied.
232    pub const fn get_kde(&self) -> Option<&HistogramKde> {
233        self.kde.as_ref()
234    }
235
236    /// Borrow the actual rug declaration, if supplied.
237    pub const fn get_rug(&self) -> Option<&HistogramRugData> {
238        self.rug.as_ref()
239    }
240
241    /// Resolve the scientific x dimension from its explicit name or the original rug x name.
242    pub fn get_value_dimension(&self) -> &str {
243        self.value_dimension.as_deref().unwrap_or_else(|| {
244            self.rug
245                .as_ref()
246                .map(|rug| rug.x.name())
247                .filter(|name| !name.trim().is_empty())
248                .unwrap_or("value")
249        })
250    }
251
252    /// Resolve the scientific y dimension from its explicit name or the original bin height name.
253    pub fn get_height_dimension(&self) -> &str {
254        self.height_dimension.as_deref().unwrap_or_else(|| {
255            let name = self.bins.height.name();
256            if name.trim().is_empty() {
257                self.bins.stat.name()
258            } else {
259                name
260            }
261        })
262    }
263
264    pub(crate) fn validate(&self) -> Result<(f64, f64), Error> {
265        dimension(self.get_value_dimension(), "histogram value dimension")?;
266        dimension(self.get_height_dimension(), "histogram height dimension")?;
267        let range = self.bins.validate()?;
268        if let Some(kde) = self.get_kde() {
269            if self.bins.stat != HistogramStat::Density {
270                return Err(Error::Data(
271                    "histogram: a supplied KDE density curve requires density bin heights".into(),
272                ));
273            }
274            let (x, y) = kde
275                .get_precomputed()
276                .expect("supplied curve always owns its columns");
277            validate_kde(x, y, range)?;
278        }
279        if let Some(rug) = self.get_rug() {
280            rug.validate(range)?;
281        }
282        Ok(range)
283    }
284}
285
286pub(crate) fn validate_kde(
287    x: &NumericValues,
288    y: &NumericValues,
289    range: (f64, f64),
290) -> Result<(), Error> {
291    aligned("histogram KDE", x.len(), &[("y", y.len())])?;
292    if x.len() < 2 {
293        return Err(Error::Data(
294            "histogram KDE: a precomputed curve requires at least two points".into(),
295        ));
296    }
297    if x.len() > MAX_KDE_POINTS {
298        return Err(Error::Data(
299            format!("histogram supplied KDE exceeds its {MAX_KDE_POINTS} point limit").into(),
300        ));
301    }
302    let mut previous = None;
303    let mut positive = false;
304    for row in 0..x.len() {
305        let x = finite(x, row, "histogram KDE finite x")?;
306        let y = finite(y, row, "histogram KDE nonnegative finite density")?;
307        if y < 0.0 {
308            return Err(Error::Data(
309                format!(
310                    "histogram KDE: precomputed point {row} requires nonnegative finite density"
311                )
312                .into(),
313            ));
314        }
315        if !(range.0..=range.1).contains(&x) {
316            return Err(Error::Data(format!("histogram KDE: precomputed x {x} at point {row} lies outside histogram bin range {}..{}", range.0, range.1).into()));
317        }
318        if previous.is_some_and(|previous| x <= previous) {
319            return Err(Error::Data(
320                "histogram KDE: precomputed x values must be strictly increasing".into(),
321            ));
322        }
323        previous = Some(x);
324        positive |= y > 0.0;
325    }
326    if !positive {
327        return Err(Error::Data(
328            "histogram KDE: a precomputed density curve must contain a positive density".into(),
329        ));
330    }
331    Ok(())
332}
333
334pub(crate) fn validate_rug_count(count: usize) -> Result<(), Error> {
335    if count == 0 || count > MAX_RUGS {
336        return Err(Error::Data(
337            format!("histogram rug requires 1..={MAX_RUGS} segments").into(),
338        ));
339    }
340    Ok(())
341}