backshift 0.3.0

Time-series forecasting checked against R and statsmodels: ARIMA, ETS, Theta, VAR, Croston/TSB, GARCH and changepoint detection, with streaming filters that run without a heap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Exponential smoothing in the innovations state-space form (ETS), with a heap-free filter.
//!
//! The models are those of Hyndman, Koehler, Ord and Snyder (2008) as R's `forecast::ets`
//! fits them: a level, an optional additive or damped trend, and an optional additive season,
//! all updated by one source of error. [`EtsSpec`] holds the smoothing parameters and the
//! current states. [`EtsFilter`] carries them forward one value at a time without a heap,
//! as [`Filter`](crate::Filter) does for ARIMA, and forecasts with R's analytic intervals.
//!
//! The states are a level `l`, a slope `b` and `m` seasonal states. With `y` the new value
//! and `f = l + phi b + s_m` its one-step forecast, one step is
//!
//! ```text
//! l' = l + phi b + alpha (y - f)
//! b' = phi b + beta (y - f)
//! s' = s_m + gamma (y - f), and the other seasonal states move one place on
//! ```
//!
//! which is R's update in the error-correction form. `phi = 1` without damping.

mod class3;
mod recursion;

pub(crate) use recursion::Smoothing;
#[cfg(feature = "alloc")]
pub(crate) use recursion::unroll;

use crate::filter::FilterError;
use crate::math;
use crate::normal::normal_quantile;
use crate::state_space::Innovation;

/// How an ETS component combines: added to the forecast, or multiplying it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Form {
    /// The component adds to the forecast; for the error, `y = f + e`.
    #[default]
    Additive,
    /// The component multiplies the forecast; for the error, `y = f (1 + e)`. It needs
    /// positive values.
    Multiplicative,
}

/// The trend of an ETS model.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Trend {
    /// No trend: the level carries the forecast.
    None,
    /// An additive trend with slope smoothing parameter `beta`.
    Additive {
        /// The slope smoothing parameter, in R's form (`beta < alpha`).
        beta: f64,
    },
    /// An additive trend damped by `phi`: the slope decays by `phi` each step.
    Damped {
        /// The slope smoothing parameter, in R's form (`beta < alpha`).
        beta: f64,
        /// The damping parameter, `0 < phi <= 1`; R fits it in `[0.8, 0.98]`.
        phi: f64,
    },
}

impl Trend {
    /// The slope smoothing parameter, or 0 without a trend.
    pub(crate) const fn beta(self) -> f64 {
        match self {
            Trend::None => 0.0,
            Trend::Additive { beta } | Trend::Damped { beta, .. } => beta,
        }
    }

    /// The damping parameter: `phi` for a damped trend, 1 otherwise.
    pub(crate) const fn phi(self) -> f64 {
        match self {
            Trend::Damped { phi, .. } => phi,
            Trend::None | Trend::Additive { .. } => 1.0,
        }
    }
}

/// An ETS model with its smoothing parameters and current states.
///
/// A fitted model gives its states after the last value
/// ([`EtsFit::spec`](crate::EtsFit::spec)), so a filter built from it continues where the
/// fit ended and needs no warm-up.
///
/// # Examples
///
/// ```
/// use backshift::{EtsFilter, EtsSpec, Trend};
///
/// // Holt's linear trend: level 10, slope 0.5.
/// let spec = EtsSpec {
///     alpha: 0.3,
///     trend: Trend::Additive { beta: 0.1 },
///     level: 10.0,
///     slope: 0.5,
///     ..EtsSpec::default()
/// };
/// let filter = EtsFilter::<1>::new(&spec).unwrap();
/// let (mut mean, mut variance) = ([0.0; 3], [0.0; 3]);
/// filter.forecast_into(&mut mean, &mut variance);
/// assert_eq!(mean, [10.5, 11.0, 11.5]);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EtsSpec<'a> {
    /// The error: additive, or multiplicative (relative to the forecast).
    pub error: Form,
    /// The level smoothing parameter, `0 < alpha < 1`.
    pub alpha: f64,
    /// The trend and its parameters.
    pub trend: Trend,
    /// Whether the seasonal states add to the forecast or multiply it; unused without them.
    pub season: Form,
    /// The seasonal smoothing parameter `gamma`; unused without seasonal states.
    pub gamma: f64,
    /// The level.
    pub level: f64,
    /// The slope; unused without a trend.
    pub slope: f64,
    /// The seasonal states, most recent first: `seasonal[m - 1]` belongs to the next value.
    /// Empty for a model without a season; its length is the period `m`.
    pub seasonal: &'a [f64],
    /// The innovation variance. Must be positive and finite.
    pub sigma2: f64,
}

impl Default for EtsSpec<'_> {
    /// Simple exponential smoothing at level 0 with `alpha = 0.5` and unit variance.
    fn default() -> Self {
        Self {
            error: Form::Additive,
            alpha: 0.5,
            trend: Trend::None,
            season: Form::Additive,
            gamma: 0.0,
            level: 0.0,
            slope: 0.0,
            seasonal: &[],
            sigma2: 1.0,
        }
    }
}

impl EtsSpec<'_> {
    /// Checks that every parameter and state is finite, `alpha` and `sigma2` are positive,
    /// and the model is one R allows: a multiplicative season needs a multiplicative error.
    fn validate(&self) -> Result<(), FilterError> {
        let values = [
            self.alpha,
            self.trend.beta(),
            self.trend.phi(),
            self.gamma,
            self.level,
            self.slope,
            self.sigma2,
        ];
        let finite = values.iter().chain(self.seasonal).all(|v| v.is_finite());
        let allowed = !(self.error == Form::Additive && self.multiplicative_season());
        // The slope update divides by `alpha`.
        if !finite || self.sigma2 <= 0.0 || self.alpha <= 0.0 || !allowed {
            return Err(FilterError::InvalidParameter);
        }

        Ok(())
    }

    /// The smoothing parameters as the recursion takes them.
    fn smoothing(&self) -> Smoothing {
        Smoothing {
            alpha: self.alpha,
            beta: self.trend.beta(),
            gamma: self.gamma,
            phi: self.trend.phi(),
            trend: !matches!(self.trend, Trend::None),
            multiplicative_season: self.multiplicative_season(),
        }
    }

    /// Whether the model has seasonal states that multiply the forecast.
    fn multiplicative_season(&self) -> bool {
        self.season == Form::Multiplicative && !self.seasonal.is_empty()
    }
}

/// A streaming ETS filter with room for `M` seasonal states, stored inline with no heap.
///
/// `M` must be at least the period of the model; a model without a season fits in `M = 0`. The size
/// is about `8 (M + 9)` bytes, and each update costs `O(1)`: the seasonal states form a
/// ring, so no update shifts them.
///
/// # Examples
///
/// ```
/// use backshift::{EtsFilter, EtsSpec};
///
/// let spec = EtsSpec { alpha: 0.5, level: 10.0, ..EtsSpec::default() };
/// let mut filter = EtsFilter::<1>::new(&spec).unwrap();
/// let innovation = filter.update(12.0);
/// assert_eq!(innovation.value, 2.0);
/// assert_eq!(filter.level(), 11.0);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct EtsFilter<const M: usize> {
    /// The error form.
    error: Form,
    /// The smoothing parameters.
    smoothing: Smoothing,
    /// The innovation variance.
    sigma2: f64,
    /// The level.
    level: f64,
    /// The slope; 0 without a trend.
    slope: f64,
    /// The seasonal states, most recent first; the first `m` entries are used.
    seasonal: [f64; M],
    /// The period `m`; 0 without a season.
    m: usize,
    /// Where the most recent seasonal state sits in the ring `seasonal[..m]`.
    head: usize,
}

impl<const M: usize> EtsFilter<M> {
    /// Builds a filter at the states of `spec`. This is the device path: it does not
    /// allocate.
    ///
    /// # Errors
    ///
    /// - [`FilterError::InvalidParameter`] if a parameter or state is not finite, or `alpha`
    ///   or `sigma2` is not positive.
    /// - [`FilterError::Capacity`] if the model has more seasonal states than `M`.
    pub fn new(spec: &EtsSpec<'_>) -> Result<Self, FilterError> {
        spec.validate()?;
        let m = spec.seasonal.len();
        if m > M {
            return Err(FilterError::Capacity {
                needed: m,
                capacity: M,
            });
        }

        let mut seasonal = [0.0; M];
        seasonal[..m].copy_from_slice(spec.seasonal);
        Ok(Self {
            error: spec.error,
            smoothing: spec.smoothing(),
            sigma2: spec.sigma2,
            level: spec.level,
            slope: if matches!(spec.trend, Trend::None) {
                0.0
            } else {
                spec.slope
            },
            seasonal,
            m,
            head: 0,
        })
    }

    /// Feeds one value and returns its one-step forecast error `y - f` and the variance of
    /// it: `sigma2`, or `sigma2 f^2` with a multiplicative error.
    ///
    /// A non-finite value counts as missing: its error is `NaN`, and the states move on as
    /// their forecast, as if the value had been forecast exactly.
    pub fn update(&mut self, y: f64) -> Innovation {
        let forecast = self
            .smoothing
            .forecast(self.level, self.slope, self.seasonal(), self.head);
        let innovation = Innovation {
            value: if y.is_finite() {
                y - forecast
            } else {
                f64::NAN
            },
            variance: match self.error {
                Form::Additive => self.sigma2,
                Form::Multiplicative => self.sigma2 * forecast * forecast,
            },
        };
        let observed = if y.is_finite() { y } else { forecast };
        let m = self.m;
        self.smoothing.update(
            &mut self.level,
            &mut self.slope,
            &mut self.seasonal[..m],
            &mut self.head,
            observed,
        );

        innovation
    }

    /// The current level.
    #[must_use]
    pub const fn level(&self) -> f64 {
        self.level
    }

    /// Forecasts the next `mean.len()` values and their prediction variances.
    ///
    /// The variances are R's analytic ones. With an additive error (R's class 1) they are
    /// `sigma2 (1 + c_1^2 + ... + c_(h-1)^2)` with `c_j = alpha + beta phi_j + gamma` where
    /// `j` is a multiple of `m`, and `phi_j = phi + ... + phi^j`. With a multiplicative
    /// error and no or an additive season (class 2) they follow from the same `c_j` and the
    /// means. With a multiplicative season (class 3) they need working memory: this method
    /// writes the point forecasts and `NaN` variances, and [`EtsFilter::forecast_with`]
    /// computes the variances and R's means, the expectations of the future values.
    ///
    /// # Panics
    ///
    /// Panics if `mean` and `variance` have different lengths.
    pub fn forecast_into(&self, mean: &mut [f64], variance: &mut [f64]) {
        self.forecast_with(&mut [], mean, variance);
    }

    /// The working memory [`EtsFilter::forecast_with`] needs for this model: 0, or for a
    /// multiplicative season `7 q^2 + 3 q + m` values with `q = m` (`2 m` with a trend): the
    /// moment recursion, and the seasonal states in forecast order.
    #[must_use]
    pub const fn forecast_scratch_len(&self) -> usize {
        if self.smoothing.multiplicative_season {
            class3::scratch_len(self.smoothing.trend, self.m) + self.m
        } else {
            0
        }
    }

    /// Like [`EtsFilter::forecast_into`], with `scratch` of at least
    /// [`EtsFilter::forecast_scratch_len`] values for the variances of a multiplicative
    /// season. With less, those variances are `NaN`.
    ///
    /// # Panics
    ///
    /// Panics if `mean` and `variance` have different lengths.
    pub fn forecast_with(&self, scratch: &mut [f64], mean: &mut [f64], variance: &mut [f64]) {
        assert_eq!(
            mean.len(),
            variance.len(),
            "mean and variance must have the same length"
        );
        self.smoothing
            .forecast_means(self.level, self.slope, self.seasonal(), self.head, mean);
        if self.smoothing.multiplicative_season {
            self.class3_moments(scratch, mean, variance);
            return;
        }

        self.smoothing
            .forecast_variances(self.m, self.sigma2, variance);
        if self.error == Form::Multiplicative {
            self.smoothing
                .relative_variances(self.m, self.sigma2, mean, variance);
        }
    }

    /// R's class-3 means and variances, replacing the point forecasts in `mean` with the
    /// expectations. If `scratch` is too short, the point forecasts stay and the variances
    /// are `NaN`. The seasonal ring is unrolled into the end of `scratch` first.
    fn class3_moments(&self, scratch: &mut [f64], mean: &mut [f64], variance: &mut [f64]) {
        let needed = self.forecast_scratch_len();
        if scratch.len() < needed {
            variance.fill(f64::NAN);
            return;
        }

        let (work, ordered) = scratch[..needed].split_at_mut(needed - self.m);
        for (j, value) in ordered.iter_mut().enumerate() {
            *value = self.seasonal[(self.head + j) % self.m];
        }
        class3::moments(
            &self.smoothing,
            self.level,
            self.slope,
            ordered,
            self.sigma2,
            work,
            mean,
            variance,
        );
    }

    /// Forecasts the next `mean.len()` values with central prediction intervals at `level`:
    /// `mean ± z sqrt(variance)` with `z = Φ⁻¹((1 + level) / 2)`, as R's `forecast.ets`.
    /// `level` is a probability in `(0, 1)`; outside it the bounds are not finite. With a
    /// multiplicative season the bounds are `NaN`; see [`EtsFilter::forecast_interval_with`].
    ///
    /// # Panics
    ///
    /// Panics if `mean`, `lower` and `upper` do not all have the same length.
    pub fn forecast_interval_into(
        &self,
        level: f64,
        mean: &mut [f64],
        lower: &mut [f64],
        upper: &mut [f64],
    ) {
        self.forecast_interval_with(&mut [], level, mean, lower, upper);
    }

    /// Like [`EtsFilter::forecast_interval_into`], with `scratch` as in
    /// [`EtsFilter::forecast_with`].
    ///
    /// # Panics
    ///
    /// Panics if `mean`, `lower` and `upper` do not all have the same length.
    pub fn forecast_interval_with(
        &self,
        scratch: &mut [f64],
        level: f64,
        mean: &mut [f64],
        lower: &mut [f64],
        upper: &mut [f64],
    ) {
        assert!(
            mean.len() == lower.len() && mean.len() == upper.len(),
            "mean, lower and upper must have the same length"
        );

        // `upper` holds the variances until it is overwritten below.
        self.forecast_with(scratch, mean, upper);
        let z = normal_quantile(f64::midpoint(1.0, level));
        for ((m, lo), up) in mean.iter().zip(lower.iter_mut()).zip(upper.iter_mut()) {
            let half_width = z * math::sqrt(*up);
            *lo = m - half_width;
            *up = m + half_width;
        }
    }

    /// The ring of seasonal states in use; the most recent sits at `head`.
    fn seasonal(&self) -> &[f64] {
        &self.seasonal[..self.m]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_model_without_a_season_needs_no_seasonal_capacity() {
        let spec = EtsSpec {
            error: Form::Additive,
            alpha: 0.3,
            trend: Trend::Additive { beta: 0.1 },
            gamma: 0.0,
            level: 10.0,
            slope: 1.0,
            season: Form::Additive,
            seasonal: &[],
            sigma2: 1.0,
        };
        let mut filter = EtsFilter::<0>::new(&spec).unwrap();
        filter.update(11.5);
        let (mut mean, mut variance) = ([0.0; 2], [0.0; 2]);
        filter.forecast_into(&mut mean, &mut variance);
        assert!(mean.iter().chain(&variance).all(|v| v.is_finite()));

        let zero = EtsSpec { alpha: 0.0, ..spec };
        assert!(EtsFilter::<0>::new(&zero).is_err());
    }

    #[test]
    fn missing_values_move_the_states_on_as_forecast() {
        let spec = EtsSpec {
            alpha: 0.4,
            trend: Trend::Damped {
                beta: 0.1,
                phi: 0.9,
            },
            level: 10.0,
            slope: 1.0,
            ..EtsSpec::default()
        };
        let mut filter = EtsFilter::<1>::new(&spec).unwrap();
        assert!(filter.update(f64::NAN).value.is_nan());
        assert!((filter.level() - 10.9).abs() < 1e-12);
        assert!(filter.update(f64::INFINITY).value.is_nan());
        assert!(filter.update(12.0).value.is_finite());
    }

    #[test]
    fn rejects_bad_models() {
        let seasonal = [1.0, -1.0];
        let spec = EtsSpec {
            seasonal: &seasonal,
            ..EtsSpec::default()
        };
        assert_eq!(
            EtsFilter::<1>::new(&spec).unwrap_err(),
            FilterError::Capacity {
                needed: 2,
                capacity: 1
            }
        );
        let bad = EtsSpec {
            sigma2: 0.0,
            ..EtsSpec::default()
        };
        assert_eq!(
            EtsFilter::<1>::new(&bad).unwrap_err(),
            FilterError::InvalidParameter
        );
    }
}