Skip to main content

flair/
lib.rs

1#![no_std]
2extern crate core;
3extern crate alloc;
4#[cfg(feature = "std")]
5extern crate std;
6
7use core::{
8    fmt::{self, Display},
9    result::Result,
10};
11
12#[cfg(feature = "std")]
13use std::time::{SystemTime, UNIX_EPOCH};
14
15pub mod constants;
16pub mod double_exponential;
17pub mod flair;
18pub mod optshrink;
19pub mod svd;
20
21pub use flair::{
22    forecast,
23    forecast_mean,
24    forecast_quantiles
25};
26
27// ============================================================
28// NoiseMode
29// ============================================================
30
31/// Level noise sampling model.
32///
33/// Controls how stochastic Level paths are drawn during forecast assembly.
34///
35/// # Variants
36///
37/// - [`Bootstrap`](NoiseMode::Bootstrap) *(default)*: empirical resample of LOOCV residuals
38///   (preserves empirical skew/kurtosis). Automatically falls back to [`StudentT`](NoiseMode::StudentT)
39///   when fewer than 4 LOO residuals are available (very short series).
40/// - [`StudentT`](NoiseMode::StudentT): parametric Student-t with `ν = n_train − p` degrees of
41///   freedom, followed by post-hoc shrinkage toward the per-horizon median when `ν < 50`.
42///
43/// # Example
44///
45/// ```rust
46/// use flair::{forecast, Freq, NoiseMode};
47/// let y: Vec<f64> = (0..120).map(|i| 100.0 + 20.0 * (i as f64 * std::f64::consts::PI / 6.0).sin()).collect();
48/// let (paths, _) = forecast(&y, &Freq::Monthly, 12, 100, 0, None, NoiseMode::Bootstrap).unwrap();
49/// assert!(paths.iter().flat_map(|p| p.iter()).all(|v| v.is_finite()));
50/// ```
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum NoiseMode {
53    /// Empirical bootstrap resampling of LOOCV residuals (default).
54    #[default]
55    Bootstrap,
56    /// Parametric Student-t with post-hoc median shrinkage.
57    StudentT,
58}
59
60/// Returns a non-deterministic seed derived from the system clock.
61/// use like: `let forcast = flair::forecast(&y, 12, "M", 100, flair::seed_from_time());`
62#[cfg(feature = "std")]
63pub fn seed_from_time() -> u64 {
64    SystemTime::now()
65        .duration_since(UNIX_EPOCH)
66        .map(|d| d.subsec_nanos() as u64 ^ d.as_secs().wrapping_mul(0x9e3779b97f4a7c15))
67        .unwrap_or(0xdeadbeefcafe1234)
68}
69
70// ============================================================
71// Freq (required as arguments)
72// ============================================================
73
74#[derive(Debug)]
75pub enum Freq {
76    Secondly(usize),  // 10
77    Minutely(usize),  // 5, 10, 15, 30
78    Hourly(usize),    // 1, 2, 12
79    Daily,
80    Weekly,
81    Monthly,
82    Quarterly,
83    Yearly,
84}
85
86impl Freq {
87    pub fn secondly(n: usize) -> Result<Self, Error> {
88        match n {
89            10 => Ok(Freq::Secondly(n)),
90            _ => Err(Error::InvalidFreq(n)),
91        }
92    }
93    pub fn minutely(n: usize) -> Result<Self, Error> {
94        match n {
95            5 | 10 | 15 | 30 => Ok(Freq::Minutely(n)),
96            _ => Err(Error::InvalidFreq(n)),
97        }
98    }
99    pub fn hourly(n: usize) -> Result<Self, Error> {
100        match n {
101            1 | 2 | 12 => Ok(Freq::Hourly(n)),
102            _ => Err(Error::InvalidFreq(n)),
103        }
104    }
105}
106
107// ============================================================
108// Confidence (returned alongside forecasts)
109// ============================================================
110
111pub struct Confidence {
112    /// sigma_1^2 / sum(sigma_i^2): rank-1 signal strength (1.0 = single period, ~1/P = flat).
113    /// None for Yearly (P=1) or series too short for the Level x Shape decomposition.
114    pub rank1: Option<f64>,
115    /// Minimum Ridge LOOCV error; lower is more predictable.
116    pub gcv:   Option<f64>,
117}
118
119// ============================================================
120// Error (this crate can provide)
121// ============================================================
122
123#[derive(Debug, Clone)]
124pub enum Error {
125    InvalidFreq(usize),
126    InvalidInput(&'static str),
127    Svd(SvdError),
128}
129
130impl Display for Error {
131    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132        match self {
133            Error::InvalidFreq(n) => write!(f, "invalid frequency: {}", n),
134            Error::InvalidInput(msg) => write!(f, "invalid input: {}", msg),
135            Error::Svd(e) => write!(f, "svd error: {}", e),
136        }
137    }
138}
139
140#[derive(Debug, Clone)]
141pub enum SvdError {
142    DimensionMismatch,
143    ConvergenceFailed,
144}
145
146impl Display for SvdError {
147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148        match self {
149            SvdError::DimensionMismatch => write!(f, "dimension mismatch"),
150            SvdError::ConvergenceFailed => write!(f, "convergence failed"),
151        }
152    }
153}