Skip to main content

solow_tsa/
deterministic.rs

1//! Deterministic trend/seasonal term construction.
2//!
3//! [`DeterministicProcess`] builds the in-sample design matrix of deterministic
4//! regressors (a constant, polynomial time trends, and seasonal dummies) used
5//! by time-series models, mirroring the reference `tsa.deterministic`
6//! `DeterministicProcess(...).in_sample()` term matrix.
7
8use ndarray::Array2;
9use solow_core::error::{Error, Result};
10
11/// Builder for a matrix of deterministic time-series terms.
12///
13/// Configure with a constant, a polynomial time-trend `order`, and optional
14/// seasonal dummies of a given `period`, then call [`Self::in_sample`] to
15/// materialise the `steps × k` term matrix.
16///
17/// Column order is `[const?, trend, trend_squared, ..., seasonal dummies?]`.
18/// When the constant is present the first seasonal period is used as the
19/// reference category and dropped, yielding `period - 1` dummy columns named
20/// `s(2,period)..s(period,period)`; otherwise all `period` dummies are kept.
21/// The time index for the trend terms runs `1, 2, ..., steps`.
22#[derive(Debug, Clone)]
23pub struct DeterministicProcess {
24    steps: usize,
25    constant: bool,
26    order: usize,
27    seasonal: bool,
28    period: usize,
29}
30
31impl DeterministicProcess {
32    /// Create a process spanning `steps` in-sample observations.
33    ///
34    /// `constant` toggles the intercept column, `order` is the degree of the
35    /// polynomial time trend (0 disables it), and `seasonal` toggles seasonal
36    /// dummies with the given `period` (which must be at least 2 when seasonal
37    /// terms are requested).
38    pub fn new(
39        steps: usize,
40        constant: bool,
41        order: usize,
42        seasonal: bool,
43        period: usize,
44    ) -> Result<Self> {
45        if seasonal && period < 2 {
46            return Err(Error::Value(
47                "period must be >= 2 when seasonal terms are requested".into(),
48            ));
49        }
50        Ok(Self {
51            steps,
52            constant,
53            order,
54            seasonal,
55            period,
56        })
57    }
58
59    /// Number of deterministic seasonal dummy columns.
60    fn n_seasonal(&self) -> usize {
61        if !self.seasonal {
62            0
63        } else if self.constant {
64            self.period - 1
65        } else {
66            self.period
67        }
68    }
69
70    /// Total number of deterministic columns produced by [`Self::in_sample`].
71    pub fn ncols(&self) -> usize {
72        (self.constant as usize) + self.order + self.n_seasonal()
73    }
74
75    /// Materialise the in-sample deterministic term matrix.
76    ///
77    /// The result has shape `(steps, ncols)` with columns ordered
78    /// `[const?, trend^1..trend^order, seasonal dummies?]`.
79    pub fn in_sample(&self) -> Array2<f64> {
80        let n = self.steps;
81        let k = self.ncols();
82        let mut out = Array2::<f64>::zeros((n, k));
83        for i in 0..n {
84            let mut col = 0;
85            if self.constant {
86                out[[i, col]] = 1.0;
87                col += 1;
88            }
89            // Polynomial trend with time index starting at 1.
90            let time = (i + 1) as f64;
91            for power in 1..=self.order {
92                out[[i, col]] = time.powi(power as i32);
93                col += 1;
94            }
95            // Seasonal dummies.
96            if self.seasonal {
97                let phase = i % self.period; // 0-based period within cycle
98                if self.constant {
99                    // Reference category is phase 0 (period 1); dummies cover
100                    // phases 1..period-1 mapping to columns s(2,p)..s(p,p).
101                    if phase >= 1 {
102                        out[[i, col + (phase - 1)]] = 1.0;
103                    }
104                } else {
105                    out[[i, col + phase]] = 1.0;
106                }
107            }
108        }
109        out
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn constant_and_quadratic_trend() {
119        let dp = DeterministicProcess::new(3, true, 2, false, 0).unwrap();
120        let m = dp.in_sample();
121        assert_eq!(m.dim(), (3, 3));
122        // [const, trend, trend_squared].
123        assert_eq!(m[[0, 0]], 1.0);
124        assert_eq!(m[[0, 1]], 1.0);
125        assert_eq!(m[[0, 2]], 1.0);
126        assert_eq!(m[[2, 1]], 3.0);
127        assert_eq!(m[[2, 2]], 9.0);
128    }
129
130    #[test]
131    fn seasonal_with_constant_drops_first_period() {
132        let dp = DeterministicProcess::new(8, true, 0, true, 4).unwrap();
133        let m = dp.in_sample();
134        // const + (period-1) dummies.
135        assert_eq!(m.dim(), (8, 4));
136        // Row 0 (phase 0) -> all dummies zero, const 1.
137        assert_eq!(m[[0, 0]], 1.0);
138        assert_eq!(m[[0, 1]], 0.0);
139        assert_eq!(m[[0, 2]], 0.0);
140        assert_eq!(m[[0, 3]], 0.0);
141        // Row 1 (phase 1) -> s(2,4) = 1.
142        assert_eq!(m[[1, 1]], 1.0);
143        // Row 3 (phase 3) -> s(4,4) = 1.
144        assert_eq!(m[[3, 3]], 1.0);
145    }
146
147    #[test]
148    fn seasonal_without_constant_keeps_all_dummies() {
149        let dp = DeterministicProcess::new(4, false, 0, true, 4).unwrap();
150        let m = dp.in_sample();
151        assert_eq!(m.dim(), (4, 4));
152        // Identity-like block: row i has a 1 in column i.
153        for i in 0..4 {
154            for j in 0..4 {
155                assert_eq!(m[[i, j]], if i == j { 1.0 } else { 0.0 });
156            }
157        }
158    }
159
160    #[test]
161    fn rejects_tiny_period() {
162        assert!(DeterministicProcess::new(4, true, 0, true, 1).is_err());
163    }
164}