use ndarray::Array2;
use solow_core::error::{Error, Result};
#[derive(Debug, Clone)]
pub struct DeterministicProcess {
steps: usize,
constant: bool,
order: usize,
seasonal: bool,
period: usize,
}
impl DeterministicProcess {
pub fn new(
steps: usize,
constant: bool,
order: usize,
seasonal: bool,
period: usize,
) -> Result<Self> {
if seasonal && period < 2 {
return Err(Error::Value(
"period must be >= 2 when seasonal terms are requested".into(),
));
}
Ok(Self {
steps,
constant,
order,
seasonal,
period,
})
}
fn n_seasonal(&self) -> usize {
if !self.seasonal {
0
} else if self.constant {
self.period - 1
} else {
self.period
}
}
pub fn ncols(&self) -> usize {
(self.constant as usize) + self.order + self.n_seasonal()
}
pub fn in_sample(&self) -> Array2<f64> {
let n = self.steps;
let k = self.ncols();
let mut out = Array2::<f64>::zeros((n, k));
for i in 0..n {
let mut col = 0;
if self.constant {
out[[i, col]] = 1.0;
col += 1;
}
let time = (i + 1) as f64;
for power in 1..=self.order {
out[[i, col]] = time.powi(power as i32);
col += 1;
}
if self.seasonal {
let phase = i % self.period; if self.constant {
if phase >= 1 {
out[[i, col + (phase - 1)]] = 1.0;
}
} else {
out[[i, col + phase]] = 1.0;
}
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constant_and_quadratic_trend() {
let dp = DeterministicProcess::new(3, true, 2, false, 0).unwrap();
let m = dp.in_sample();
assert_eq!(m.dim(), (3, 3));
assert_eq!(m[[0, 0]], 1.0);
assert_eq!(m[[0, 1]], 1.0);
assert_eq!(m[[0, 2]], 1.0);
assert_eq!(m[[2, 1]], 3.0);
assert_eq!(m[[2, 2]], 9.0);
}
#[test]
fn seasonal_with_constant_drops_first_period() {
let dp = DeterministicProcess::new(8, true, 0, true, 4).unwrap();
let m = dp.in_sample();
assert_eq!(m.dim(), (8, 4));
assert_eq!(m[[0, 0]], 1.0);
assert_eq!(m[[0, 1]], 0.0);
assert_eq!(m[[0, 2]], 0.0);
assert_eq!(m[[0, 3]], 0.0);
assert_eq!(m[[1, 1]], 1.0);
assert_eq!(m[[3, 3]], 1.0);
}
#[test]
fn seasonal_without_constant_keeps_all_dummies() {
let dp = DeterministicProcess::new(4, false, 0, true, 4).unwrap();
let m = dp.in_sample();
assert_eq!(m.dim(), (4, 4));
for i in 0..4 {
for j in 0..4 {
assert_eq!(m[[i, j]], if i == j { 1.0 } else { 0.0 });
}
}
}
#[test]
fn rejects_tiny_period() {
assert!(DeterministicProcess::new(4, true, 0, true, 1).is_err());
}
}