ndhistogram/axis/
variable.rs

1use std::{cmp::Ordering, fmt::Display};
2
3use crate::error::AxisError;
4
5use super::{Axis, BinInterval};
6
7/// An axis with variable sized bins.
8///
9/// An axis with variable sized bins.
10/// Constructed with a list of bin edges.
11/// Beyond the lowest (highest) bin edges is an underflow (overflow) bin.
12/// Hence this axis has num edges + 1 bins.
13///
14/// For floating point types, positive and negative infinities map to overflow
15/// and underflow bins respectively. NaN map to the overflow bin.
16///
17/// # Example
18/// Create a 1D histogram with 3 variable width bins between 0.0 and 7.0, plus overflow and underflow bins.
19/// ```rust
20///    use ndhistogram::{ndhistogram, Histogram};
21///    use ndhistogram::axis::{Axis, Variable, BinInterval};
22///    # fn main() -> Result<(), ndhistogram::Error> {
23///    let mut hist = ndhistogram!(Variable::new(vec![0.0, 1.0, 3.0, 7.0])?; i32);
24///    hist.fill(&0.0);
25///    hist.fill(&1.0);
26///    hist.fill(&2.0);
27///    assert_eq!(
28///        hist.values().copied().collect::<Vec<_>>(),
29///        vec![0, 1, 2, 0, 0],
30///    );
31///    # Ok(()) }
32/// ```
33#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
35pub struct Variable<T = f64> {
36    bin_edges: Vec<T>,
37}
38
39impl<T> Variable<T>
40where
41    T: PartialOrd + Copy,
42{
43    /// Factory method to create an axis with [Variable] binning given a set of bin edges.
44    ///
45    /// If less than 2 edges are provided or if it fails to sort the
46    /// bin edges (for example if a NAN value is given), an error is returned.
47    pub fn new<I: IntoIterator<Item = T>>(bin_edges: I) -> Result<Self, AxisError> {
48        let mut bin_edges: Vec<T> = bin_edges.into_iter().collect();
49        if bin_edges.len() < 2 {
50            return Err(AxisError::InvalidNumberOfBinEdges);
51        }
52        let mut sort_failed = false;
53        bin_edges.sort_by(|a, b| {
54            a.partial_cmp(b).unwrap_or_else(|| {
55                sort_failed = true;
56                Ordering::Less
57            })
58        });
59        if sort_failed {
60            return Err(AxisError::FailedToSortBinEdges);
61        }
62        Ok(Self { bin_edges })
63    }
64
65    /// Low edge of axis (excluding underflow bin).
66    pub fn low(&self) -> &T {
67        self.bin_edges
68            .first()
69            .expect("Variable bin_edges can never be empty as new returns an error if it is")
70    }
71
72    /// High edge of axis (excluding overflow bin).
73    pub fn high(&self) -> &T {
74        self.bin_edges
75            .last()
76            .expect("Variable bin_edges can never be empty as new returns an error if it is")
77    }
78}
79
80impl<T> Axis for Variable<T>
81where
82    T: PartialOrd + Copy,
83{
84    type Coordinate = T;
85    type BinInterval = BinInterval<T>;
86
87    #[inline]
88    fn index(&self, coordinate: &Self::Coordinate) -> Option<usize> {
89        let search_result = self.bin_edges.binary_search_by(|probe| {
90            probe
91                .partial_cmp(coordinate)
92                .unwrap_or(std::cmp::Ordering::Less)
93        });
94        match search_result {
95            Ok(index) => Some(index + 1),
96            Err(index) => Some(index),
97        }
98    }
99
100    fn num_bins(&self) -> usize {
101        self.bin_edges.len() + 1
102    }
103
104    fn bin(&self, index: usize) -> Option<Self::BinInterval> {
105        if index == 0 {
106            Some(Self::BinInterval::underflow(*self.low()))
107        } else if index == self.bin_edges.len() {
108            Some(Self::BinInterval::overflow(*self.high()))
109        } else if index < self.bin_edges.len() {
110            Some(Self::BinInterval::new(
111                self.bin_edges[index - 1],
112                self.bin_edges[index],
113            ))
114        } else {
115            None
116        }
117    }
118}
119
120impl<T: Display + PartialOrd + Copy> Display for Variable<T> {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        write!(
123            f,
124            "Axis{{# bins={}, range=[{}, {}), class={}}}",
125            self.bin_edges.len() - 1,
126            self.low(),
127            self.high(),
128            stringify!(Variable)
129        )
130    }
131}
132
133impl<'a, T> IntoIterator for &'a Variable<T>
134where
135    Variable<T>: Axis,
136{
137    type Item = (usize, <Variable<T> as Axis>::BinInterval);
138    type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
139
140    fn into_iter(self) -> Self::IntoIter {
141        self.iter()
142    }
143}