Skip to content
Open
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
81 changes: 81 additions & 0 deletions .github/workflows/respicast.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
name: RespiCast submission

# Submits ci-proto's forecasts to ECDC's RespiCast hub every week (examples/respicast).
# The hub publishes new data on Fridays and takes forecasts until 23:59 CET on Wednesday. The
# Saturday run normally submits; the Monday and Tuesday runs only act if it did not. The hub's
# own checks merge a valid submission, so a pull request that opens is a live forecast.

on:
schedule:
- cron: '0 8 * * 6'
- cron: '0 8 * * 1'
- cron: '0 8 * * 2'
workflow_dispatch:
inputs:
round:
description: Round date (YYYY-MM-DD); leave empty for the round open now
required: false
dry_run:
description: Make and check the forecasts without opening the pull request
type: boolean
default: true

permissions:
contents: read

concurrency:
group: respicast-submission
cancel-in-progress: false

jobs:
submit:
# Only the public repository submits on a schedule.
if: github.repository == 'continuousintelligence/ci' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HUB_REPO: european-modelling-hubs/RespiCast-SyndromicIndicators
# The fork the pull requests come from; set the RESPICAST_FORK variable to change it.
FORK_REPO: ${{ vars.RESPICAST_FORK || 'Benjamin-Walker/RespiCast-SyndromicIndicators' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
version: '0.11.30'
python-version: '3.13'
enable-cache: true
- name: Install locked dependencies
run: uv sync --locked
- name: Fetch the hub's latest data
run: |
git clone --depth 1 --filter=blob:none --sparse \
"https://github.com/$HUB_REPO.git" "$RUNNER_TEMP/hub"
git -C "$RUNNER_TEMP/hub" sparse-checkout set hub-config target-data
- name: Forecast and check the submission
id: forecast
env:
ROUND: ${{ inputs.round }}
run: >-
uv run --locked python examples/respicast/submit.py
--hub "$RUNNER_TEMP/hub" --output "$RUNNER_TEMP/submission" --device cpu
${ROUND:+--round "$ROUND"}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: respicast-${{ steps.forecast.outputs.round }}
path: ${{ runner.temp }}/submission/${{ steps.forecast.outputs.file }}
- name: Open the pull request to the hub
env:
GH_TOKEN: ${{ secrets.RESPICAST_TOKEN || github.token }}
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run && '1' || '' }}
HAS_TOKEN: ${{ secrets.RESPICAST_TOKEN != '' }}
ROUND: ${{ steps.forecast.outputs.round }}
AUTHOR_NAME: Ben Walker
AUTHOR_EMAIL: [email protected]
run: |
if [[ -z $DRY_RUN && $HAS_TOKEN != true ]]; then
echo "::error::Add a RESPICAST_TOKEN secret that can push to $FORK_REPO."
exit 1
fi
bash examples/respicast/open_pr.sh "$ROUND" "$RUNNER_TEMP/submission"
13 changes: 13 additions & 0 deletions examples/respicast/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ 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.

## Weekly submissions

ci-proto also forecasts live, as `CI-ci_proto` on the hub. Each Saturday, after the hub's Friday
data release, the [RespiCast submission](../../.github/workflows/respicast.yml) workflow runs
`submit.py` for the open round on a standard CPU runner. That script forecasts from the hub's
latest data in the same way as `forecast.py`, extends the nine quantiles to the hub's 23 levels
and checks the file against the hub's rules. `open_pr.sh` then opens the pull request to the
hub. Monday and Tuesday runs submit only if Saturday's did not.

```bash
python examples/respicast/submit.py --hub HUB_CHECKOUT # writes the open round's file
```

## Scoring

- WIS ([Bracher et al. 2021](https://doi.org/10.1371/journal.pcbi.1008618)) rewards a median
Expand Down
80 changes: 80 additions & 0 deletions examples/respicast/open_pr.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Open the pull request that submits ci-proto's forecasts for one round to RespiCast.
#
# bash examples/respicast/open_pr.sh ROUND FOLDER
#
# ROUND is the round's date and FOLDER is submit.py's --output folder. The file goes to a new
# branch of FORK, made from its main once that is brought up to the hub's, and the pull request
# goes from there to HUB, whose checks merge a valid submission by themselves. Nothing happens if
# the round is already on the hub's main or has an open pull request. With DRY_RUN=1 it runs those
# checks and says what it would do. GH_TOKEN must be able to write to FORK and open pull requests
# on HUB.
set -euo pipefail

round=$1
folder=$2
[[ $round =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || { echo "Not a date: $round" >&2; exit 1; }

hub=${HUB_REPO:-european-modelling-hubs/RespiCast-SyndromicIndicators}
fork=${FORK_REPO:-Benjamin-Walker/RespiCast-SyndromicIndicators}
name=CI-ci_proto
path=model-output/$name/$round-$name.csv
branch=add-$name-$round
title="Add $name forecasts for $round"
body="Weekly forecasts from $name for the $(date -d "$round" '+%-d %B %Y') round."
[[ -s $folder/$path ]] || { echo "No submission at $folder/$path" >&2; exit 1; }

# Delete the fork's branches from earlier submissions once the hub has merged or closed their
# pull requests, so the fork keeps only main.
for old in $(gh api "repos/$fork/branches?per_page=100" --paginate \
--jq ".[].name | select(startswith(\"add-$name-\"))"); do
state=$(gh pr list -R "$hub" --head "$old" --state all --json state,headRepositoryOwner \
--jq "[.[] | select(.headRepositoryOwner.login == \"${fork%%/*}\")][0].state // \"\"")
if [[ $state == MERGED || $state == CLOSED ]]; then
if [[ -n ${DRY_RUN:-} ]]; then
echo "Dry run: would delete the branch $fork:$old (pull request ${state,,})."
else
gh api -X DELETE "repos/$fork/git/refs/heads/$old" --silent
echo "Deleted the branch $fork:$old (pull request ${state,,})."
fi
fi
done

if gh api "repos/$hub/contents/$path?ref=main" --silent 2>/dev/null; then
echo "The $round round is already on the hub's main branch; nothing to do."
exit 0
fi
open=$(gh pr list -R "$hub" --head "$branch" --state open --json url,headRepositoryOwner \
--jq "[.[] | select(.headRepositoryOwner.login == \"${fork%%/*}\")][0].url // \"\"")
if [[ -n $open ]]; then
echo "The $round round already has an open pull request: $open"
exit 0
fi
if [[ -n ${DRY_RUN:-} ]]; then
echo "Dry run: would put $path on $fork:$branch and open \"$title\" on $hub."
exit 0
fi

# Bring the fork's main up to the hub's, then branch from it. GitHub refuses the update when the
# hub has changed its own workflows and the token lacks the workflow scope; the fork's main is
# then older but still part of the hub's history, so the pull request holds only the new file.
if ! gh api -X POST "repos/$fork/merge-upstream" -f branch=main --silent; then
echo "::warning::Could not update $fork's main from $hub; branching from it as it is."
fi
sha=$(gh api "repos/$fork/git/ref/heads/main" --jq .object.sha)
gh api -X DELETE "repos/$fork/git/refs/heads/$branch" --silent 2>/dev/null || true
gh api "repos/$fork/git/refs" -f ref="refs/heads/$branch" -f sha="$sha" --silent

# The file goes in through the contents API, as one commit on the new branch.
payload=$(mktemp)
trap 'rm -f "$payload"' EXIT
base64 -w0 "$folder/$path" | jq -Rs --arg message "$title" --arg branch "$branch" \
--arg author "${AUTHOR_NAME:?}" --arg email "${AUTHOR_EMAIL:?}" \
'{message: $message, branch: $branch, content: .,
author: {name: $author, email: $email}, committer: {name: $author, email: $email}}' \
> "$payload"
gh api -X PUT "repos/$fork/contents/$path" --input "$payload" --silent

url=$(gh api "repos/$hub/pulls" -f title="$title" -f body="$body" -f base=main \
-f head="${fork%%/*}:$branch" --jq .html_url)
echo "Opened $url"
189 changes: 189 additions & 0 deletions examples/respicast/submit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""Make ci-proto's RespiCast submission for the round that is open now.

RespiCast takes forecasts each week until 23:59 CET on Wednesday, for the round named after that
Wednesday. This reads a checkout of the hub's main branch, forecasts with ci-proto from the hub's
latest data release exactly as forecast.py does, puts the nine quantiles on the hub's 23 levels,
checks the file against the hub's rules and writes it. The weekly workflow
(.github/workflows/respicast.yml) runs it and then opens the pull request to the hub.

python examples/respicast/submit.py --hub HUB [--round YYYY-MM-DD] [--output FOLDER]
"""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
from statistics import NormalDist

import numpy as np
import pandas as pd
from forecast import MODEL, REVISION, forecast
from hub import HORIZONS, LEVELS, OUTPUT, TARGETS, release

from continuousintelligence import load_model

NAME = "CI-ci_proto" # team and model abbreviations, as registered with the hub
HUB_LEVELS = [0.01, 0.025, 0.05, *(round(k / 20, 2) for k in range(2, 19)), 0.95, 0.975, 0.99]
STALE_WEEKS = 8 # countries with no report in this many weeks are left out
COLUMNS = [
"origin_date",
"target",
"target_end_date",
"horizon",
"location",
"output_type",
"output_type_id",
"value",
]


def options(hub: Path, target: str) -> dict[str, set]:
"""The values the hub accepts for ``target``: rounds, countries and target weeks."""
config = json.loads((hub / "hub-config" / "tasks.json").read_text())["rounds"][0]
for task in config["model_tasks"]:
ids = task["task_ids"]
if ids["target"]["required"] == [target]:
return {k: set(ids[k]["required"] or []) | set(ids[k]["optional"] or []) for k in ids}
raise SystemExit(f"The hub does not list {target!r} in hub-config/tasks.json.")


def window(hub: Path) -> tuple[int, int]:
"""Days before the round date that submissions open and close."""
due = json.loads((hub / "hub-config" / "tasks.json").read_text())["rounds"][0]
return due["submissions_due"]["start"], due["submissions_due"]["end"]


def open_round(hub: Path, today: pd.Timestamp) -> pd.Timestamp:
"""The first round on or after ``today``: the one taking submissions now."""
dates = sorted(pd.Timestamp(d) for d in options(hub, next(iter(TARGETS)))["origin_date"])
later = [d for d in dates if d >= today.normalize()]
if not later:
raise SystemExit(f"The hub lists no round on or after {today.date()}.")
return later[0]


def latest_release(hub: Path, target: str) -> pd.Timestamp:
"""Date of the hub's latest ERVISS data release for ``target``."""
files = (hub / "target-data" / "ERVISS" / "snapshots").glob(f"*-{TARGETS[target]}.csv")
return max(pd.Timestamp(file.name[:10]) for file in files)


def extend(q9: np.ndarray) -> np.ndarray:
"""Nine quantiles ``[N, 9]`` at 10% to 90% -> the hub's 23 levels ``[N, 23]``.

Linear in log(1 + value) against the normal score of the level, with the end segments
continued into the tails, so the outer levels widen the way the inner ones do.
"""
normal = NormalDist()
x = np.array([normal.inv_cdf(level) for level in LEVELS])
target = np.array([normal.inv_cdf(level) for level in HUB_LEVELS])
values = np.log1p(np.maximum.accumulate(np.maximum(q9, 0.0), axis=-1))
seg = np.clip(np.searchsorted(x, target, side="right") - 1, 0, len(x) - 2)
left, right = values[:, seg], values[:, seg + 1]
weight = (target - x[seg]) / (x[seg + 1] - x[seg])
return np.maximum(np.expm1(left + weight * (right - left)), 0.0)


def submission(hub: Path, origin: pd.Timestamp, model) -> tuple[pd.DataFrame, pd.DataFrame]:
"""The hub-format table for ``origin``, and each country's latest reported week."""
rows, report = [], []
for target in TARGETS:
allowed = options(hub, target)
history = release(hub, target, origin)
quantiles = forecast(model, history) # [locations, 9, horizons]
for location, q9 in zip(history.columns, quantiles, strict=True):
reported = history[location].dropna()
last = reported.index.max()
report.append((target, location, last, location in allowed["location"]))
if location not in allowed["location"] or not np.isfinite(q9).all():
continue
if pd.isna(last) or last < history.index[-1] - pd.Timedelta(weeks=STALE_WEEKS):
continue
q23 = extend(q9.T) # [horizons, 23]
for step, horizon in enumerate(HORIZONS):
end = origin - pd.Timedelta(days=10) + pd.Timedelta(weeks=horizon)
base = (origin.date().isoformat(), target, end.date().isoformat(), horizon)
rows.append((*base, location, "median", "", q9[4, step]))
for level, value in zip(HUB_LEVELS, q23[step], strict=True):
rows.append((*base, location, "quantile", f"{level:g}", value))
table = pd.DataFrame(rows, columns=COLUMNS)
table["value"] = table["value"].astype(float).round(4)
report = pd.DataFrame(report, columns=["target", "location", "last_reported", "hub_location"])
report["weeks_behind"] = (origin - pd.Timedelta(days=10) - report["last_reported"]).dt.days // 7
return table, report


def check(table: pd.DataFrame, hub: Path, origin: pd.Timestamp) -> None:
"""Stop with a message if the table breaks any of the hub's rules."""
problems = []
if table.empty:
problems.append("no forecasts")
if not (np.isfinite(table["value"]).all() and (table["value"] >= 0).all()):
problems.append("values that are missing, infinite or negative")
if table.duplicated(COLUMNS[:-1]).any():
problems.append("duplicate rows")
for target, part in table.groupby("target"):
allowed = options(hub, target)
for column in ("origin_date", "target_end_date", "location", "horizon"):
values = part[column] if column != "horizon" else part[column].astype(int)
if not set(values) <= allowed[column]:
problems.append(f"{target}: {column} values the hub does not accept")
keys = ["target", "location", "horizon"]
quantiles = table[table["output_type"] == "quantile"]
if not (quantiles.groupby(keys).size() == len(HUB_LEVELS)).all():
problems.append("forecasts without all 23 quantile levels")
if not quantiles.groupby(keys)["value"].apply(lambda v: (np.diff(v) >= 0).all()).all():
problems.append("quantiles that decrease")
if not (table.groupby(["target", "location"])["horizon"].nunique() == len(HORIZONS)).all():
problems.append("countries without all four horizons")
if (table["origin_date"] != origin.date().isoformat()).any():
problems.append("rows for another round")
if problems:
raise SystemExit("The submission is not valid: " + "; ".join(problems) + ".")


def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("--hub", type=Path, required=True, help="checkout of the hub's main")
parser.add_argument("--round", help="round date (a Wednesday); default: the open round")
parser.add_argument("--output", type=Path, default=OUTPUT / "submission")
parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
args = parser.parse_args()

today = pd.Timestamp.now(tz="UTC").tz_localize(None)
origin = pd.Timestamp(args.round) if args.round else open_round(args.hub, today)
start, _ = window(args.hub)
released = {target: latest_release(args.hub, target) for target in TARGETS}
for target, date in released.items():
if date < origin + pd.Timedelta(days=start):
raise SystemExit(
f"The hub's latest {target} data are from {date.date()}, before the "
f"{origin.date()} round opened; the new release has not arrived yet."
)
print(f"Round {origin.date()}, data released {min(released.values()).date()}")

model = load_model(MODEL, revision=REVISION, device=args.device)
table, report = submission(args.hub, origin, model)
check(table, args.hub, origin)

relative = Path("model-output") / NAME / f"{origin.date()}-{NAME}.csv"
path = args.output / relative
path.parent.mkdir(parents=True, exist_ok=True)
table.to_csv(path, index=False)
counts = table.groupby("target")["location"].nunique().to_dict()
print(f"Wrote {path}: {len(table):,} rows, countries per indicator {counts}")
behind = report[(report["weeks_behind"] > 0) | ~report["hub_location"]]
if not behind.empty:
print("Countries behind on reporting or outside the hub's list:")
print(behind.sort_values(["target", "weeks_behind"]).to_string(index=False))
if "GITHUB_OUTPUT" in os.environ:
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"round={origin.date()}\nfile={relative}\n")


if __name__ == "__main__":
main()