ndhistogram/value/
sum.rs

1use num_traits::Float;
2
3use crate::Fill;
4use crate::FillWith;
5
6/// ndhistogram bin value type for filling unweighted values.
7/// Analogous to [WeightedSum](crate::value::WeightedSum). Methods returning variance and standard
8/// deviation assume Poisson statistics.
9#[derive(Copy, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct Sum<T = f64> {
12    sum: T,
13}
14
15impl<T: Copy> Sum<T> {
16    /// Factory method to create an unfilled (or zero valued) Sum.
17    pub fn new() -> Self
18    where
19        Self: Default,
20    {
21        Self::default()
22    }
23
24    /// Get the current value of the sum.
25    pub fn get(&self) -> T {
26        self.sum()
27    }
28
29    /// Get the current value.
30    pub fn sum(&self) -> T {
31        self.sum
32    }
33
34    /// Estimate of the variance of value assuming Poisson statistics.
35    pub fn variance(&self) -> T {
36        self.sum
37    }
38
39    /// Square root of the variance.
40    pub fn standard_deviation<O>(&self) -> O
41    where
42        T: Into<O>,
43        O: Float,
44    {
45        self.variance().into().sqrt()
46    }
47}
48
49impl<T: Copy + Fill> Fill for Sum<T> {
50    #[inline]
51    fn fill(&mut self) {
52        self.sum.fill();
53    }
54}
55
56impl<T, W> FillWith<W> for Sum<T>
57where
58    T: FillWith<W> + Copy,
59    W: Copy,
60{
61    #[inline]
62    fn fill_with(&mut self, weight: W) {
63        self.sum.fill_with(weight);
64    }
65}