backshift 0.3.0

Time-series forecasting checked against R and statsmodels: ARIMA, ETS, Theta, VAR, Croston/TSB, GARCH and changepoint detection, with streaming filters that run without a heap
Documentation
# Generate R reference vectors for the Croston conformance tests.
#
# Writes `tests/it/r_croston_data.rs`. R's packages are pinned by the Docker image in
# `scripts/r/`; run from the repository root:
#
#     docker build -t backshift-r-reference scripts/r
#     docker run --rm -v "$PWD":/work backshift-r-reference Rscript scripts/generate_r_croston_reference.R
#
# The series are simulated here with fixed seeds and stored in the output, so the tests do
# not depend on R's random number generator.

suppressPackageStartupMessages(library(forecast))

out <- "tests/it/r_croston_data.rs"

source("scripts/r/rust_literals.R")

lines <- c(
  "//! R reference vectors for the Croston conformance tests.",
  "//!",
  sprintf("//! Generated by `scripts/generate_r_croston_reference.R` with %s and forecast %s.",
          R.version.string, as.character(packageVersion("forecast"))),
  "//! Do not edit by hand; rerun the script instead.",
  "",
  "/// A `croston(values, h = 5, alpha)` forecast.",
  "pub struct CrostonCase {",
  "    /// The demand series, zeros for periods without demand.",
  "    pub values: &'static [f64],",
  "    /// The smoothing parameter of both the sizes and the intervals.",
  "    pub alpha: f64,",
  "    /// The forecast for every horizon (Croston's forecast is flat).",
  "    pub forecast: f64,",
  "    /// The one-step forecast of each value from the values before it; `NaN` until R has",
  "    /// one.",
  "    pub fitted: &'static [f64],",
  "}",
  ""
)
emit <- function(...) lines <<- c(lines, ...)

simulate <- function(n, probability, seed) {
  set.seed(seed)
  occurs <- runif(n) < probability
  round(ifelse(occurs, rgamma(n, shape = 2, rate = 0.5), 0), 2)
}

cases <- list(
  list(name = "SPARSE", alpha = 0.1, values = simulate(60, 0.25, 61)),
  list(name = "FREQUENT", alpha = 0.25, values = simulate(50, 0.6, 62))
)

for (case in cases) {
  fc <- croston(case$values, h = 5, alpha = case$alpha)
  emit(
    sprintf("/// `croston(values, h = 5, alpha = %s)` on %d values.", case$alpha, length(case$values)),
    sprintf("pub const %s: CrostonCase = CrostonCase {", case$name),
    sprintf("    values: %s,", rust_array(case$values)),
    sprintf("    alpha: %s,", rust_float(case$alpha)),
    sprintf("    forecast: %s,", rust_float(fc$mean[1])),
    sprintf("    fitted: %s,", rust_array(fc$fitted)),
    "};",
    ""
  )
}
emit(sprintf("/// All Croston reference cases.\npub const ALL: &[&CrostonCase] = &[%s];",
             paste0("&", vapply(cases, function(c) c$name, ""), collapse = ", ")))

writeLines(lines, out)