ndhistogram/axis/
variablenoflow.rs

1use crate::error::AxisError;
2
3use super::{Axis, BinInterval, Variable};
4
5use std::fmt::{Debug, Display};
6
7/// An axis with variable sized bins and no overflow bins.
8///
9/// An axis with variable sized bins constructed with a list of bin edges.
10/// This axis has (num edges - 1) bins.
11///
12/// For floating point types, infinities and NaN do not map to any bin.
13///
14/// # Example
15/// Create a 1D histogram with 3 variable width bins between 0.0 and 7.0.
16/// ```rust
17///    use ndhistogram::{ndhistogram, Histogram};
18///    use ndhistogram::axis::{Axis, VariableNoFlow};
19///    # fn main() -> Result<(), ndhistogram::Error> {
20///    let mut hist = ndhistogram!(VariableNoFlow::new(vec![0.0, 1.0, 3.0, 7.0])?; i32);
21///    hist.fill(&-1.0); // will be ignored as there is no underflow bin
22///    hist.fill(&1.0);
23///    hist.fill(&2.0);
24///    assert_eq!(
25///        hist.values().copied().collect::<Vec<_>>(),
26///        vec![0, 2, 0],
27///    );
28///    # Ok(()) }
29/// ```
30#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct VariableNoFlow<T = f64> {
33    axis: Variable<T>,
34}
35
36impl<T: PartialOrd + Copy> VariableNoFlow<T> {
37    /// Factory method to create an variable binning from a set of bin edges with no under/overflow bins.
38    /// See the documentation for [Variable::new].
39    ///
40    /// The parameters must satify the same constraints as [Variable::new], otherwise an error is returned.
41    pub fn new<I: IntoIterator<Item = T>>(bin_edges: I) -> Result<Self, AxisError> {
42        Ok(Self {
43            axis: Variable::new(bin_edges)?,
44        })
45    }
46
47    /// Return the lowest bin edge.
48    pub fn low(&self) -> &T {
49        self.axis.low()
50    }
51
52    /// Return the highest bin edge.
53    pub fn high(&self) -> &T {
54        self.axis.high()
55    }
56}
57
58impl<T: PartialOrd + Copy> Axis for VariableNoFlow<T> {
59    type Coordinate = T;
60    type BinInterval = BinInterval<T>;
61
62    #[inline]
63    fn index(&self, coordinate: &Self::Coordinate) -> Option<usize> {
64        let index = self.axis.index(coordinate)?;
65        if index == 0 || index + 1 == self.axis.num_bins() {
66            return None;
67        }
68        Some(index - 1)
69    }
70
71    fn num_bins(&self) -> usize {
72        self.axis.num_bins() - 2
73    }
74
75    fn bin(&self, index: usize) -> Option<Self::BinInterval> {
76        let bin = self.axis.bin(index + 1)?;
77        match bin {
78            BinInterval::Underflow { end: _ } => None,
79            BinInterval::Overflow { start: _ } => None,
80            BinInterval::Bin { start: _, end: _ } => Some(bin),
81        }
82    }
83}
84
85impl<'a, T: PartialOrd + Copy> IntoIterator for &'a VariableNoFlow<T> {
86    type Item = (usize, <VariableNoFlow<T> as Axis>::BinInterval);
87    type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
88
89    fn into_iter(self) -> Self::IntoIter {
90        self.iter()
91    }
92}
93
94impl<T: PartialOrd + Copy + Display> Display for VariableNoFlow<T>
95where
96    Self: Axis,
97{
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        write!(
100            f,
101            "Axis{{# bins={}, range=[{}, {}), class={}}}",
102            self.num_bins(),
103            self.axis.low(),
104            self.axis.high(),
105            stringify!(VariableNoFlow)
106        )
107    }
108}