Files
tea/verification/hk1k.py
T
AlbertoPMDM 0ee5263419 verification mlflow: register plans and every biomarker, reload each in a fresh process
python -m verification mlflow [--uri] [--table]: both plans and the 9 biomarkers in
both implementations, registered as tea_modulo-test.*; falls back to a local store
(mlflow_local/, kept) when the server does not answer. The HK1K check registers
HK1K-trained baselines when TEA_MLFLOW_URI answers from the job.
2026-11-19 02:10:15 -06:00

133 lines
6.1 KiB
Python

"""
HK1K check on the team's cluster (public data).
python -m verification hk1k --out processed/usuarios/alberto/tea-verify/ [--limit 40]
1. Lists the HK1K EDFs and ages (anon_codex_age_sex.csv) in a worker task.
2. Runs the pipeline (legacy and modern) on every study with age in --ages
(default 16-36 months) through the remote Dask scheduler, mains 50 Hz.
3. Checks that the remote run equals a sequential run of the first studies.
4. Compares modern with legacy per feature, and the posterior rhythm by age group
with the HK1K reference table (normas/referencia_hk1k.csv), when present.
5. Re-runs each failed study step by step (file name, step, message, traceback:
HK1K is public).
6. Prints a JSON summary and writes it to S3 under --out (worker task).
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
from verification.common import (ALL_BIOMARKERS, compare, group_stats, run_impls, versions,
write_summary)
HK1K = "raw/eeg-helsinki/"
LINE_HZ = 50.0
REF = Path(__file__).resolve().parents[1] / "biomarcadores-tea" / "normas" / "referencia_hk1k.csv"
def guard(path: str) -> str:
p = str(path)
p = p[len("s3://"):] if p.startswith("s3://") else p
if not p.startswith(HK1K) or ".." in p:
raise PermissionError(f"the HK1K check reads only {HK1K}; refused another prefix")
return p
def list_hk1k(base: str = HK1K) -> list[tuple[str, float]]:
"""In a task: (s3 path, age in months) of each HK1K EDF with an age."""
import pandas as pd
from tea_modulo.pipeline.storage import s3
fs = s3()
paths = fs.find(guard(base))
tables = [r for r in paths if r.endswith("anon_codex_age_sex.csv")]
if not tables:
raise FileNotFoundError("anon_codex_age_sex.csv not found under the HK1K prefix")
with fs.open(tables[0], "rb") as f:
codex = pd.read_csv(f)
codex.columns = ["archivo", "edad_anos", "sexo"]
edfs = {Path(r).name: r for r in paths if r.endswith(".edf")}
return [("s3://" + guard(edfs[r.archivo]), round(float(r.edad_anos) * 12, 1))
for r in codex.itertuples() if r.archivo in edfs]
def main(argv=None) -> int:
import argparse
from distributed import Client
from tea_modulo.pipeline.dask_runner import scheduler_address
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
ap = argparse.ArgumentParser(prog="python -m verification hk1k")
ap.add_argument("--out", required=True)
ap.add_argument("--ages", nargs=2, type=float, default=(16.0, 36.0))
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--check-n", type=int, default=4, help="studies re-run sequentially for the equality check")
ap.add_argument("--impl", nargs="+", default=["legacy", "modern"])
ap.add_argument("--biomarkers", nargs="+", default=list(ALL_BIOMARKERS))
ap.add_argument("--mlflow-uri", default=os.environ.get("TEA_MLFLOW_URI", ""),
help="register plans and HK1K-trained biomarkers there (skipped if it does not answer)")
args = ap.parse_args(argv)
addr = scheduler_address()
if not addr:
print("no DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS: run this inside the tea-verify DaskJob",
file=sys.stderr)
return 2
plan = {**DIRECTOR_CLUSTER.to_dict(), "line_hz": LINE_HZ}
summary = {"check": "hk1k", "plan_hash": plan["hash"], "line_hz": LINE_HZ, "ages": list(args.ages),
"commit": os.environ.get("TEA_COMMIT", "")}
with Client(addr, direct_to_workers=False) as client:
summary["scheduler"] = versions(client)
items = client.submit(list_hk1k, pure=False, priority=-10).result()
items = sorted((p, a) for p, a in items if args.ages[0] <= a <= args.ages[1])
if args.limit:
items = items[: args.limit]
summary["n_listed"] = len(items)
infos, tables = run_impls(client, items, plan=plan, impls=args.impl, biomarkers=args.biomarkers,
check_n=args.check_n, line_hz=LINE_HZ, name_files=True)
for impl, info in infos.items():
if impl in tables:
t = tables[impl]
ok = t[(t.valid == 1) & (t.error == "")]
info["by_age_group"] = {f"{lo}-{hi}": group_stats(
ok[(ok.age_months >= lo) & (ok.age_months < hi)].get("posterior_rhythm_hz", []))
for lo, hi in ((12, 24), (24, 36))}
summary["impl"] = infos
if {"legacy", "modern"} <= set(tables):
summary["modern_vs_legacy"] = compare(tables["legacy"], tables["modern"])
summary["reference"] = _reference()
if args.mlflow_uri and tables:
from verification.mlflow_check import register_all
ok = {i: t[(t.valid == 1) & (t.error == "")] for i, t in tables.items()}
try:
summary["mlflow"] = register_all(ok, uri=args.mlflow_uri, impls=tuple(ok),
data_label=f"hk1k-{summary['commit'] or 'local'}",
fallback_local=False)
except Exception as e: # noqa: BLE001
summary["mlflow"] = {"error": f"{type(e).__name__}: {e}"[:300]}
text = json.dumps(summary, indent=1, default=str)
print(text)
key = client.submit(write_summary, text, args.out,
f"summary_{summary['commit'] or 'local'}.json", pure=False).result()
print(f"summary written to s3://{key}", file=sys.stderr)
bad = [i for i, v in infos.items() if v.get("remote_equals_sequential") is False]
return 1 if bad else 0
def _reference() -> dict:
"""HK1K reference rhythm (E15) for the age groups the run covers, if the table is here."""
if not REF.exists():
return {"available": False}
import pandas as pd
r = pd.read_csv(REF, encoding="utf-8-sig")
r = r[(r.biomarcador == "ritmo_posterior") & (r.estado == "vigilia")]
return {"available": True, "ritmo_posterior_vigilia": r[["grupo_edad_anos", "n", "p5", "mediana", "p95"]]
.to_dict("records")}