Skip to main content

predsync_core/predictor/
ewma.rs

1//! Exponentially weighted moving average predictor for numeric fields.
2
3use super::{Predictor, PredictorError};
4use crate::hash::ewma_state_hash;
5
6/// An exponentially weighted moving average (EWMA) predictor.
7///
8/// The first sample initialises the level exactly. Each later sample updates
9/// it in a fixed order with no fused multiply-add:
10///
11/// ```text
12/// level = alpha * x + (1 - alpha) * level
13/// ```
14///
15/// `alpha` must be finite and in `(0, 1]`; a larger value reacts faster to new
16/// samples. `alpha = 1` is equivalent to [hold-last](super::HoldLastPredictor)
17/// prediction. [`Predictor::predict`] returns the current level for any future
18/// tick, so this is a flat forecast. Unlike the polynomial predictors, EWMA
19/// needs no window: every accepted sample contributes to the level.
20///
21/// ```
22/// use predsync_core::predictor::{EwmaPredictor, Predictor};
23///
24/// let mut predictor = EwmaPredictor::new(0.25);
25/// assert_eq!(predictor.predict(1), None);
26/// predictor.update(0, 4.0).unwrap();
27/// predictor.update(1, 8.0).unwrap();
28/// assert_eq!(predictor.predict(9), Some(5.0));
29/// predictor.update(2, 12.0).unwrap();
30/// assert_eq!(predictor.predict(9), Some(6.75));
31/// ```
32#[derive(Debug, Clone)]
33pub struct EwmaPredictor {
34    alpha: f64,
35    beta: f64,
36    level: f64,
37    last_t: Option<u64>,
38    count: u64,
39}
40
41impl EwmaPredictor {
42    /// Create a predictor with smoothing factor `alpha`.
43    ///
44    /// # Panics
45    ///
46    /// Panics if `alpha` is not finite or is outside `(0, 1]`.
47    pub fn new(alpha: f64) -> Self {
48        assert!(
49            alpha.is_finite() && alpha > 0.0 && alpha <= 1.0,
50            "ewma alpha must be finite and in (0, 1]"
51        );
52        Self {
53            alpha,
54            beta: 1.0 - alpha,
55            level: 0.0,
56            last_t: None,
57            count: 0,
58        }
59    }
60
61    /// The smoothing factor supplied to [`Self::new`].
62    pub fn alpha(&self) -> f64 {
63        self.alpha
64    }
65
66    /// The current smoothed level, or `None` before the first sample or when
67    /// the level is not finite.
68    pub fn level(&self) -> Option<f64> {
69        (self.count > 0 && self.level.is_finite()).then_some(self.level)
70    }
71
72    /// Number of accepted samples.
73    pub fn sample_count(&self) -> u64 {
74        self.count
75    }
76
77    /// Incorporate a sample at strictly increasing tick `t`.
78    pub fn update(&mut self, t: u64, x: f64) -> Result<(), PredictorError> {
79        if self.last_t.is_some_and(|last| t <= last) {
80            return Err(PredictorError::NonMonotonic);
81        }
82        if self.count == 0 {
83            self.level = x;
84        } else {
85            self.level = self.alpha * x + self.beta * self.level;
86        }
87        self.last_t = Some(t);
88        self.count += 1;
89        Ok(())
90    }
91
92    /// Clear the predictor to its initial state.
93    pub fn reset(&mut self) {
94        self.level = 0.0;
95        self.last_t = None;
96        self.count = 0;
97    }
98
99    /// Deterministic hash of the smoothing factor and current state.
100    pub fn state_hash(&self) -> u64 {
101        ewma_state_hash(
102            self.alpha,
103            self.last_t.unwrap_or(0),
104            self.count,
105            if self.count == 0 { 0.0 } else { self.level },
106        )
107    }
108
109    /// The current smoothed level, independent of the requested tick.
110    pub fn predict(&self, _t: u64) -> Option<f64> {
111        self.level()
112    }
113}
114
115impl Predictor for EwmaPredictor {
116    fn reset(&mut self) {
117        EwmaPredictor::reset(self);
118    }
119
120    fn update(&mut self, t: u64, x: f64) -> Result<(), PredictorError> {
121        EwmaPredictor::update(self, t, x)
122    }
123
124    fn predict(&self, t: u64) -> Option<f64> {
125        EwmaPredictor::predict(self, t)
126    }
127
128    fn state_hash(&self) -> u64 {
129        EwmaPredictor::state_hash(self)
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    extern crate std;
136    use super::*;
137    use crate::predictor::check_predictor;
138
139    #[test]
140    fn first_sample_initialises_level() {
141        let mut predictor = EwmaPredictor::new(0.25);
142        assert_eq!(predictor.predict(0), None);
143        predictor.update(3, 7.0).unwrap();
144        assert_eq!(predictor.level(), Some(7.0));
145        assert_eq!(predictor.sample_count(), 1);
146        assert_eq!(predictor.predict(100), Some(7.0));
147    }
148
149    #[test]
150    fn recurrence_is_bit_exact_and_flat() {
151        let mut predictor = EwmaPredictor::new(0.25);
152        for &(t, x) in &[(0u64, 4.0f64), (1, 8.0), (2, 12.0)] {
153            predictor.update(t, x).unwrap();
154        }
155        assert_eq!(predictor.level(), Some(6.75));
156        for t in [3, 10, 1_000] {
157            assert_eq!(predictor.predict(t), Some(6.75));
158        }
159    }
160
161    #[test]
162    fn alpha_one_matches_hold_last() {
163        let mut predictor = EwmaPredictor::new(1.0);
164        predictor.update(0, 1.25).unwrap();
165        predictor.update(7, -3.5).unwrap();
166        assert_eq!(predictor.predict(8), Some(-3.5));
167    }
168
169    #[test]
170    fn irregular_ticks_do_not_change_weighting() {
171        let mut predictor = EwmaPredictor::new(0.5);
172        predictor.update(0, 0.0).unwrap();
173        predictor.update(1_000_000, 8.0).unwrap();
174        assert_eq!(predictor.predict(1_000_001), Some(4.0));
175    }
176
177    #[test]
178    fn reset_returns_initial_state_and_hash() {
179        let mut predictor = EwmaPredictor::new(0.3);
180        let initial = predictor.state_hash();
181        predictor.update(0, 2.0).unwrap();
182        assert_ne!(predictor.state_hash(), initial);
183        predictor.reset();
184        assert_eq!(predictor.state_hash(), initial);
185        assert_eq!(predictor.predict(1), None);
186        assert_eq!(predictor.sample_count(), 0);
187    }
188
189    #[test]
190    fn non_monotonic_update_leaves_state_unchanged() {
191        let mut predictor = EwmaPredictor::new(0.5);
192        predictor.update(0, 2.0).unwrap();
193        predictor.update(1, 4.0).unwrap();
194        let before = predictor.state_hash();
195        assert_eq!(
196            predictor.update(1, 100.0),
197            Err(PredictorError::NonMonotonic)
198        );
199        assert_eq!(
200            predictor.update(0, 100.0),
201            Err(PredictorError::NonMonotonic)
202        );
203        assert_eq!(predictor.state_hash(), before);
204        assert_eq!(predictor.predict(2), Some(3.0));
205    }
206
207    #[test]
208    fn state_hash_includes_alpha_and_level() {
209        let mut left = EwmaPredictor::new(0.25);
210        let mut right = EwmaPredictor::new(0.5);
211        left.update(0, 1.0).unwrap();
212        right.update(0, 1.0).unwrap();
213        assert_ne!(left.state_hash(), right.state_hash());
214
215        let mut same = EwmaPredictor::new(0.25);
216        same.update(0, 1.0).unwrap();
217        assert_eq!(left.state_hash(), same.state_hash());
218        right.update(1, 2.0).unwrap();
219        assert_ne!(left.state_hash(), right.state_hash());
220    }
221
222    #[test]
223    fn state_hash_matches_reference_model() {
224        let mut predictor = EwmaPredictor::new(0.25);
225        assert_eq!(predictor.state_hash(), 0x49A8_D931_C63A_2DF8);
226        for &(t, x) in &[(0u64, 4.0f64), (1, 8.0), (2, 12.0)] {
227            predictor.update(t, x).unwrap();
228        }
229        assert_eq!(predictor.state_hash(), 0xC3F8_0FA9_9A5A_E526);
230    }
231
232    #[test]
233    fn conformance_helper_accepts_ewma() {
234        let trace = std::concat!(
235            "{\"name\":\"ewma\",\"kind\":\"ewma\",\"alpha\":0.25,",
236            "\"samples\":[[0,4.0],[1,8.0]],",
237            "\"queries\":[{\"t\":2,\"expect\":5.0}]}"
238        );
239        let mut predictor = EwmaPredictor::new(0.25);
240        check_predictor(&mut predictor, trace).unwrap();
241    }
242
243    #[test]
244    #[should_panic(expected = "ewma alpha must be finite and in (0, 1]")]
245    fn invalid_alpha_panics() {
246        let _ = EwmaPredictor::new(0.0);
247    }
248}