timestral-backtest-lab / lab /quantiles.py
Segizu's picture
Timestral Backtest Lab (ZeroGPU)
756aa06 verified
Raw History Blame Contribute Delete
1.79 kB
"""Quantile level helpers matching official Timestral knots (non-crossing head)."""
from __future__ import annotations
import numpy as np
# Official config.json / model card for Timestral-28M
QUANTILE_LEVELS: tuple[float, ...] = (
0.01,
0.05,
0.1,
0.15,
0.2,
0.25,
0.3,
0.35,
0.4,
0.45,
0.5,
0.55,
0.6,
0.65,
0.7,
0.75,
0.8,
0.85,
0.9,
0.95,
0.99,
)
def enforce_monotonic_quantiles(quantiles: np.ndarray) -> np.ndarray:
"""Ensure non-decreasing quantiles along the last axis (explicit safety).
Official Timestral emits sorted quantiles; this is a defensive isotonic
projection if a numerical glitch crosses bands.
"""
q = np.asarray(quantiles, dtype=np.float64)
if q.ndim != 2:
raise ValueError("expected (horizon, n_quantiles)")
# Forward cumulative max then backward cumulative min to restore order.
ascending = np.maximum.accumulate(q, axis=1)
# Re-run from the high end to pull down crossings.
flipped = np.minimum.accumulate(ascending[:, ::-1], axis=1)[:, ::-1]
return flipped
def select_band(
quantiles: np.ndarray,
levels: tuple[float, ...] | list[float],
*,
low: float,
high: float,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return (low, median, high) point forecasts from a (H, Q) quantile matrix."""
q = enforce_monotonic_quantiles(quantiles)
levels_t = tuple(float(x) for x in levels)
index = {lvl: i for i, lvl in enumerate(levels_t)}
for need in (low, 0.5, high):
if need not in index:
raise ValueError(f"quantile level {need} not in model levels {levels_t}")
lo = q[:, index[low]]
med = q[:, index[0.5]]
hi = q[:, index[high]]
return lo, med, hi