1use std::{
2 cmp::Ordering,
3 fmt::Display,
4 ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign},
5};
6
7use crate::axis::Axis;
8
9use super::histogram::{Histogram, Item, Iter, IterMut, ValuesMut};
10
11#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct VecHistogram<A, V> {
17 axes: A,
18 values: Vec<V>,
19}
20
21impl<A: Axis, V: Default + Clone> VecHistogram<A, V> {
22 pub fn new(axes: A) -> Self {
25 let size = axes.num_bins();
26 Self {
27 axes,
28 values: vec![V::default(); size],
29 }
30 }
31}
32
33impl<A: Axis, V> Histogram<A, V> for VecHistogram<A, V> {
34 fn value(&self, coordinate: &A::Coordinate) -> Option<&V> {
35 let index = self.axes.index(coordinate)?;
36 self.values.get(index)
37 }
38
39 #[inline]
40 fn axes(&self) -> &A {
41 &self.axes
42 }
43
44 fn value_at_index(&self, index: usize) -> Option<&V> {
45 self.values.get(index)
46 }
47
48 fn values<'a>(&'a self) -> Box<dyn Iterator<Item = &'a V> + 'a> {
49 Box::new(self.values.iter())
50 }
51
52 fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = Item<A::BinInterval, &'a V>> + 'a> {
53 Box::new(self.axes().iter().map(move |(index, binrange)| {
54 Item {
55 index,
56 bin: binrange,
57 value: self
58 .value_at_index(index)
59 .expect("iter() indices are always in range"),
60 }
61 }))
62 }
63
64 fn value_at_index_mut(&mut self, index: usize) -> Option<&mut V> {
65 self.values.get_mut(index)
66 }
67
68 fn values_mut(&mut self) -> ValuesMut<'_, V> {
69 Box::new(self.values.iter_mut())
70 }
71
72 fn iter_mut(&mut self) -> IterMut<'_, A, V> {
73 Box::new(
74 self.axes
75 .iter()
76 .zip(self.values.iter_mut())
77 .map(|((index, bin), value)| Item { index, bin, value }),
78 )
79 }
80}
81
82impl<'a, A: Axis, V> IntoIterator for &'a VecHistogram<A, V> {
83 type Item = Item<A::BinInterval, &'a V>;
84
85 type IntoIter = Iter<'a, A, V>;
86
87 fn into_iter(self) -> Self::IntoIter {
88 self.iter()
89 }
90}
91
92impl<'a, A: Axis, V: 'a> IntoIterator for &'a mut VecHistogram<A, V> {
93 type Item = Item<A::BinInterval, &'a mut V>;
94
95 type IntoIter = IterMut<'a, A, V>;
96
97 fn into_iter(self) -> Self::IntoIter {
98 self.iter_mut()
99 }
100}
101
102impl<A: Axis, V> Display for VecHistogram<A, V>
103where
104 V: Clone + Into<f64>,
105 A::BinInterval: Display,
106{
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 let precision = f.precision().unwrap_or(2);
109
110 let sum = self
111 .values()
112 .map(|it| {
113 let x: f64 = it.clone().into();
114 x
115 })
116 .fold(0.0, |it, value| it + value);
117 write!(
118 f,
119 "VecHistogram{}D({} bins, sum={})",
120 self.axes().num_dim(),
121 self.axes().num_bins(),
122 sum
123 )?;
124 let values: Vec<_> = self
125 .iter()
126 .take(50)
127 .map(|item| {
128 (item.bin, {
129 let x: f64 = item.value.clone().into();
130 x
131 })
132 })
133 .collect();
134 let scale = values
135 .iter()
136 .max_by(|l, r| l.1.partial_cmp(&r.1).unwrap_or(Ordering::Less))
137 .map(|it| it.1)
138 .unwrap_or(f64::INFINITY);
139 values
140 .into_iter()
141 .map(|(bin, value)| (bin, 50.0 * (value / scale)))
142 .map(|(bin, value)| (format!("{bin:.precision$}"), "#".repeat(value as usize)))
143 .map(|(bin, value)| write!(f, "\n{bin:>16} | {value}"))
144 .filter_map(Result::ok)
145 .count();
146 Ok(())
147 }
148}
149
150macro_rules! impl_binary_op_with_immutable_borrow {
151 ($Trait:tt, $method:tt, $mathsymbol:tt, $testresult:tt) => {
152 impl<A: Axis + PartialEq + Clone, V> $Trait<&VecHistogram<A, V>> for &VecHistogram<A, V>
153where
154 for<'a> &'a V: $Trait<Output = V>,
155{
156 type Output = Result<VecHistogram<A, V>, crate::error::BinaryOperationError>;
157
158 #[doc=concat!("let combined_hist = (&hist1 ", stringify!($mathsymbol), " &hist2).expect(\"Axes are compatible\");")]
174 #[doc=concat!("assert_eq!(combined_hist.value(&0.0).unwrap(), &", stringify!($testresult), ");")]
175 fn $method(self, rhs: &VecHistogram<A, V>) -> Self::Output {
178 if self.axes() != rhs.axes() {
179 return Err(crate::error::BinaryOperationError);
180 }
181 let values = self
182 .values
183 .iter()
184 .zip(rhs.values.iter())
185 .map(|(l, r)| l $mathsymbol r)
186 .collect();
187 Ok(VecHistogram {
188 axes: self.axes().clone(),
189 values,
190 })
191 }
192}
193 };
194}
195
196impl_binary_op_with_immutable_borrow! {Add, add, +, 3.0}
197impl_binary_op_with_immutable_borrow! {Sub, sub, -, 1.0}
198impl_binary_op_with_immutable_borrow! {Mul, mul, *, 2.0}
199impl_binary_op_with_immutable_borrow! {Div, div, /, 2.0}
200
201macro_rules! impl_binary_op_with_scalar {
202 ($Trait:tt, $method:tt, $mathsymbol:tt) => {
203 impl<A: Axis + PartialEq + Clone, V> $Trait<&V> for &VecHistogram<A, V>
204where
205 for<'a> &'a V: $Trait<Output = V>,
206{
207 type Output = VecHistogram<A, V>;
208
209 fn $method(self, rhs: &V) -> Self::Output {
210 let values = self
211 .values
212 .iter()
213 .map(|l| l $mathsymbol rhs)
214 .collect();
215 VecHistogram {
216 axes: self.axes().clone(),
217 values,
218 }
219 }
220}
221 };
222}
223
224impl_binary_op_with_scalar! {Add, add, +}
225impl_binary_op_with_scalar! {Sub, sub, -}
226impl_binary_op_with_scalar! {Mul, mul, *}
227impl_binary_op_with_scalar! {Div, div, /}
228
229macro_rules! impl_binary_op_with_owned {
230 ($Trait:tt, $method:tt, $ValueAssignTrait:tt, $mathsymbol:tt, $assignmathsymbol:tt, $testresult:tt) => {
231 impl<A: Axis + PartialEq, V> $Trait<&VecHistogram<A, V>> for VecHistogram<A, V>
232 where
233 for<'a> V: $ValueAssignTrait<&'a V>,
234 {
235 type Output = Result<VecHistogram<A, V>, crate::error::BinaryOperationError>;
236
237 #[doc=concat!("let combined_hist = (hist1 ", stringify!($mathsymbol), " &hist2).expect(\"Axes are compatible\");")]
255 #[doc=concat!("assert_eq!(combined_hist.value(&0.0).unwrap(), &", stringify!($testresult), ");")]
256 fn $method(mut self, rhs: &VecHistogram<A, V>) -> Self::Output {
259 if self.axes() != rhs.axes() {
260 return Err(crate::error::BinaryOperationError);
261 }
262 self.values
263 .iter_mut()
264 .zip(rhs.values.iter())
265 .for_each(|(l, r)| *l $assignmathsymbol &r);
266 Ok(self)
267 }
268 }
269 };
270}
271
272impl_binary_op_with_owned! {Add, add, AddAssign, +, +=, 3.0}
273impl_binary_op_with_owned! {Sub, sub, SubAssign, -, -=, 1.0}
274impl_binary_op_with_owned! {Mul, mul, MulAssign, *, *=, 2.0}
275impl_binary_op_with_owned! {Div, div, DivAssign, /, /=, 2.0}
276
277macro_rules! impl_binary_op_assign {
278 ($Trait:tt, $method:tt, $ValueAssignTrait:tt, $mathsymbol:tt, $testresult:tt) => {
279 impl<A: Axis + PartialEq, V> $Trait<&VecHistogram<A, V>> for VecHistogram<A, V>
280 where
281 for<'a> V: $ValueAssignTrait<&'a V>,
282 {
283 #[doc=concat!("hist1 ", stringify!($mathsymbol), " &hist2;")]
302 #[doc=concat!("assert_eq!(hist1.value(&0.0).unwrap(), &", stringify!($testresult), ");")]
303 fn $method(&mut self, rhs: &VecHistogram<A, V>) {
306 if self.axes() != rhs.axes() {
307 panic!("Cannot combine VecHistograms with incompatible axes.");
308 }
309 self.values
310 .iter_mut()
311 .zip(rhs.values.iter())
312 .for_each(|(l, r)| *l $mathsymbol &r);
313 }
314 }
315 };
316}
317
318impl_binary_op_assign! {AddAssign, add_assign, AddAssign, +=, 3.0}
319impl_binary_op_assign! {SubAssign, sub_assign, SubAssign, -=, 1.0}
320impl_binary_op_assign! {MulAssign, mul_assign, MulAssign, *=, 2.0}
321impl_binary_op_assign! {DivAssign, div_assign, DivAssign, /=, 2.0}
322
323#[cfg(feature = "rayon")]
324use rayon::prelude::*;
325
326impl<A, V> VecHistogram<A, V> {
349 #[cfg(feature = "rayon")]
353 pub fn par_values(&self) -> impl IndexedParallelIterator<Item = &V>
354 where
355 V: Sync,
356 {
357 self.values.par_iter()
358 }
359
360 #[cfg(feature = "rayon")]
364 pub fn par_values_mut(&mut self) -> impl IndexedParallelIterator<Item = &mut V>
365 where
366 V: Send,
367 {
368 self.values.par_iter_mut()
369 }
370
371 #[cfg(feature = "rayon")]
375 pub fn par_iter(
376 &self,
377 ) -> impl IndexedParallelIterator<Item = Item<<A as Axis>::BinInterval, &V>>
378 where
379 A: Axis + Sync,
380 V: Sync,
381 <A as Axis>::BinInterval: Send,
382 {
383 self.values
384 .par_iter()
385 .enumerate()
386 .map(move |(index, value)| Item {
387 index,
388 bin: self
389 .axes
390 .bin(index)
391 .expect("We only iterate over valid indices."),
392 value,
393 })
394 }
395
396 #[cfg(feature = "rayon")]
400 pub fn par_iter_mut(
401 &mut self,
402 ) -> impl IndexedParallelIterator<Item = Item<<A as Axis>::BinInterval, &mut V>>
403 where
404 A: Axis + Sync + Send,
405 V: Send + Sync,
406 <A as Axis>::BinInterval: Send,
407 {
408 let axes = &self.axes;
409 self.values.par_iter_mut().enumerate().map(move |it| Item {
410 index: it.0,
411 bin: axes.bin(it.0).expect("We only iterate over valid indices."),
412 value: it.1,
413 })
414 }
415}