gammalooprs/observables/
estimates.rs1use super::{
4 HistogramBinSnapshot, HistogramSnapshot, HistogramSnapshotKind, ObservableSnapshotBundle,
5};
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8use thiserror::Error;
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
13pub struct IndependentEstimate {
14 pub mean: Option<f64>,
15 pub error: Option<f64>,
16}
17
18impl IndependentEstimate {
19 fn from_bins<'a>(bins: impl IntoIterator<Item = (&'a HistogramBinSnapshot, usize)>) -> Self {
20 let mut mean = Some(0.0);
21 let mut error = Some(0.0_f64);
22 for (bin, count) in bins {
23 mean = mean.and_then(|sum| (count > 0).then(|| sum + bin.average(count)));
24 error = error.and_then(|sum| (count > 1).then(|| sum.hypot(bin.error(count))));
25 }
26 Self { mean, error }
27 }
28}
29
30#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
34pub struct HistogramEstimates {
35 pub sample_counts: Vec<usize>,
36 pub bins: Vec<IndependentEstimate>,
37 pub underflow: IndependentEstimate,
38 pub overflow: IndependentEstimate,
39}
40
41impl HistogramEstimates {
42 fn from_histograms(histograms: &[&HistogramSnapshot]) -> Self {
43 let first = histograms[0];
44 let discrete_bins = histograms
45 .iter()
46 .map(|histogram| {
47 histogram
48 .bins
49 .iter()
50 .filter_map(|bin| bin.bin_id.map(|id| (id, bin)))
51 .collect::<BTreeMap<_, _>>()
52 })
53 .collect::<Vec<_>>();
54 let bins = first
55 .bins
56 .iter()
57 .enumerate()
58 .map(|(index, bin)| {
59 IndependentEstimate::from_bins(histograms.iter().enumerate().map(
60 |(population, histogram)| {
61 let other = match first.kind {
62 HistogramSnapshotKind::Discrete => {
63 let id = bin
64 .bin_id
65 .expect("validated discrete histogram has bin identifiers");
66 discrete_bins[population][&id]
67 }
68 HistogramSnapshotKind::Continuous => &histogram.bins[index],
69 };
70 (other, histogram.sample_count)
71 },
72 ))
73 })
74 .collect();
75 Self {
76 sample_counts: histograms
77 .iter()
78 .map(|histogram| histogram.sample_count)
79 .collect(),
80 bins,
81 underflow: IndependentEstimate::from_bins(
82 histograms
83 .iter()
84 .map(|histogram| (&histogram.underflow_bin, histogram.sample_count)),
85 ),
86 overflow: IndependentEstimate::from_bins(
87 histograms
88 .iter()
89 .map(|histogram| (&histogram.overflow_bin, histogram.sample_count)),
90 ),
91 }
92 }
93}
94
95#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
98pub struct ObservableEstimates {
99 pub histograms: BTreeMap<String, HistogramEstimates>,
100}
101
102#[derive(Clone, Debug, Eq, Error, PartialEq)]
105pub enum ObservableEstimateError {
106 #[error("independent estimates have different observable names")]
107 ObservableNames,
108 #[error("independent estimates have incompatible histogram '{0}'")]
109 HistogramLayout(String),
110}
111
112impl ObservableSnapshotBundle {
113 pub fn sum_independent_estimates<'a>(
132 populations: impl IntoIterator<Item = &'a Self>,
133 ) -> Result<ObservableEstimates, ObservableEstimateError> {
134 let populations = populations.into_iter().collect::<Vec<_>>();
135 let Some(first) = populations.first() else {
136 return Ok(ObservableEstimates::default());
137 };
138 if populations
139 .iter()
140 .any(|population| !population.histograms.keys().eq(first.histograms.keys()))
141 {
142 return Err(ObservableEstimateError::ObservableNames);
143 }
144 let mut histograms = BTreeMap::new();
145 for (name, reference) in &first.histograms {
146 let inputs = populations
147 .iter()
148 .map(|population| &population.histograms[name])
149 .collect::<Vec<_>>();
150 if inputs
151 .iter()
152 .any(|histogram| !reference.has_compatible_layout(histogram))
153 {
154 return Err(ObservableEstimateError::HistogramLayout(name.clone()));
155 }
156 histograms.insert(name.clone(), HistogramEstimates::from_histograms(&inputs));
157 }
158 Ok(ObservableEstimates { histograms })
159 }
160}