Skip to main content

lib_jsl_random/
histogram.rs

1//! Fixed-width histograms.
2//!
3//! See the book entry [Pseudo-random number generators](https://jwkunz.github.io/lib_jsl/book/random/generators.html#histograms).
4
5use lib_jsl_core::ErrorsJSL;
6/// The histogram will take incoming data, place it into discrete bins, and count the hits in each bin
7/// The bin_labels are labeled by the minimum boundary of the bin
8/// e.g. bin_value = 1, with a bin width of 1, corresponds to hits in  the interval [1,2).
9pub struct Histogram{
10    bin_min : f64,
11    bin_labels : Vec<f64>,
12    bin_counts : Vec<usize>,
13    total : usize,
14    bin_width : f64
15}
16
17impl Histogram{
18    /// Creates a new histogram that spans `[bin_min, bin_max]` with `n_bins` equal bins.
19    /// The bin labels are the lower edges, `bin_min + i · width`; `bin_max` itself is counted in the
20    /// last bin.
21    pub fn new(bin_min : f64, bin_max : f64, n_bins : usize)->Self{
22        let span = bin_max-bin_min;
23        let bin_width = span / (n_bins) as f64;
24        // (The labels once started at 0 whatever bin_min was, which shifted every bin.)
25        let bin_labels = (0..n_bins).map(|x| bin_min + x as f64*bin_width).collect();
26        let bin_counts = (0..n_bins).map(|_| 0).collect();
27        let total = 0;
28        Histogram { bin_min, bin_labels, bin_counts, total, bin_width}
29    }
30    /// Reset the counts in each bin
31    pub fn reset(&mut self){
32        self.bin_counts.iter_mut().for_each(|x| *x = 0);
33        self.total = 0;
34    }
35    /// Find the bin of the value and increment the count
36    /// Will fail if the sample exceeds the bin_min and bin_max
37    pub fn count(&mut self, value : f64) -> Result<(),ErrorsJSL>{
38        let n_bins = self.bin_counts.len();
39        let bin_index_raw = (value - self.bin_min) / self.bin_width;
40        if bin_index_raw.is_nan() || bin_index_raw < 0.0{
41            return Err(ErrorsJSL::InvalidInputRange("Input value is less than minimum bin value"));
42        }
43        else if bin_index_raw > n_bins as f64{
44            return Err(ErrorsJSL::InvalidInputRange("Input value is greater than maximum bin value"));
45        }
46        // bin_max itself (index n_bins) belongs to the last bin; the bound once allowed index
47        // n_bins through to a panic.
48        self.bin_counts[(bin_index_raw.floor() as usize).min(n_bins - 1)] += 1;
49        self.total += 1;
50        Ok(())
51    }
52    /// Getters
53    pub fn get_bin_labels(&self) -> &Vec<f64>{
54        &self.bin_labels
55    }
56    /// Get counts without dividing by total
57    pub fn get_counts_raw(&self) -> &Vec<usize>{
58        &self.bin_counts
59    }
60    /// Get counts after dividing by total.  Will fail if total = 0;
61    pub fn get_counts_normalized(&self) -> Result<Vec<f64>,ErrorsJSL>{
62        if self.total == 0{
63            return Err(ErrorsJSL::RuntimeError("Not bin counts have yet been recorded"));
64        }
65        let scale = 1.0/self.total as f64;
66        Ok(self.bin_counts.iter().map(|&x| (x as f64)*scale).collect())
67    }
68    /// Get the total
69    pub fn get_total(&self) -> usize{
70        self.total
71    }
72    /// Get the bin width
73    pub fn get_bin_width(&self) -> f64{
74        self.bin_width
75    }
76    /// These functions return vectors of tuples (bin_label,count)
77    /// In either raw or normalized format
78    pub fn get_counts_raw_paired(&self) -> Vec<(f64,usize)>{
79        self.bin_labels.iter().zip(self.bin_counts.iter()).map(|(&x,&y)| (x,y)).collect::<Vec<(f64,usize)>>()
80    }
81    pub fn get_counts_normalized_paired(&self) -> Result<Vec<(f64,f64)>,ErrorsJSL>{
82        let counts = self.get_counts_normalized()?;
83        Ok(self.bin_labels.iter().zip(counts.iter()).map(|(&x,&y)| (x,y)).collect::<Vec<(f64,f64)>>())
84    }
85}
86
87#[cfg(test)]
88mod test{
89    use super::*;
90    use crate::{distributions::gaussian_distribution_box_muller_vec, uniform_generator::UniformRNG};
91    #[test]
92    fn test_histogram(){
93        let mut rng = UniformRNG::from_seed(0);
94        let mut dut = Histogram::new(0.0, 10.0, 10);
95        let n_samples = 1_000_000;
96        gaussian_distribution_box_muller_vec(n_samples,&mut rng, 5.0, 1.0).iter().for_each(|&x| {let _ = dut.count(x);});
97        // The probabilities of N(5, 1) falling in each unit bin (Φ(k − 4) − Φ(k − 5)); the
98        // sampling error with 10⁶ samples is below 5e-4 per bin.
99        let expected = [3.17e-5, 1.3499e-3, 2.1400e-2, 1.35905e-1, 3.41345e-1, 3.41345e-1, 1.35905e-1, 2.1400e-2, 1.3499e-3, 3.17e-5];
100        let counts_norm = dut.get_counts_normalized().unwrap();
101        assert!(counts_norm.iter().zip(expected).all(|(c, e)| (c - e).abs() < 1e-3), "{counts_norm:?}");
102        assert!((counts_norm.iter().sum::<f64>() - 1.0).abs() < 1e-4);
103        dbg!(_ = dut.get_counts_normalized_paired());
104    }
105
106    #[test]
107    fn bins_start_at_bin_min_and_cover_the_closed_range() {
108        // Labels once started at 0 whatever bin_min was; values at bin_max panicked.
109        let mut h = Histogram::new(-4.0, 8.0, 12);
110        assert_eq!(h.get_bin_labels()[0], -4.0);
111        for v in [-4.0, -3.5, 0.2, 7.99, 8.0] {
112            h.count(v).unwrap();
113        }
114        let c = h.get_counts_raw();
115        assert_eq!((c[0], c[4], c[11]), (2, 1, 2));
116        assert!(h.count(-4.1).is_err() && h.count(8.1).is_err() && h.count(f64::NAN).is_err());
117        h.reset();
118        assert_eq!(h.get_total(), 0);
119    }
120}