# backshift
[](https://crates.io/crates/backshift)
[](https://docs.rs/backshift/)
[](https://github.com/sunsided/arima-rs/actions/workflows/ci.yml)
[](#license)
ARIMA models for Rust, fitted by exact maximum likelihood, with a streaming filter that runs on targets without a heap.
A model is fitted wherever there is an allocator (a laptop, a server, statsmodels if you prefer), and its coefficients are
all a microcontroller needs to filter new values and forecast them with prediction intervals. The name is the backshift
operator `B` that ARIMA models are written in: `(1 - B)^d y_t` is the series differenced `d` times.
```rust
use backshift::{Arima, Filter};
let history = [0.3, 1.1, 0.4, -0.2, 0.9, 1.4, 0.6, 0.1, -0.5, 0.2, 0.8, 1.0, 0.3, -0.1, 0.4];
let fitted = Arima::new(1, 0, 0).fit(&history).unwrap();
println!("AIC {:.2}", fitted.aic());
// The device side needs only the coefficients.
let mut filter = Filter::<4>::new(&fitted.spec()).unwrap();
filter.warm_up(&history);
let innovation = filter.update(0.7).unwrap();
let (mut mean, mut lower, mut upper) = ([0.0; 3], [0.0; 3], [0.0; 3]);
filter.forecast_interval_into(0.95, &mut mean, &mut lower, &mut upper);
```
## Who is this for
The crate is for running ARIMA where a Python process won't fit: on a microcontroller watching a sensor, in WebAssembly,
or in a Rust service that would rather not link BLAS. The streaming filter is the part that sets it apart. Each new value
costs one Kalman step in `O(r²)` for `r = max(p, q + 1)` states, the innovation it returns doubles as an anomaly score
(its variance comes with it), and the whole state lives inline in a `Copy` struct.
If you need seasonal models, exogenous regressors or automatic order selection today, this crate doesn't have them yet.
statsmodels and R's `forecast` package have all three; in Rust, [`foresight`](https://crates.io/crates/foresight) offers
seasonal ARIMA and a stepwise auto-ARIMA, but does not build for bare-metal targets.
## What's in it
- `Arima::new(p, d, q).fit(y)`: exact Gaussian maximum likelihood with `sigma2` concentrated out, Hannan–Rissanen
starting values and an in-crate BFGS; AR and MA parts stay stationary and invertible through statsmodels' PACF
transforms. `Fitted` reports the log-likelihood, AIC, AICc and BIC.
- `Filter<R>`: built from an `ArimaSpec` alone, it differences raw values in place, returns one-step innovations,
treats `NaN` as missing, and forecasts original-scale means, variances and intervals. `R` is the state capacity,
`max(p, q + 1) + d`.
- `loglike` and `innovations` for any model size, through the same recursion as the filter.
- The building blocks: `acov`, `acorr`, `pacf`, `difference`, `integrate`, `yule_walker`, `burg`, `hannan_rissanen`
and `normal_quantile`.
## Running without a heap
The crate is `no_std`. With `default-features = false` pick one of the floating-point backends:
| `std` (default) | Everything, using the standard library's math functions. Implies `alloc`. |
| `libm` | Bare-metal targets: `TimeSeries`, `acov`/`acorr`, `Filter` and `normal_quantile`. No allocator needed. |
| `libm`, `alloc` | Bare-metal targets with an allocator: adds fitting, `pacf`, differencing and the estimators. |
```toml
[dependencies]
backshift = { version = "0.1", default-features = false, features = ["libm"] }
```
CI links a `no_std`/`no_main` binary for `thumbv7em-none-eabihf` that runs the filter and forecasts with intervals, and
a counting allocator asserts that `Filter::new`, `update`, `warm_up` and the forecasts allocate nothing. That binary
comes out at about 21 KB of `.text`. A `Filter<R>` takes about `8 (R² + 4R)` bytes; `Filter::new` needs about three
times that on the stack while it solves for the starting covariance.
## Checked against statsmodels
Every result is compared with statsmodels 0.14 on reference series generated by
[`scripts/generate_reference.py`](scripts/generate_reference.py):
| `acorr`, `pacf`, `acov`, `yule_walker`, `burg` | `acf`, `pacf(method="ldb")`, `acovf`, `yule_walker`, `burg` | 1e-9 (Burg's `sigma2`: 1e-8) |
| Log-likelihood, innovations, streaming | `SARIMAX(...).filter(params)`, `results.extend(...)` | 1e-9 |
| Forecast means, variances and intervals | `ARIMA(...).get_forecast(h)`, `conf_int(...)` | 1e-9 |
| `hannan_rissanen` | `hannan_rissanen(..., unbiased=False)` | 1e-9 |
| `Arima::fit` | `ARIMA(...).fit()` | log-likelihood never more than 1e-6 below statsmodels', parameters 5e-4 |
In practice the fit ends up 1e-9 to 6e-8 *above* statsmodels' log-likelihood; the parameter tolerance is loose because
two optimisers stop at slightly different points of a flat likelihood.
Three conventions differ from statsmodels' defaults on purpose:
- For `d > 0` the likelihood is that of the differenced series (statsmodels' `simple_differencing=True`, and what R's
`arima` does). statsmodels' default keeps the first `d` values through a diffuse start, which moves the log-likelihood
by about 1e-5; forecasts agree either way.
- BIC and AICc count only non-missing values, as R does. statsmodels counts missing ones too.
- The filter always runs the full Kalman recursion. statsmodels stops updating the state covariance once it changes by
less than 1e-19, which moves later innovations by up to about 1e-9, so the references are generated with
`ssm.tolerance = 0`.
## Status
Version 0.1 covers non-seasonal ARIMA(p, d, q) with an optional mean or drift. Seasonal models, exogenous regressors,
diagnostics (Ljung–Box, KPSS) and automatic order selection are planned, roughly in that order; the
[roadmap](https://github.com/sunsided/arima-rs/blob/main/docs/ROADMAP.md) has the details. The minimum supported Rust
version is 1.85.
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <https://opensource.org/licenses/MIT>)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as
defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.