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
use crate::{access, clone, tools::Range};
#[derive(Debug, Clone, PartialEq)]
pub struct Binner {
range: Range,
bins: u64,
}
impl Binner {
access!(range, Range);
clone!(bins, u64);
#[inline]
#[must_use]
pub fn new(range: Range, bins: u64) -> Self {
debug_assert!(bins > 0);
Self { range, bins }
}
#[inline]
#[must_use]
pub fn bin_width(&self) -> f64 {
self.range.width() / self.bins as f64
}
#[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
}
#[inline]
#[must_use]
pub fn try_bin(&self, x: f64) -> Option<usize> {
if self.range.contains(x) {
Some(self.bin(x))
} else {
None
}
}
}