lib_jsl_random/
histogram.rs1use lib_jsl_core::ErrorsJSL;
6pub 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 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 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 pub fn reset(&mut self){
32 self.bin_counts.iter_mut().for_each(|x| *x = 0);
33 self.total = 0;
34 }
35 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 self.bin_counts[(bin_index_raw.floor() as usize).min(n_bins - 1)] += 1;
49 self.total += 1;
50 Ok(())
51 }
52 pub fn get_bin_labels(&self) -> &Vec<f64>{
54 &self.bin_labels
55 }
56 pub fn get_counts_raw(&self) -> &Vec<usize>{
58 &self.bin_counts
59 }
60 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 pub fn get_total(&self) -> usize{
70 self.total
71 }
72 pub fn get_bin_width(&self) -> f64{
74 self.bin_width
75 }
76 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 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 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}