use crate::math;
use core::error::Error;
use core::f64::consts::TAU;
use core::fmt::{Display, Formatter};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FourierError {
InvalidTerms,
RowLength {
needed: usize,
got: usize,
},
}
impl Display for FourierError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
FourierError::InvalidTerms => {
write!(f, "need 1 <= K and 2K <= period, with a finite period")
}
FourierError::RowLength { needed, got } => {
write!(f, "a row needs {needed} entries, got {got}")
}
}
}
}
impl Error for FourierError {}
#[must_use]
pub fn fourier_columns(period: f64, k: usize) -> usize {
k.saturating_mul(2) - usize::from(is_nyquist(period, k))
}
pub fn fourier_row(period: f64, k: usize, t: u64, row: &mut [f64]) -> Result<(), FourierError> {
let needed = validate(period, k)?;
if row.len() != needed {
return Err(FourierError::RowLength {
needed,
got: row.len(),
});
}
let phase = t as f64 % period;
let mut slots = row.iter_mut();
for i in 1..=k {
let angle = TAU * ((i as f64 * phase) % period) / period;
if !(i == k && is_nyquist(period, k)) {
*slots.next().expect("one slot per column: checked above") = math::sin(angle);
}
*slots.next().expect("one slot per column: checked above") = math::cos(angle);
}
Ok(())
}
fn validate(period: f64, k: usize) -> Result<usize, FourierError> {
if k == 0 || !period.is_finite() || 2.0 * k as f64 > period {
return Err(FourierError::InvalidTerms);
}
Ok(fourier_columns(period, k))
}
fn is_nyquist(period: f64, k: usize) -> bool {
k > 0 && 2.0 * k as f64 == period
}
#[cfg(feature = "alloc")]
pub fn fourier(
terms: &[(f64, usize)],
t0: u64,
rows: usize,
) -> Result<alloc::vec::Vec<f64>, FourierError> {
if terms.is_empty() {
return Err(FourierError::InvalidTerms);
}
let widths = terms
.iter()
.map(|&(period, k)| validate(period, k))
.collect::<Result<alloc::vec::Vec<_>, _>>()?;
let columns: usize = widths.iter().sum();
let len = rows
.checked_mul(columns)
.expect("the regressor matrix fits in memory");
let mut out = alloc::vec![0.0; len];
for (row, t) in out.chunks_exact_mut(columns).zip(t0..) {
let mut rest = row;
for (&(period, k), &width) in terms.iter().zip(&widths) {
let (part, tail) = rest.split_at_mut(width);
fourier_row(period, k, t, part)?;
rest = tail;
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn drops_the_nyquist_sine() {
assert_eq!(fourier_columns(4.0, 2), 3);
assert_eq!(fourier_columns(4.5, 2), 4);
let mut row = [0.0; 3];
fourier_row(4.0, 2, 1, &mut row).unwrap();
assert!((row[0] - 1.0).abs() < 1e-15);
assert!(row[1].abs() < 1e-15);
assert!((row[2] + 1.0).abs() < 1e-15);
}
#[test]
fn rejects_bad_terms_and_rows() {
let mut row = [0.0; 4];
assert_eq!(
fourier_row(3.0, 2, 0, &mut row),
Err(FourierError::InvalidTerms)
);
assert_eq!(
fourier_row(7.0, 0, 0, &mut row),
Err(FourierError::InvalidTerms)
);
assert_eq!(
fourier_row(f64::NAN, 1, 0, &mut row),
Err(FourierError::InvalidTerms)
);
assert_eq!(
fourier_row(7.0, 1, 0, &mut row),
Err(FourierError::RowLength { needed: 2, got: 4 })
);
}
#[cfg(feature = "alloc")]
#[test]
fn rejects_empty_terms() {
assert_eq!(fourier(&[], 0, 5), Err(FourierError::InvalidTerms));
}
#[test]
fn does_not_drift_over_many_periods() {
let (mut early, mut late) = ([0.0; 6], [0.0; 6]);
fourier_row(365.25, 3, 17, &mut early).unwrap();
fourier_row(365.25, 3, 17 + 1461 * 684_462_696, &mut late).unwrap();
for (a, b) in early.iter().zip(&late) {
assert!((a - b).abs() < 1e-12, "{a} vs {b}");
}
}
#[test]
fn no_harmonics_have_no_columns() {
assert_eq!(fourier_columns(0.0, 0), 0);
}
}