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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
use std::fmt::Display;
use super::{Axis, BinInterval};
use serde::{Deserialize, Serialize};
#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]
pub struct Variable<T = f64> {
bin_edges: Vec<T>,
}
impl<T> Variable<T>
where
T: PartialOrd + Copy,
{
pub fn new<I: IntoIterator<Item = T>>(bin_edges: I) -> Self {
let mut bin_edges: Vec<T> = bin_edges.into_iter().collect();
if bin_edges.len() < 2 {
panic!("Invalid axis number of bin edges ({})", bin_edges.len());
}
bin_edges.sort_by(|a, b| a.partial_cmp(b).expect("failed to sort bin_edges."));
Self { bin_edges }
}
pub fn low(&self) -> &T {
self.bin_edges
.first()
.expect("Variable bin_edges unexpectedly empty")
}
pub fn high(&self) -> &T {
self.bin_edges
.last()
.expect("Variable bin_edges unexpectedly empty")
}
}
impl<T> Axis for Variable<T>
where
T: PartialOrd + Copy,
{
type Coordinate = T;
type BinInterval = BinInterval<T>;
#[inline]
fn index(&self, coordinate: &Self::Coordinate) -> Option<usize> {
match self.bin_edges.binary_search_by(|probe| {
probe
.partial_cmp(coordinate)
.expect("incomparable values. NAN bin edges?")
}) {
Ok(index) => Some(index + 1),
Err(index) => Some(index),
}
}
fn num_bins(&self) -> usize {
self.bin_edges.len() + 1
}
fn bin(&self, index: usize) -> Option<Self::BinInterval> {
if index == 0 {
Some(Self::BinInterval::underflow(*self.low()))
} else if index == self.bin_edges.len() {
Some(Self::BinInterval::overflow(*self.high()))
} else if index < self.bin_edges.len() {
Some(Self::BinInterval::new(
self.bin_edges[index - 1],
self.bin_edges[index],
))
} else {
None
}
}
}
impl<T: Display + PartialOrd + Copy> Display for Variable<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Axis{{# bins={}, range=[{}, {}), class={}}}",
self.bin_edges.len() - 1,
self.low(),
self.high(),
stringify!(Variable)
)
}
}
impl<'a, T> IntoIterator for &'a Variable<T>
where
Variable<T>: Axis,
{
type Item = (usize, <Variable<T> as Axis>::BinInterval);
type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}