Skip to main content

gammalooprs/observables/
estimates.rs

1//! Final estimates from independent populations, keeping their raw sample counts separate.
2
3use super::{
4    HistogramBinSnapshot, HistogramSnapshot, HistogramSnapshotKind, ObservableSnapshotBundle,
5};
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8use thiserror::Error;
9
10/// A sum of independent estimates; no fictitious pooled sample count is assigned.
11/// See [`ObservableSnapshotBundle::sum_independent_estimates`].
12#[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/// Bin estimates in the first input snapshot's order, with counts for each population.
31/// Coordinates and labels are supplied by that compatible raw snapshot.
32/// See [`ObservableSnapshotBundle::sum_independent_estimates`].
33#[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/// Presentation estimates, distinct from mergeable/reconstructible raw snapshots.
96/// See [`ObservableSnapshotBundle::sum_independent_estimates`].
97#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
98pub struct ObservableEstimates {
99    pub histograms: BTreeMap<String, HistogramEstimates>,
100}
101
102/// Independent estimates must describe the same observables and bins.
103/// See [`ObservableSnapshotBundle::sum_independent_estimates`].
104#[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    /// Sum independent population means and variances, without pooling their counts.
114    ///
115    /// For stratification, each input is one stratum's conditional-weight statistics.
116    /// Merge worker batches within each stratum before calling this operation.
117    /// A population with no attempts makes the mean unavailable; fewer than two
118    /// attempts makes the error unavailable. Covariances between bins are not implied.
119    ///
120    /// # Errors
121    /// Returns an error for different observable names or incompatible bin layouts.
122    ///
123    /// # Examples
124    /// ```
125    /// use gammalooprs::observables::ObservableSnapshotBundle;
126    /// let strata = [ObservableSnapshotBundle::default(), ObservableSnapshotBundle::default()];
127    /// let estimates = ObservableSnapshotBundle::sum_independent_estimates(&strata)?;
128    /// assert!(estimates.histograms.is_empty());
129    /// # Ok::<(), gammalooprs::observables::ObservableEstimateError>(())
130    /// ```
131    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}