Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions examples/respicast/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# ci-proto on Europe's respiratory forecasting hub

[RespiCast](https://respicast.ecdc.europa.eu/) is the forecasting hub run by the European Centre
for Disease Prevention and Control (ECDC) with the Institute for Scientific Interchange (ISI)
Foundation and the London School of Hygiene & Tropical Medicine (LSHTM). Every week, teams send
it forecasts of influenza-like illness (ILI) and acute respiratory infection (ARI) across
Europe. ECDC combines these forecasts into an ensemble, the median of the teams' forecasts, and
publishes it weekly on the [RespiCast website](https://respicast.ecdc.europa.eu/forecasts/).

These scripts replay every round since August 2025 with ci-proto and score it against the
ensemble and every submitted model. We use the released model at a pinned revision. The model
has not undergone any fine-tuning and no settings were chosen on this data. In each round, the
histories of all countries go into a single call per indicator, as raw weekly rates per
100,000. Each round uses only the data the hub had published by its deadline, and forecasts are
scored against the latest data.

ci-proto's training data contains no RespiCast data, and none from ECDC's European Respiratory
Virus Surveillance Summary ([ERVISS](https://erviss.org/)), the source of most of the hub's
data. European ILI data up to April 2025 form part of the
[fev-bench](https://github.com/autogluon/fev) test set, on which ci-proto has been publicly
evaluated. The evaluation here starts with the round of 6 August 2025. Each round is one week's
forecasts, and seasons run from August to July, so 2025-26 covers the 50 rounds from 6 August
2025 to 22 July 2026 (the hub skipped two summer weeks).

## Results

Forecasts are scored with the weighted interval score (WIS), the score RespiCast publishes for
every model. The table gives ci-proto's total WIS divided by the RespiCast ensemble's. Values
below 1 mean ci-proto had lower error. The brackets give 90% intervals from resampling the
rounds.

| Season | Rounds | Forecasts | Both indicators | ARI | ILI |
|---|---:|---:|---|---|---|
| 2025-26 | 50 | 7,409 | 0.71 (0.66-0.77) | 0.64 (0.59-0.70) | 0.87 (0.79-0.97) |
Comment thread
lingyiyang marked this conversation as resolved.
Resolved
| 2026-27, to 18 November | 15 | 1,924 | 0.80 (0.77-0.83) | 0.74 (0.70-0.79) | 0.92 (0.86-0.99) |

ci-proto also had lower error than each of the 21 team models in 2025-26. So far in 2026-27,
it has lower error than each of the 15 team models that have forecast more than one round and
more than one country.

## Run

```bash
python examples/respicast/forecast.py # writes ci-proto.csv; a GPU is used if there is one
python examples/respicast/compare.py # writes headline.csv and versus.csv
```

The first run fetches the hub at the pinned commit (about 400 MB) into
`outputs/respicast/hub`; outputs go to `outputs/respicast`. Pass `--hub` to use an existing
checkout and `--output` for another folder.

## Scoring

- WIS ([Bracher et al. 2021](https://doi.org/10.1371/journal.pcbi.1008618)) rewards a median
close to the outcome and ranges that are narrow but still contain it. We recompute the WIS of
all models using the same nine quantile levels as the ones that ci-proto produces,
specifically, 10% to 90%.
- Models are scored on the same forecasts as RespiCast's own evaluation: the countries and
horizons the hub asks for in each round.
- Each comparison is a ratio of total WIS. Intervals resample rounds (10,000 draws) and need at
least three rounds.

## Credits

Forecasts and data come from ECDC's
[European Syndromic Indicators Forecasting Hub](https://github.com/european-modelling-hubs/RespiCast-SyndromicIndicators),
run with the ISI Foundation and LSHTM, and the teams who submit to it. Surveillance data are
from ERVISS (ECDC and the WHO Regional Office for Europe) and WHO FluID, as collected by the
hub. The scripts fetch these from the hub; none are included here.
120 changes: 120 additions & 0 deletions examples/respicast/compare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""Score ci-proto against the RespiCast ensemble and every submitted model.

Forecasts are scored with the weighted interval score (WIS, Bracher et al. 2021) on the nine
quantile levels ci-proto produces, 10% to 90%, against the latest data at the pinned commit.
Models are scored on the same forecasts as RespiCast's own evaluation: the countries and
horizons the hub asks for in each round. Each comparison divides ci-proto's total WIS by the
other model's, counting only the rounds, countries and horizons both forecast (below 1: ci-proto
had lower error), with a 90% interval from resampling rounds.

python examples/respicast/compare.py
"""

from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np
import pandas as pd
from hub import (
BASELINE,
CI,
ENSEMBLE,
LEVELS,
OUTPUT,
QUANTILES,
TASK,
checkout,
rounds,
season,
submissions,
target_week,
truth,
)


def wis(quantiles: np.ndarray, observed: np.ndarray, levels: list[float]) -> np.ndarray:
"""Weighted interval score from quantiles ``[N, levels]`` at symmetric levels with a median."""
middle = len(levels) // 2
score = 0.5 * np.abs(observed - quantiles[:, middle])
for k in range(middle):
alpha = 2 * levels[k]
lower, upper = quantiles[:, k], quantiles[:, -1 - k]
below = np.maximum(lower - observed, 0)
above = np.maximum(observed - upper, 0)
score = score + alpha / 2 * (upper - lower + 2 / alpha * (below + above))
return score / (middle + 0.5)


def paired(scores: pd.DataFrame, reference: str, draws: int = 10_000) -> dict:
"""ci-proto's total WIS divided by ``reference``'s.

Only the rounds, countries and horizons both forecast count, so neither model is scored on
forecasts the other did not make.
"""
ours = scores[scores["model"] == CI]
theirs = scores.loc[scores["model"] == reference, [*TASK, "wis"]]
both = ours.merge(theirs, on=TASK, suffixes=("", "_ref"))
weekly = both.groupby("origin_date")[["wis", "wis_ref"]].sum()
result = {
"ratio": both["wis"].sum() / both["wis_ref"].sum(),
"low": np.nan,
"high": np.nan,
"rounds": len(weekly),
"forecasts": len(both),
"locations": both["location"].nunique(),
}
if len(weekly) >= 3: # too few rounds to resample otherwise
pick = np.random.default_rng(12345).integers(0, len(weekly), (draws, len(weekly)))
ratios = weekly["wis"].to_numpy()[pick].sum(1) / weekly["wis_ref"].to_numpy()[pick].sum(1)
result["low"], result["high"] = np.quantile(ratios, [0.05, 0.95])
return result


def score(hub: Path, output: Path) -> pd.DataFrame:
"""Every forecast RespiCast evaluates, with its outcome and WIS."""
origins = rounds(hub)
theirs = submissions(hub, origins)
ours = pd.read_csv(output / "ci-proto.csv", parse_dates=["origin_date"]).assign(model=CI)
table = pd.concat([theirs, ours], ignore_index=True)
table = table[table["origin_date"].isin(origins)]
keys = pd.MultiIndex.from_arrays([table["target"], table["location"], target_week(table)])
table["observed"] = truth(hub).reindex(keys).to_numpy()
table = table.dropna(subset=["observed", *QUANTILES]).copy()
table["wis"] = wis(table[QUANTILES].to_numpy(), table["observed"].to_numpy(), LEVELS)
table["season"] = table["origin_date"].map(season)
tasks = table.loc[table["model"] == BASELINE, TASK]
return table.merge(tasks, on=TASK)


def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("--hub", type=Path, default=OUTPUT / "hub", help="hub checkout")
parser.add_argument("--output", type=Path, default=OUTPUT, help="folder for forecasts")
args = parser.parse_args()
scores = score(checkout(args.hub), args.output)

headline, versus = [], []
for name, part in scores.groupby("season"):
for target in ("both", "ARI incidence", "ILI incidence"):
subset = part if target == "both" else part[part["target"] == target]
headline.append({"season": name, "target": target, **paired(subset, ENSEMBLE)})
for model in sorted(set(part["model"]) - {CI}):
versus.append({"season": name, "model": model, **paired(part, model)})
headline, versus = pd.DataFrame(headline), pd.DataFrame(versus)
versus = versus.sort_values(["season", "ratio"])
headline.to_csv(args.output / "headline.csv", index=False)
versus.to_csv(args.output / "versus.csv", index=False)

pd.set_option("display.width", 200)
print("\nci-proto's total WIS / the RespiCast ensemble's:")
print(headline.round(3).to_string(index=False))
print("\nci-proto's total WIS / each submitted model's:")
print(versus.round(3).to_string(index=False))


if __name__ == "__main__":
main()
67 changes: 67 additions & 0 deletions examples/respicast/forecast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""Forecast every RespiCast round since August 2025 with ci-proto.

For each round and indicator, the histories of all countries go into a single call to the
model, using the data the hub had published by the round's deadline. The model has not been
fine-tuned and no settings were chosen on this data. The forecasts are saved for compare.py.

python examples/respicast/forecast.py
"""

from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np
import pandas as pd
import torch
from hub import FREQ, HORIZONS, OUTPUT, QUANTILES, TARGETS, TASK, checkout, release, rounds

from continuousintelligence import load_model

MODEL = "ContinuousIntelligence/ci-proto"
REVISION = "ee3031351a151e3f6febf8c62b53e6ea1008bef6" # pinned Hub commit


def forecast(model, history: pd.DataFrame) -> np.ndarray:
"""Quantiles ``[locations, 9, horizons]`` from weeks x locations (NaN where missing)."""
weeks = pd.date_range(history.index[0], periods=len(history) + len(HORIZONS), freq=FREQ)
return model.forecast(
torch.tensor(history.to_numpy(float).T, dtype=torch.float32),
horizon=len(HORIZONS),
timestamps=torch.tensor(weeks.as_unit("ns").asi8, dtype=torch.int64),
freq=FREQ,
series_ids=list(history.columns),
).numpy()


def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("--hub", type=Path, default=OUTPUT / "hub", help="hub checkout")
parser.add_argument("--output", type=Path, default=OUTPUT, help="folder for forecasts")
parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
args = parser.parse_args()
hub = checkout(args.hub)
model = load_model(MODEL, revision=REVISION, device=args.device)
origins = rounds(hub)
rows = []
for count, origin in enumerate(origins, 1):
for target in TARGETS:
history = release(hub, target, origin)
quantiles = forecast(model, history)
for location, values in zip(history.columns, quantiles, strict=True):
for step, horizon in enumerate(HORIZONS):
if np.isfinite(values[:, step]).all():
rows.append((origin, target, location, horizon, *values[:, step]))
print(f"{count}/{len(origins)} rounds", end="\r", flush=True)
args.output.mkdir(parents=True, exist_ok=True)
path = args.output / "ci-proto.csv"
table = pd.DataFrame(rows, columns=[*TASK, *QUANTILES])
table.to_csv(path, index=False, float_format="%.9g")
print(f"\nSaved {len(table):,} forecasts from {len(origins)} rounds to {path}")


if __name__ == "__main__":
main()
124 changes: 124 additions & 0 deletions examples/respicast/hub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Data from ECDC's RespiCast syndromic-indicators hub, pinned to the commit behind our results.

The hub holds each week's surveillance release, every team's submitted forecasts and the latest
data used to score them. ``checkout`` fetches only the files these scripts read (about 400 MB).
"""

from __future__ import annotations

import subprocess
from pathlib import Path

import pandas as pd

REPO = "https://github.com/european-modelling-hubs/RespiCast-SyndromicIndicators.git"
COMMIT = "5acf646ced030353dea6dc5ab28221e5cc9fab2d" # 21 November 2026, after the 18 Nov round
FOLDERS = ("/model-output/", "/target-data/")
OUTPUT = Path(__file__).resolve().parents[2] / "outputs" / "respicast"

TARGETS = {"ILI incidence": "ILI_incidence", "ARI incidence": "ARI_incidence"}
SOURCES = ("ERVISS", "FluID")
HORIZONS = (1, 2, 3, 4) # weeks after the round's latest data week
FREQ = "W-SUN" # ISO weeks, dated by their Sunday
ENSEMBLE = "respicast-hubEnsemble"
BASELINE = "respicast-quantileBaseline"
CI = "ci-proto"
TASK = ["origin_date", "target", "location", "horizon"]
LEVELS = [round(k / 10, 1) for k in range(1, 10)] # ci-proto's quantile levels
QUANTILES = [f"q{level:g}" for level in LEVELS]
SEASONS = {"2025-26": ("2025-08-01", "2026-07-31"), "2026-27": ("2026-08-01", "2027-07-31")}


def checkout(path: Path) -> Path:
"""The hub at ``COMMIT`` in ``path``, fetched on first use."""
git = ["git", "-C", str(path)]
if not (path / ".git").exists():
path.mkdir(parents=True, exist_ok=True)
subprocess.run([*git, "init", "-q"], check=True)
subprocess.run([*git, "sparse-checkout", "set", "--no-cone", *FOLDERS], check=True)
fetch = ["fetch", "-q", "--depth", "1", "--filter=blob:none", REPO, COMMIT]
subprocess.run([*git, *fetch], check=True)
subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True)
head = subprocess.run([*git, "rev-parse", "HEAD"], capture_output=True, text=True, check=True)
if head.stdout.strip() != COMMIT:
raise RuntimeError(f"{path} is at {head.stdout.strip()}, not {COMMIT}")
return path


def season(origin: pd.Timestamp) -> str:
"""The season (August to July) containing a round."""
for name, (first, last) in SEASONS.items():
if pd.Timestamp(first) <= origin <= pd.Timestamp(last):
return name
raise ValueError(f"{origin.date()} is outside {list(SEASONS)}")


def rounds(hub: Path) -> pd.DatetimeIndex:
"""Deadlines (Wednesdays) of the rounds since August 2025 with a hub ensemble."""
files = (hub / "model-output" / ENSEMBLE).glob("*.csv")
dates = pd.DatetimeIndex(sorted(pd.Timestamp(file.name[:10]) for file in files))
return dates[dates >= pd.Timestamp(SEASONS["2025-26"][0])]


def release(hub: Path, target: str, origin: pd.Timestamp) -> pd.DataFrame:
"""The history for the round due on ``origin``: weekly rates, one column per country.

The data are as published by the deadline, before any later revisions. The hub keeps a
snapshot of each weekly data release from two sources: ERVISS for EU/EEA countries and WHO
FluID for Switzerland and the UK nations. This takes the latest snapshot of each dated on or
before the deadline. Rows are weeks, dated by their Sunday, up to the round's latest data week,
which ends ten days before the deadline. Weeks a country did not report are NaN.
"""
last = origin - pd.Timedelta(days=10)
parts = []
for source in SOURCES:
folder = hub / "target-data" / source / "snapshots"
files = sorted(folder.glob(f"*-{TARGETS[target]}.csv"))
published = [file for file in files if pd.Timestamp(file.name[:10]) <= origin]
if published:
data = pd.read_csv(published[-1], parse_dates=["truth_date"])
parts.append(data.pivot_table(index="truth_date", columns="location", values="value"))
frame = pd.concat(parts, axis=1)
frame = frame[frame.index <= last]
frame = frame.reindex(pd.date_range(frame.index.min(), last, freq=FREQ))
return frame[sorted(frame.columns)]


def truth(hub: Path) -> pd.Series:
"""What happened: the rates forecasts are scored against, by indicator, country and week.

The hub's latest data from both sources, including every revision up to the pinned commit,
unlike ``release``, which gives the data as they stood at a round's deadline.
"""
folder = hub / "target-data"
frames = [pd.read_csv(folder / f"latest-{stem}.csv") for stem in TARGETS.values()]
frame = pd.concat(frames)
frame["truth_date"] = pd.to_datetime(frame["truth_date"])
return frame.set_index(["target", "location", "truth_date"])["value"]


def submissions(hub: Path, origins: pd.DatetimeIndex) -> pd.DataFrame:
"""Every submitted quantile forecast for ``origins``.

One row per model, round, indicator, country and horizon.
"""
frames = []
for file in sorted((hub / "model-output").glob("*/*.csv")):
if pd.Timestamp(file.name[:10]) in origins:
frame = pd.read_csv(file, dtype={"output_type_id": str})
frames.append(frame.assign(model=file.parent.name))
frame = pd.concat(frames, ignore_index=True)
frame = frame[(frame["output_type"] == "quantile") & frame["horizon"].isin(HORIZONS)].copy()
frame["level"] = frame["output_type_id"].astype(float).round(3)
frame["origin_date"] = pd.to_datetime(frame["origin_date"])
table = frame.pivot_table(
index=["model", *TASK], columns="level", values="value", aggfunc="first"
)
table.columns = [f"q{level:g}" for level in table.columns]
return table.reset_index()


def target_week(table: pd.DataFrame) -> pd.Series:
"""The week each forecast is for: ``horizon`` weeks after the round's latest data week."""
latest = table["origin_date"] - pd.Timedelta(days=10)
return latest + pd.to_timedelta(7 * table["horizon"], unit="D")