"""Tests for formula-safe CSV export and quantile band handling.""" from __future__ import annotations from pathlib import Path import numpy as np import pandas as pd from lab.export_csv import escape_csv_cell, write_forecast_csv, write_metrics_csv from lab.quantiles import QUANTILE_LEVELS, enforce_monotonic_quantiles, select_band def test_formula_escaping() -> None: assert escape_csv_cell("=CMD()") == "'=CMD()" assert escape_csv_cell("+1+1") == "'+1+1" assert escape_csv_cell("-1") == "'-1" assert escape_csv_cell("@SUM(A1)") == "'@SUM(A1)" assert escape_csv_cell("normal") == "normal" assert escape_csv_cell(3.5) == "3.5" def test_write_forecast_csv_escapes_and_nonempty(tmp_path: Path) -> None: path = tmp_path / "out.csv" times = ["2024-01-01", "=1+1", "2024-01-03"] median = np.array([1.0, 2.0, 3.0]) lo = np.array([0.5, 1.5, 2.5]) hi = np.array([1.5, 2.5, 3.5]) write_forecast_csv(path, times=times, median=median, q_low=lo, q_high=hi, low_level=0.1, high_level=0.9) text = path.read_text(encoding="utf-8") assert text.strip() assert "'=1+1" in text df = pd.read_csv(path) assert len(df) == 3 assert "median" in df.columns def test_write_metrics_csv(tmp_path: Path) -> None: path = tmp_path / "metrics.csv" rows = { "timestral": {"mae": 1.2, "mase": "N/A"}, "last_value": {"mae": 2.0, "mase": 1.5}, } write_metrics_csv(path, rows) # keep_default_na=False so literal N/A is not parsed as NaN df = pd.read_csv(path, keep_default_na=False) assert set(df["model"]) == {"timestral", "last_value"} assert "N/A" in df["mase"].astype(str).tolist() def test_quantile_levels_match_official() -> None: expected = ( 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, ) assert QUANTILE_LEVELS == expected def test_enforce_monotonic_quantiles() -> None: # Simulate a crossing: q10 > q90 at one step (should not happen in official # non-crossing head, but we handle explicitly). q = np.zeros((4, len(QUANTILE_LEVELS)), dtype=float) q[:, :] = np.linspace(0, 1, len(QUANTILE_LEVELS)) q[2, 2] = 0.9 # corrupt low quantile q[2, 18] = 0.1 # corrupt high quantile fixed = enforce_monotonic_quantiles(q) assert np.all(np.diff(fixed, axis=1) >= -1e-9) def test_select_band_shape_and_order() -> None: h = 5 q = np.tile(np.linspace(0, 20, len(QUANTILE_LEVELS)), (h, 1)).astype(float) lo, med, hi = select_band(q, QUANTILE_LEVELS, low=0.1, high=0.9) assert lo.shape == med.shape == hi.shape == (h,) assert np.all(lo <= med) assert np.all(med <= hi)