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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! The optimiser's view of one ETS model: its parameter vector, the recursion runs that
//! score it, and R's bounds and admissibility checks.
//!
//! A model with an additive error and additive components is linear in its initial
//! states, so for given smoothing parameters the best states follow by least squares
//! ([`Layout::best_states`]), and the optimiser searches only the smoothing parameters. With
//! a multiplicative error or season that no longer holds, so the optimiser carries the
//! initial states too ([`Layout::concentrated`] is false), as R does.

use super::super::hannan_rissanen::cholesky_solve;
use super::super::roots::roots_inside;
use super::Ets;
use crate::ets::{Form, Smoothing, unroll};
use crate::math;
use crate::optimize::brent;
use alloc::vec;
use alloc::vec::Vec;

/// R's "usual" lower bound of `alpha`, `beta` and `gamma`.
const LOWER: f64 = 1e-4;

/// R's "usual" upper bound of `alpha`, `beta` and `gamma`.
const UPPER: f64 = 0.9999;

/// R's bounds of the damping parameter `phi`.
pub(super) const PHI_BOUNDS: (f64, f64) = (0.8, 0.98);

/// The grid of starting points, as fractions of each smoothing parameter's range: `alpha`
/// takes every value, `beta`, `gamma` and `phi` the values of their own grid.
///
/// The likelihood can have more than one local optimum in the smoothing parameters. One
/// evaluation per grid point is cheap next to an optimisation, so the fit scores the grid
/// and runs BFGS from the best [`REFINED`] points only.
const ALPHA_GRID: [f64; 6] = [0.01, 0.05, 0.15, 0.3, 0.5, 0.8];

/// The grid of `beta`, as fractions of its range `[lower, alpha]`; see [`ALPHA_GRID`].
const BETA_GRID: [f64; 3] = [0.01, 0.3, 0.99];

/// The grid of `gamma`, as fractions of its range `[lower, 1 - alpha]`; see [`ALPHA_GRID`].
const GAMMA_GRID: [f64; 2] = [0.01, 0.3];

/// The grid of `phi`, as fractions of its range `[0.8, 0.98]`; see [`ALPHA_GRID`].
const PHI_GRID: [f64; 2] = [0.5, 0.99];

/// How many of the best grid points the fit refines with BFGS when the initial states are
/// concentrated out.
const REFINED: usize = 2;

/// How far beyond the first or last point of [`ALPHA_GRID`] [`Layout::alpha_search`]
/// searches, in logit units: far enough that `alpha` reaches R's bounds to within 1e-8 of
/// its range, where random walks put the optimum.
const EDGE: f64 = 20.0;

/// How many it refines when the optimiser also carries the initial states, whose likelihood
/// has more local optima (on the R suite's ETS(M,Ad,N) the third-best start ends 1.05 higher
/// than the best two).
const REFINED_JOINT: usize = 4;

/// The optimiser's vector `u` for one model: the unconstrained smoothing parameters
/// (`alpha`, then `beta`, `gamma` and `phi` where the model has them), followed by the free
/// initial states unless they are concentrated out (level, slope with a trend, then the
/// first `m - 1` seasonal states, most recent first).
#[derive(Debug, Clone, Copy)]
pub(super) struct Layout {
    /// The model.
    pub(super) model: Ets,
}

impl Layout {
    /// The layout of `model`.
    pub(super) const fn of(model: &Ets) -> Self {
        Self { model: *model }
    }

    /// Whether the initial states are concentrated out by least squares: only for an
    /// additive error with additive components, where the errors are linear in them.
    pub(super) fn concentrated(&self) -> bool {
        self.model.error == Form::Additive && !self.multiplicative_season()
    }

    /// Whether the model has a season that multiplies the forecast.
    fn multiplicative_season(&self) -> bool {
        self.model.period > 0 && self.model.season == Form::Multiplicative
    }

    /// The number of smoothing parameters: `alpha`, and `beta`, `gamma`, `phi` where used.
    pub(super) const fn smoothing_len(&self) -> usize {
        let model = &self.model;
        1 + (model.trend as usize) + ((model.period > 0) as usize) + (model.damped as usize)
    }

    /// The number of free initial states: the level, the slope with a trend, and `m - 1`
    /// seasonal states (the last follows from the others).
    pub(super) const fn states_len(&self) -> usize {
        1 + (self.model.trend as usize) + self.model.period.saturating_sub(1)
    }

    /// The [`REFINED`] (or [`REFINED_JOINT`]) grid points with the lowest objective, as
    /// optimiser vectors. Without concentration each point carries the starting states
    /// `start`.
    pub(super) fn best_starts(&self, y: &[f64], start: &[f64]) -> Vec<Vec<f64>> {
        let mut scored: Vec<(f64, Vec<f64>)> = self
            .grid()
            .into_iter()
            .map(|mut u| {
                if !self.concentrated() {
                    u.extend_from_slice(start);
                }
                (objective(self, y, &u), u)
            })
            .collect();
        scored.sort_by(|a, b| a.0.total_cmp(&b.0));
        let refined = if self.concentrated() {
            REFINED
        } else {
            REFINED_JOINT
        };
        scored.into_iter().take(refined).map(|(_, u)| u).collect()
    }

    /// The optimiser vector of a model whose only free parameter is `alpha` (no trend, no
    /// season, the initial level concentrated out), or `None` if no grid point scores.
    ///
    /// A one-parameter likelihood needs no BFGS: the best point of [`ALPHA_GRID`] brackets
    /// the optimum with its neighbours, and Brent's method finds it in a few evaluations.
    pub(super) fn alpha_search(&self, y: &[f64]) -> Option<Vec<f64>> {
        debug_assert!(self.concentrated() && self.smoothing_len() == 1);
        let points = ALPHA_GRID.map(logit);
        let scores = points.map(|u| objective(self, y, &[u]));
        let (best, &score) = scores
            .iter()
            .enumerate()
            .filter(|(_, value)| value.is_finite())
            .min_by(|a, b| a.1.total_cmp(b.1))?;
        let low = points
            .get(best.wrapping_sub(1))
            .copied()
            .unwrap_or(points[0] - EDGE);
        let high = points.get(best + 1).copied().unwrap_or(points[best] + EDGE);
        let (u, value) = brent(|u| objective(self, y, &[u]), (low, high), 0.0);

        Some(vec![if value < score { u } else { points[best] }])
    }

    /// Every grid point of [`ALPHA_GRID`] and the grids of the model's other parameters, as
    /// unconstrained smoothing parameters (the logits of the fractions).
    fn grid(&self) -> Vec<Vec<f64>> {
        let model = &self.model;
        let axes: [&[f64]; 4] = [
            &ALPHA_GRID,
            if model.trend { &BETA_GRID } else { &[] },
            if model.period > 0 { &GAMMA_GRID } else { &[] },
            if model.damped { &PHI_GRID } else { &[] },
        ];
        let mut points = vec![Vec::new()];
        for axis in axes.iter().filter(|axis| !axis.is_empty()) {
            points = points
                .iter()
                .flat_map(|point| {
                    axis.iter().map(move |&fraction| {
                        let mut next: Vec<f64> = point.clone();
                        next.push(logit(fraction));
                        next
                    })
                })
                .collect();
        }

        points
    }

    /// The smoothing parameters `u` maps to, within R's usual bounds: `beta < alpha`,
    /// `gamma < 1 - alpha`.
    pub(super) fn smoothing(&self, u: &[f64]) -> Smoothing {
        let model = &self.model;
        let mut next = u.iter().copied();
        let mut take = || next.next().unwrap_or(0.0);
        let alpha = LOWER + (UPPER - LOWER) * logistic(take());
        let beta = if model.trend {
            LOWER + (alpha.min(UPPER) - LOWER) * logistic(take())
        } else {
            0.0
        };
        let gamma = if model.period > 0 {
            LOWER + ((1.0 - alpha).min(UPPER) - LOWER) * logistic(take())
        } else {
            0.0
        };
        let phi = if model.damped {
            PHI_BOUNDS.0 + (PHI_BOUNDS.1 - PHI_BOUNDS.0) * logistic(take())
        } else {
            1.0
        };

        Smoothing {
            alpha,
            beta,
            gamma,
            phi,
            trend: model.trend,
            multiplicative_season: self.multiplicative_season(),
        }
    }

    /// Writes the seasonal part of the free states `free` into `seasonal` and returns the
    /// level and slope. The last seasonal state makes them sum to 0 (additive) or `m`
    /// (multiplicative), as R constrains them.
    pub(super) fn expand(&self, free: &[f64], seasonal: &mut [f64]) -> (f64, f64) {
        let level = free[0];
        let slope = if self.model.trend { free[1] } else { 0.0 };
        let rest = &free[1 + usize::from(self.model.trend)..];
        if let Some(last) = seasonal.len().checked_sub(1) {
            let total = if self.multiplicative_season() {
                count_as_f64(seasonal.len())
            } else {
                0.0
            };
            seasonal[..last].copy_from_slice(rest);
            seasonal[last] = total - rest.iter().sum::<f64>();
        }

        (level, slope)
    }

    /// Runs the recursion over `y` from the free states `free` and writes the one-step
    /// errors `y - f` into `errors`. Leaves the final seasonal states in `seasonal` as a ring
    /// and returns the final level, slope and the ring's head (see [`unroll`]).
    fn errors(
        &self,
        smoothing: &Smoothing,
        free: &[f64],
        y: &[f64],
        seasonal: &mut [f64],
        errors: &mut [f64],
    ) -> (f64, f64, usize) {
        let (level, slope) = self.expand(free, seasonal);
        recurse(smoothing, level, slope, seasonal, y, errors)
    }

    /// The free initial states that minimise the residual sum of squares at `smoothing`, or
    /// [`None`] if the least-squares problem is singular. Only for [`Layout::concentrated`]
    /// models.
    ///
    /// The errors are `e = e_0 + E x` in the free states `x`: `e_0` from the data with all
    /// states 0, and column `j` of `E` from all-zero data with state `j` at 1. The fit needs
    /// more values than states, which [`Ets::fit`] checks.
    fn best_states(&self, smoothing: &Smoothing, y: &[f64]) -> Option<Vec<f64>> {
        let (n, k) = (y.len(), self.states_len());
        let mut seasonal = vec![0.0; self.model.period];
        let mut base = vec![0.0; n];
        self.errors(smoothing, &vec![0.0; k], y, &mut seasonal, &mut base);
        let columns = self.state_columns(smoothing, n);

        // The normal equations of `E x = -e_0`: `E'E x = -E'e_0`, lower triangle only.
        let mut gram = vec![vec![0.0; k]; k];
        let mut moment = vec![0.0; k];
        for (i, column_i) in columns.chunks_exact(n).enumerate() {
            moment[i] = -column_i.iter().zip(&base).map(|(c, e)| c * e).sum::<f64>();
            for (j, column_j) in columns.chunks_exact(n).take(i + 1).enumerate() {
                gram[i][j] = column_i.iter().zip(column_j).map(|(a, b)| a * b).sum();
            }
        }

        cholesky_solve(gram, moment)
    }

    /// The columns of `E`, all `k` back to back: the one-step errors over `n` all-zero values
    /// from each free initial state at 1.
    ///
    /// Three recursion passes give them all: the level, the slope, and the oldest seasonal
    /// state. With zero data a state whose forecast error is zero only ages, so a unit in
    /// the seasonal state `j` places from the oldest acts as one in the oldest, `j` steps
    /// later. A free seasonal state `j` is that unit less one in the oldest state (the
    /// oldest makes them sum to zero).
    fn state_columns(&self, smoothing: &Smoothing, n: usize) -> Vec<f64> {
        let k = self.states_len();
        let leading = 1 + usize::from(self.model.trend);
        let zeros = vec![0.0; n];
        let mut seasonal = vec![0.0; self.model.period];
        let mut columns = vec![0.0; k * n];
        let mut unit = vec![0.0; k];
        for (j, column) in columns.chunks_exact_mut(n).take(leading).enumerate() {
            unit.fill(0.0);
            unit[j] = 1.0;
            self.errors(smoothing, &unit, &zeros, &mut seasonal, column);
        }

        let m = self.model.period;
        if m == 0 {
            return columns;
        }

        // The oldest seasonal state at 1 and all other states at 0, which the free states
        // cannot express (the oldest is minus their sum), so the recursion starts from them.
        seasonal.fill(0.0);
        seasonal[m - 1] = 1.0;
        let mut oldest = vec![0.0; n];
        recurse(smoothing, 0.0, 0.0, &mut seasonal, &zeros, &mut oldest);
        for (j, column) in columns.chunks_exact_mut(n).skip(leading).enumerate() {
            // Free state `j` is `m - 1 - j` places from the oldest.
            let delay = m - 1 - j;
            for (t, value) in column.iter_mut().enumerate() {
                let aged = t.checked_sub(delay).map_or(0.0, |s| oldest[s]);
                *value = aged - oldest[t];
            }
        }

        columns
    }

    /// Takes the initial states at `u` (solved for, or read from `u`) and runs the
    /// recursion over `y`, or [`None`] if the parameters are not admissible, the states
    /// cannot be solved for, or a multiplicative model leaves positive values.
    pub(super) fn run(&self, y: &[f64], u: &[f64]) -> Option<Run> {
        let smoothing = self.smoothing(u);
        if !admissible(&smoothing, self.model.period) {
            return None;
        }

        let initial = if self.concentrated() {
            self.best_states(&smoothing, y)?
        } else {
            u[self.smoothing_len()..].to_vec()
        };
        let mut ring = vec![0.0; self.model.period];
        let mut errors = vec![0.0; y.len()];
        let (level, slope, head) = self.errors(&smoothing, &initial, y, &mut ring, &mut errors);
        let (sse, log_forecasts) = self.score(y, &errors)?;
        let mut seasonal = vec![0.0; self.model.period];
        unroll(&ring, head, &mut seasonal);
        if self.multiplicative_season() && !self.positive_seasons(&initial) {
            return None;
        }

        Some(Run {
            smoothing,
            sse,
            log_forecasts,
            initial,
            level,
            slope,
            seasonal,
        })
    }

    /// The residual sum of squares and `sum ln |f|` (0 with an additive error) of the
    /// errors `y - f`, or [`None`] where a multiplicative error meets a zero forecast.
    fn score(&self, y: &[f64], errors: &[f64]) -> Option<(f64, f64)> {
        if self.model.error == Form::Additive {
            return Some((errors.iter().map(|e| e * e).sum(), 0.0));
        }

        let (mut sse, mut log_forecasts) = (0.0, 0.0);
        for (&value, &error) in y.iter().zip(errors) {
            let forecast = value - error;
            if forecast == 0.0 || !forecast.is_finite() {
                return None;
            }

            let relative = error / forecast;
            sse += relative * relative;
            log_forecasts += math::ln(forecast.abs());
        }

        Some((sse, log_forecasts))
    }

    /// Whether every initial seasonal state of a multiplicative season is positive, as R
    /// requires.
    fn positive_seasons(&self, initial: &[f64]) -> bool {
        let mut seasonal = vec![0.0; self.model.period];
        self.expand(initial, &mut seasonal);
        seasonal.iter().all(|&s| s > 0.0)
    }
}

/// Runs the recursion over `y` from the given states, with the seasonal ring `seasonal` (most
/// recent first, head 0), and writes the one-step errors `y - f` into `errors`. Returns the
/// final level, slope and the ring's head.
fn recurse(
    smoothing: &Smoothing,
    mut level: f64,
    mut slope: f64,
    seasonal: &mut [f64],
    y: &[f64],
    errors: &mut [f64],
) -> (f64, f64, usize) {
    let mut head = 0;
    for (&value, error) in y.iter().zip(errors.iter_mut()) {
        *error = value - smoothing.forecast(level, slope, seasonal, head);
        smoothing.update(&mut level, &mut slope, seasonal, &mut head, value);
    }

    (level, slope, head)
}

/// What one pass of the recursion leaves: the parameters, the sums the likelihood needs, the
/// fitted initial states and the states after the last value.
#[derive(Debug, Clone)]
pub(super) struct Run {
    /// The smoothing parameters.
    pub(super) smoothing: Smoothing,
    /// The sum of the squared one-step errors, relative to the forecasts with a
    /// multiplicative error.
    pub(super) sse: f64,
    /// `sum ln |f|` over the one-step forecasts with a multiplicative error; 0 otherwise.
    pub(super) log_forecasts: f64,
    /// The free initial states: level, slope (with a trend), then `m - 1` seasonal states.
    pub(super) initial: Vec<f64>,
    /// The level after the last value.
    pub(super) level: f64,
    /// The slope after the last value.
    pub(super) slope: f64,
    /// The seasonal states after the last value, most recent first.
    pub(super) seasonal: Vec<f64>,
}

/// The fitting objective at `u`: R's `lik / (2 n)`, `0.5 ln(SSE / n) + sum ln |f| / n`, the
/// negative concentrated log-likelihood per value up to a constant, or `+inf` where it
/// cannot be evaluated.
pub(super) fn objective(layout: &Layout, y: &[f64], u: &[f64]) -> f64 {
    match layout.run(y, u) {
        Some(run) if run.sse > 0.0 && run.sse.is_finite() => {
            let n = count_as_f64(y.len());
            0.5 * math::ln(run.sse / n) + run.log_forecasts / n
        }
        _ => f64::INFINITY,
    }
}

/// R's `admissible`: the parameters give a forecastable model (the weights of past errors
/// decay). For seasonal models it checks the roots of the characteristic polynomial.
fn admissible(smoothing: &Smoothing, m: usize) -> bool {
    let Smoothing {
        alpha,
        beta,
        gamma,
        phi,
        trend,
        ..
    } = *smoothing;
    if !(0.0..=1.0 + 1e-8).contains(&phi) {
        return false;
    }

    if m == 0 {
        let level_ok = alpha >= 1.0 - 1.0 / phi && alpha <= 1.0 + 1.0 / phi;
        let slope_ok =
            !trend || (beta >= alpha * (phi - 1.0) && beta <= (1.0 + phi) * (2.0 - alpha));
        return level_ok && slope_ok;
    }

    seasonal_admissible(alpha, beta, gamma, phi, m)
}

/// The seasonal part of R's `admissible`, roots included.
fn seasonal_admissible(alpha: f64, beta: f64, gamma: f64, phi: f64, m: usize) -> bool {
    let mf = count_as_f64(m);
    let gamma_ok = gamma >= (1.0 - 1.0 / phi - alpha).max(0.0) && gamma <= 1.0 + 1.0 / phi - alpha;
    let alpha_ok =
        alpha >= 1.0 - 1.0 / phi - gamma * (1.0 - mf + phi + phi * mf) / (2.0 * phi * mf);
    let beta_ok = beta >= -(1.0 - phi) * (gamma / mf + alpha);
    if !(gamma_ok && alpha_ok && beta_ok) {
        return false;
    }

    // R's `P`, in increasing powers, is `phi (1 - alpha - gamma)`, `alpha + beta - alpha phi
    // + gamma - 1`, `m - 2` times `alpha + beta - alpha phi`, `alpha + beta - phi`, then 1.
    // Its roots are those of `z^(m + 1) + a_1 z^m + ... + a_(m + 1)` with `a` reversed.
    let middle = alpha + beta - alpha * phi;
    let mut a = vec![alpha + beta - phi];
    a.extend(core::iter::repeat_n(middle, m - 2));
    a.push(middle + gamma - 1.0);
    a.push(phi * (1.0 - alpha - gamma));
    roots_inside(&a, 1.0 + 1e-10)
}

/// The logistic function `1 / (1 + e^-u)`.
fn logistic(u: f64) -> f64 {
    1.0 / (1.0 + math::exp(-u))
}

/// The inverse of [`logistic`] for `0 < p < 1`.
fn logit(p: f64) -> f64 {
    math::ln(p / (1.0 - p))
}

/// A count as a float. Counts here are series lengths and periods, far below 2^53.
#[expect(
    clippy::cast_precision_loss,
    reason = "series lengths and parameter counts stay far below 2^53, where the conversion is exact"
)]
pub(super) fn count_as_f64(count: usize) -> f64 {
    count as f64
}

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

    #[test]
    fn concentrated_states_minimise_the_squared_errors() {
        // Checks the state columns directly: at fixed smoothing, moving any free state off
        // the least-squares solution must not lower the sum of squared errors.
        let layout = Layout::of(&Ets::new().damped().seasonal(4));
        let smoothing = layout.smoothing(&[-1.0, -2.0, -1.5, 0.5]);
        let y: Vec<f64> = (0..40)
            .map(|t| {
                let t = f64::from(t);
                20.0 + 0.3 * t + [2.0, -1.0, 0.5, -1.5][(t as usize) % 4] + (t * 1.7).sin()
            })
            .collect();
        let best = layout.best_states(&smoothing, &y).unwrap();
        let sse = |free: &[f64]| {
            let (mut ring, mut errors) = (vec![0.0; 4], vec![0.0; y.len()]);
            layout.errors(&smoothing, free, &y, &mut ring, &mut errors);
            errors.iter().map(|e| e * e).sum::<f64>()
        };
        let minimum = sse(&best);
        for j in 0..best.len() {
            for step in [-1e-3, 1e-3] {
                let mut moved = best.clone();
                moved[j] += step;
                assert!(sse(&moved) > minimum, "state {j}, step {step}");
            }
        }
    }

    #[test]
    fn transforms_respect_rs_bounds() {
        let layout = Layout::of(&Ets::new().damped().seasonal(4));
        for u in [-40.0, 0.0, 40.0] {
            let s = layout.smoothing(&[u, u, u, u]);
            assert!((LOWER..=UPPER).contains(&s.alpha));
            assert!(s.beta >= LOWER && s.beta <= s.alpha + 1e-12);
            assert!(s.gamma >= LOWER - 1e-12 && s.gamma <= 1.0 - s.alpha + 1e-12);
            assert!((PHI_BOUNDS.0..=PHI_BOUNDS.1).contains(&s.phi));
        }
    }

    #[test]
    fn seasonal_states_sum_to_their_constraint() {
        let additive = Layout::of(&Ets::new().seasonal(3));
        let mut seasonal = [0.0; 3];
        assert_eq!(
            additive.expand(&[10.0, 1.5, -0.5], &mut seasonal),
            (10.0, 0.0)
        );
        assert_eq!(seasonal, [1.5, -0.5, -1.0]);

        let model = Ets::new()
            .error(Form::Multiplicative)
            .seasonal(3)
            .season(Form::Multiplicative);
        Layout::of(&model).expand(&[10.0, 1.2, 0.9], &mut seasonal);
        assert!((seasonal[2] - 0.9).abs() < 1e-12);
    }
}