1use super as observables;
4use super::{
5 GroupBinContribution, HistogramAccumulatorState, HistogramBinPosition, HistogramSnapshotKind,
6};
7use eyre::Report;
8use std::collections::BTreeMap;
9use std::error::Error as StdError;
10use thiserror::Error;
11
12#[derive(Debug, Error)]
16pub enum ObservableAccumulationError {
17 #[error("observable sample coefficient must be finite")]
19 NonFiniteCoefficient,
20 #[error("warm up the integrand before creating an observable accumulator")]
22 NotInitialized,
23 #[error("histogram '{title}' requires {expected:?} coordinates")]
25 HistogramKind {
26 title: String,
27 expected: HistogramSnapshotKind,
28 },
29 #[error("incompatible observable snapshot: {source}")]
31 IncompatibleSnapshot {
32 #[source]
33 source: Box<dyn StdError + Send + Sync>,
34 },
35}
36
37impl From<Report> for ObservableAccumulationError {
38 fn from(source: Report) -> Self {
39 Self::IncompatibleSnapshot {
40 source: source.into(),
41 }
42 }
43}
44
45impl HistogramAccumulatorState {
46 pub fn fill_continuous_sample(
65 &mut self,
66 entries: &[(f64, f64)],
67 ) -> Result<(), ObservableAccumulationError> {
68 if self.kind != HistogramSnapshotKind::Continuous {
69 return Err(ObservableAccumulationError::HistogramKind {
70 title: self.title.clone(),
71 expected: self.kind,
72 });
73 }
74 let (min, max, bins) = (self.x_min, self.x_max, self.bins.len());
75 self.fill_sample_bins(entries.iter().map(|&(value, weight)| {
76 let position = if value.is_finite() {
77 observables::histogram_bin_position(value, min, max, bins)
78 } else {
79 None
80 };
81 (position, weight)
82 }));
83 Ok(())
84 }
85
86 pub fn fill_discrete_sample(
93 &mut self,
94 entries: &[(isize, f64)],
95 ) -> Result<(), ObservableAccumulationError> {
96 if self.kind != HistogramSnapshotKind::Discrete {
97 return Err(ObservableAccumulationError::HistogramKind {
98 title: self.title.clone(),
99 expected: self.kind,
100 });
101 }
102 let min = self
103 .discrete_min_bin_id
104 .expect("discrete histogram missing min bin id");
105 let bins = self.bins.len();
106 self.fill_sample_bins(entries.iter().map(|&(bin, weight)| {
107 (
108 Some(observables::histogram_bin_position_discrete(bin, min, bins)),
109 weight,
110 )
111 }));
112 Ok(())
113 }
114
115 fn fill_sample_bins(
116 &mut self,
117 entries: impl IntoIterator<Item = (Option<HistogramBinPosition>, f64)>,
118 ) {
119 self.new_sample_count += 1;
120 let mut grouped = BTreeMap::<HistogramBinPosition, GroupBinContribution>::new();
121 for (position, weight) in entries {
122 let Some(position) = position.filter(|_| weight.is_finite()) else {
123 self.statistics.register_nan();
124 continue;
125 };
126 let contribution = grouped.entry(position).or_default();
127 contribution.projected_weight += weight;
128 contribution.entry_count += 1;
129 }
130 for (position, contribution) in grouped {
131 let bin = match position {
132 HistogramBinPosition::Underflow => &mut self.underflow_bin,
133 HistogramBinPosition::Overflow => &mut self.overflow_bin,
134 HistogramBinPosition::InRange(index) => {
135 self.statistics.new_in_range_entry_count += contribution.entry_count;
136 &mut self.bins[index]
137 }
138 };
139 bin.add_sample(contribution.projected_weight, contribution.entry_count, 0);
140 }
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use crate::observables::{
147 DiscreteBinOrdering, HistogramAccumulatorState, ObservablePhase, ObservableSnapshotBundle,
148 ObservableValueTransform,
149 };
150 use std::collections::BTreeMap;
151
152 fn histogram() -> HistogramAccumulatorState {
153 HistogramAccumulatorState::new_continuous(
154 "test".into(),
155 "AL".into(),
156 ObservablePhase::Real,
157 ObservableValueTransform::Identity,
158 false,
159 0.0,
160 1.0,
161 false,
162 false,
163 1,
164 )
165 }
166
167 #[test]
168 fn correlated_fills_are_summed_before_squaring_including_flow_bins() {
169 let mut state = histogram();
170 state
171 .fill_continuous_sample(&[
172 (-1.0, 10.0),
173 (-1.0, -9.0),
174 (0.25, 10.0),
175 (0.25, -9.0),
176 (2.0, 5.0),
177 (2.0, -4.0),
178 ])
179 .unwrap();
180 state.fill_continuous_sample(&[]).unwrap();
181 let snapshot = state.snapshot();
182 assert_eq!(snapshot.sample_count, 2);
183 for bin in [
184 &snapshot.bins[0],
185 &snapshot.underflow_bin,
186 &snapshot.overflow_bin,
187 ] {
188 assert_eq!(bin.entry_count, 2);
189 assert_eq!(bin.sum_weights, 1.0);
190 assert_eq!(bin.sum_weights_squared, 1.0);
191 assert_eq!(bin.average(2), 0.5);
192 assert_eq!(bin.error(2), 0.5);
193 }
194 let mut discrete = HistogramAccumulatorState::new_discrete(
195 "discrete".into(),
196 "AL".into(),
197 ObservablePhase::Real,
198 ObservableValueTransform::Identity,
199 0,
200 0,
201 DiscreteBinOrdering::AscendingBinId,
202 false,
203 vec![],
204 )
205 .unwrap();
206 discrete
207 .fill_discrete_sample(&[(0, 10.0), (0, -9.0)])
208 .unwrap();
209 assert_eq!(discrete.snapshot().bins[0].sum_weights_squared, 1.0);
210 }
211
212 #[test]
213 fn independent_strata_sum_estimates_instead_of_pooling_sample_counts() {
214 let mut positive = histogram();
215 positive.fill_continuous_sample(&[(0.25, 2.0)]).unwrap();
216 positive.fill_continuous_sample(&[(0.25, 4.0)]).unwrap();
217 let mut negative = histogram();
218 for _ in 0..3 {
219 negative.fill_continuous_sample(&[(0.25, -3.0)]).unwrap();
220 }
221 let strata = [positive, negative].map(|state| ObservableSnapshotBundle {
222 histograms: BTreeMap::from([("test".into(), state.snapshot())]),
223 });
224 let result = ObservableSnapshotBundle::sum_independent_estimates(&strata).unwrap();
225 assert_eq!(result.histograms["test"].sample_counts, [2, 3]);
226 assert_eq!(result.histograms["test"].bins[0].mean, Some(0.0));
227 assert_eq!(result.histograms["test"].bins[0].error, Some(1.0));
228 let mut incomplete = strata[1].clone();
229 incomplete.histograms.get_mut("test").unwrap().sample_count = 0;
230 let unknown =
231 ObservableSnapshotBundle::sum_independent_estimates([&strata[0], &incomplete]).unwrap();
232 assert_eq!(unknown.histograms["test"].bins[0].mean, None);
233 assert_eq!(unknown.histograms["test"].bins[0].error, None);
234 }
235
236 #[test]
237 fn finalized_histograms_merge_all_samples_without_losing_checkpointed_counts() {
238 let mut left = histogram();
239 left.fill_continuous_sample(&[(0.25, 2.0)]).unwrap();
240 left.update_results();
241 let mut right = histogram();
242 right.fill_continuous_sample(&[(0.25, 4.0)]).unwrap();
243 right.update_results();
244 let mut restored = right.snapshot().into_accumulator_state();
245 left.merge_in_place(&mut restored).unwrap();
246 let snapshot = left.snapshot();
247 assert_eq!(snapshot.sample_count, 2);
248 assert_eq!(snapshot.bins[0].sum_weights, 6.0);
249 assert_eq!(snapshot.bins[0].sum_weights_squared, 20.0);
250 assert_eq!(restored.snapshot().sample_count, 0);
251 }
252}