1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//! Binner implementation.

use crate::{access, clone, tools::Range};

/// One-dimensional binning structure.
#[derive(Debug, Clone, PartialEq)]
pub struct Binner {
    /// Range.
    range: Range,
    /// Total number of bins.
    bins: u64,
}

impl Binner {
    access!(range, Range);
    clone!(bins, u64);

    /// Construct a new Range.
    #[inline]
    #[must_use]
    pub fn new(range: Range, bins: u64) -> Self {
        debug_assert!(bins > 0);

        Self { range, bins }
    }

    /// Calculate the bin width.
    #[inline]
    #[must_use]
    pub fn bin_width(&self) -> f64 {
        self.range.width() / self.bins as f64
    }

    /// Determine the corresponding bin.
    #[inline]
    #[must_use]
    pub fn bin(&self, x: f64) -> usize {
        debug_assert!(self.range.contains(x));

        let frac = (x - self.range.min()) / self.range.width();
        let bin = (frac * self.bins as f64).floor() as u64;
        bin.min(self.bins - 1) as usize
    }

    /// Determine the corresponding bin if the value is within the range.
    #[inline]
    #[must_use]
    pub fn try_bin(&self, x: f64) -> Option<usize> {
        if self.range.contains(x) {
            Some(self.bin(x))
        } else {
            None
        }
    }
}