use crate::filter::FilterError;
use crate::math;
use crate::normal::normal_quantile;
use crate::state_space::Innovation;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ThetaSpec<'a> {
pub alpha: f64,
pub drift: f64,
pub level: f64,
pub count: usize,
pub sigma2: f64,
pub seasonal: &'a [f64],
}
#[derive(Debug, Clone, Copy)]
pub struct ThetaFilter<const M: usize> {
alpha: f64,
drift: f64,
level: f64,
count: usize,
sigma2: f64,
seasonal: [f64; M],
m: usize,
head: usize,
}
impl<const M: usize> ThetaFilter<M> {
pub fn new(spec: &ThetaSpec<'_>) -> Result<Self, FilterError> {
let finite = [spec.alpha, spec.drift, spec.level, spec.sigma2]
.iter()
.all(|v| v.is_finite());
let valid = finite
&& spec.alpha > 0.0
&& spec.alpha <= 1.0
&& spec.sigma2 > 0.0
&& spec.seasonal.iter().all(|s| s.is_finite() && *s > 0.0);
if !valid {
return Err(FilterError::InvalidParameter);
}
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 {
alpha: spec.alpha,
drift: spec.drift,
level: spec.level,
count: spec.count,
sigma2: spec.sigma2,
seasonal,
m,
head: 0,
})
}
pub fn update(&mut self, y: f64) -> Innovation {
let mut forecast = [0.0; 1];
self.means_into(&mut forecast);
let innovation = Innovation {
value: if y.is_finite() {
y - forecast[0]
} else {
f64::NAN
},
variance: self.sigma2,
};
if y.is_finite() {
let adjusted = y / self.index(0);
self.level += self.alpha * (adjusted - self.level);
}
self.count = self.count.saturating_add(1);
if self.m > 0 {
self.head = (self.head + 1) % self.m;
}
innovation
}
pub fn forecast_into(&self, mean: &mut [f64], variance: &mut [f64]) {
assert_eq!(
mean.len(),
variance.len(),
"mean and variance must have the same length"
);
self.means_into(mean);
let alpha2 = self.alpha * self.alpha;
let mut steps = 0.0;
for value in variance.iter_mut() {
*value = self.sigma2 * (1.0 + steps * alpha2);
steps += 1.0;
}
}
pub fn forecast_interval_into(
&self,
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"
);
self.forecast_into(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;
}
}
#[must_use]
pub const fn level(&self) -> f64 {
self.level
}
fn means_into(&self, mean: &mut [f64]) {
let decay = if self.count == 0 {
1.0
} else {
math::exp(count_as_f64(self.count) * math::ln(1.0 - self.alpha))
};
let weight = (1.0 - decay) / self.alpha;
let mut steps = 0.0;
for (h, value) in mean.iter_mut().enumerate() {
*value = (self.level + self.drift * (steps + weight)) * self.index(h);
steps += 1.0;
}
}
fn index(&self, h: usize) -> f64 {
if self.m == 0 {
1.0
} else {
self.seasonal[(self.head + h) % self.m]
}
}
}
#[expect(
clippy::cast_precision_loss,
reason = "value counts stay far below 2^53, where the conversion is exact"
)]
fn count_as_f64(count: usize) -> f64 {
count as f64
}