Skip to main content

adk_eval/experiments/
sample.rs

1//! Cumulative per-arm samples and looks (spec 3.5 §7.12).
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7use super::config::MetricKind;
8use crate::error::{EvalError, Result};
9
10/// The cumulative data of one metric in one arm (spec 3.5 §7.12).
11///
12/// Samples are cumulative from the start of the experiment: each look carries the totals so far,
13/// never one day's increment, so sending the same look twice changes nothing. [`Sample::merge`]
14/// adds an increment to a running total.
15///
16/// # Example
17///
18/// ```
19/// use adk_eval::experiments::Sample;
20///
21/// let monday = Sample::proportion(500, 20);
22/// let tuesday = Sample::proportion(480, 25);
23/// let total = monday.merge(&tuesday).unwrap();
24/// assert_eq!(total, Sample::proportion(980, 45));
25///
26/// let revenue = Sample::from_values(&[0.0, 12.5, 0.0, 30.0]);
27/// assert_eq!(revenue.units(), 4);
28/// assert_eq!(revenue.estimate(), 10.625);
29/// ```
30#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase", tag = "kind")]
32#[non_exhaustive]
33pub enum Sample {
34    /// Units exposed, and how many of them had the event.
35    #[serde(rename_all = "camelCase")]
36    Proportion {
37        /// Units exposed to the arm.
38        units: u64,
39        /// Units with at least one event; at most `units`.
40        events: u64,
41    },
42    /// Units exposed, and the mean and sample variance of their per-unit values.
43    #[serde(rename_all = "camelCase")]
44    Mean {
45        /// Units exposed to the arm.
46        units: u64,
47        /// The mean per-unit value.
48        mean: f64,
49        /// The sample variance of the per-unit values (denominator `units - 1`).
50        variance: f64,
51    },
52}
53
54impl Sample {
55    /// Creates a proportion sample: `events` of `units` had the event.
56    pub fn proportion(units: u64, events: u64) -> Self {
57        Self::Proportion { units, events }
58    }
59
60    /// Creates a mean sample from its summary statistics.
61    pub fn mean(units: u64, mean: f64, variance: f64) -> Self {
62        Self::Mean { units, mean, variance }
63    }
64
65    /// Summarises per-unit values as a mean sample.
66    pub fn from_values(values: &[f64]) -> Self {
67        // Welford's update keeps the variance accurate when the mean is large.
68        let mut mean = 0.0;
69        let mut m2 = 0.0;
70        for (index, value) in values.iter().enumerate() {
71            let delta = value - mean;
72            mean += delta / (index + 1) as f64;
73            m2 += delta * (value - mean);
74        }
75        let units = values.len() as u64;
76        let variance = if units > 1 { m2 / (units - 1) as f64 } else { 0.0 };
77        Self::Mean { units, mean, variance }
78    }
79
80    /// Returns how the sample is measured.
81    pub fn kind(&self) -> MetricKind {
82        match self {
83            Self::Proportion { .. } => MetricKind::Proportion,
84            Self::Mean { .. } => MetricKind::Mean,
85        }
86    }
87
88    /// Returns the units exposed.
89    pub fn units(&self) -> u64 {
90        match *self {
91            Self::Proportion { units, .. } | Self::Mean { units, .. } => units,
92        }
93    }
94
95    /// Returns the rate of a proportion or the mean of a mean sample; `0.0` with no units.
96    pub fn estimate(&self) -> f64 {
97        match *self {
98            Self::Proportion { units: 0, .. } => 0.0,
99            Self::Proportion { units, events } => events as f64 / units as f64,
100            Self::Mean { mean, .. } => mean,
101        }
102    }
103
104    /// Returns the variance of the estimate: `p(1 − p)/n` or `s²/n`; `0.0` with no units.
105    pub(crate) fn variance_of_estimate(&self) -> f64 {
106        match *self {
107            Self::Proportion { units: 0, .. } | Self::Mean { units: 0, .. } => 0.0,
108            Self::Proportion { units, .. } => {
109                let rate = self.estimate();
110                rate * (1.0 - rate) / units as f64
111            }
112            Self::Mean { units, variance, .. } => variance / units as f64,
113        }
114    }
115
116    /// Adds an increment of the same kind to this sample.
117    ///
118    /// Mean samples combine with the parallel update of Chan, Golub and LeVeque, so merging
119    /// daily summaries gives the same mean and variance as summarising every value at once.
120    ///
121    /// # Errors
122    ///
123    /// Returns [`EvalError::StatisticsError`] when the samples are of different kinds or either
124    /// is invalid.
125    pub fn merge(&self, other: &Sample) -> Result<Sample> {
126        self.check("merge")?;
127        other.check("merge")?;
128        match (*self, *other) {
129            (
130                Self::Proportion { units: left_units, events: left_events },
131                Self::Proportion { units: right_units, events: right_events },
132            ) => Ok(Self::Proportion {
133                units: left_units.saturating_add(right_units),
134                events: left_events.saturating_add(right_events),
135            }),
136            (
137                Self::Mean { units: left_units, mean: left_mean, variance: left_variance },
138                Self::Mean { units: right_units, mean: right_mean, variance: right_variance },
139            ) => {
140                let units = left_units.saturating_add(right_units);
141                if units == 0 {
142                    return Ok(Self::Mean { units: 0, mean: 0.0, variance: 0.0 });
143                }
144                let (left_n, right_n, n) = (left_units as f64, right_units as f64, units as f64);
145                let delta = right_mean - left_mean;
146                let mean = left_mean + delta * right_n / n;
147                let left_m2 = left_variance * (left_n - 1.0).max(0.0);
148                let right_m2 = right_variance * (right_n - 1.0).max(0.0);
149                let m2 = left_m2 + right_m2 + delta * delta * left_n * right_n / n;
150                let variance = if units > 1 { m2 / (n - 1.0) } else { 0.0 };
151                Ok(Self::Mean { units, mean, variance })
152            }
153            (left, right) => Err(EvalError::StatisticsError(format!(
154                "cannot merge a {:?} sample with a {:?} sample; merge samples of one metric",
155                left.kind(),
156                right.kind()
157            ))),
158        }
159    }
160
161    /// Checks the sample's values, naming `context` in the error.
162    pub(crate) fn check(&self, context: &str) -> Result<()> {
163        match *self {
164            Self::Proportion { units, events } if events > units => {
165                Err(EvalError::StatisticsError(format!(
166                    "{context}: {events} events among {units} units; a proportion counts each \
167                     unit at most once, so use a mean sample for events per unit"
168                )))
169            }
170            Self::Proportion { .. } => Ok(()),
171            Self::Mean { mean, variance, .. } if !mean.is_finite() || !variance.is_finite() => {
172                Err(EvalError::StatisticsError(format!(
173                    "{context}: mean {mean} and variance {variance} must be finite"
174                )))
175            }
176            Self::Mean { variance, .. } if variance < 0.0 => Err(EvalError::StatisticsError(
177                format!("{context}: variance {variance} is negative"),
178            )),
179            Self::Mean { .. } => Ok(()),
180        }
181    }
182}
183
184/// The samples of one metric in the control and the variant (spec 3.5 §7.12).
185#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187pub struct ArmSamples {
188    /// The control arm (A).
189    pub control: Sample,
190    /// The variant arm (B).
191    pub variant: Sample,
192}
193
194impl ArmSamples {
195    /// Pairs a control sample with a variant sample.
196    pub fn new(control: Sample, variant: Sample) -> Self {
197        Self { control, variant }
198    }
199
200    /// Returns the effective sample size `n_c·n_v / (n_c + n_v)`; `0.0` when either arm is
201    /// empty.
202    pub(crate) fn effective_units(&self) -> f64 {
203        let (control, variant) = (self.control.units() as f64, self.variant.units() as f64);
204        if control == 0.0 || variant == 0.0 {
205            return 0.0;
206        }
207        control * variant / (control + variant)
208    }
209}
210
211/// One look at an experiment: the cumulative samples of every metric so far (spec 3.5 §7.12).
212///
213/// # Example
214///
215/// ```
216/// use adk_eval::experiments::{Look, Sample};
217///
218/// let look = Look::new()
219///     .with_metric("signups", Sample::proportion(600, 24), Sample::proportion(600, 30))
220///     .with_metric("unsubscribes", Sample::proportion(600, 3), Sample::proportion(600, 6));
221/// assert_eq!(look.metric("signups").unwrap().variant.units(), 600);
222/// ```
223#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub struct Look {
226    /// Samples by metric id.
227    pub metrics: BTreeMap<String, ArmSamples>,
228}
229
230impl Look {
231    /// Creates an empty look.
232    pub fn new() -> Self {
233        Self::default()
234    }
235
236    /// Adds the cumulative samples of `metric`.
237    pub fn with_metric(
238        mut self,
239        metric: impl Into<String>,
240        control: Sample,
241        variant: Sample,
242    ) -> Self {
243        self.metrics.insert(metric.into(), ArmSamples::new(control, variant));
244        self
245    }
246
247    /// Returns the samples of `metric`.
248    pub fn metric(&self, metric: &str) -> Option<&ArmSamples> {
249        self.metrics.get(metric)
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn merging_daily_summaries_matches_summarising_all_values() {
259        let monday = [3.0, 0.0, 12.5, 7.25, 0.0];
260        let tuesday = [100.0, 1.0, 2.0];
261        let merged = Sample::from_values(&monday).merge(&Sample::from_values(&tuesday)).unwrap();
262        let all: Vec<f64> = monday.iter().chain(&tuesday).copied().collect();
263        let Sample::Mean { units, mean, variance } = merged else { panic!("mean sample") };
264        let Sample::Mean { mean: expected_mean, variance: expected_variance, .. } =
265            Sample::from_values(&all)
266        else {
267            panic!("mean sample")
268        };
269        assert_eq!(units, 8);
270        assert!((mean - expected_mean).abs() < 1e-12);
271        assert!((variance - expected_variance).abs() < 1e-9);
272    }
273
274    #[test]
275    fn invalid_samples_are_refused() {
276        assert!(Sample::proportion(10, 11).check("look").is_err());
277        assert!(Sample::mean(10, f64::NAN, 1.0).check("look").is_err());
278        assert!(Sample::mean(10, 1.0, -1.0).check("look").is_err());
279        assert!(Sample::proportion(10, 1).merge(&Sample::mean(10, 1.0, 1.0)).is_err());
280    }
281
282    #[test]
283    fn effective_units_is_half_the_arm_size_for_equal_arms() {
284        let arms = ArmSamples::new(Sample::proportion(1000, 1), Sample::proportion(1000, 2));
285        assert_eq!(arms.effective_units(), 500.0);
286        let empty = ArmSamples::new(Sample::proportion(0, 0), Sample::proportion(1000, 2));
287        assert_eq!(empty.effective_units(), 0.0);
288    }
289}