Files
tea/verification/issste.py
T
AlbertoPMDM 0e942e04c1 verification/ out of the package; ISSSTELEÓN check; a Dask-level task failure is an error row
- verification/ (hk1k, issste, common) moved out of src/: not in the wheel;
  the image imports it with PYTHONPATH=/opt/tea-modulo.
- python -m verification issste: every biomarker, legacy and modern, on
  processed/eeg-edf-2025|2026; age from the EDF header inside the task; group
  numbers only (file names, paths, dates and rows stay in the job).
- Pipeline.map (Dask): a task that dies (KilledWorker) becomes an error row
  instead of stopping the batch.
- deploy/verify.sh [hk1k|issste]; issste uses 3 workers x 6 GiB per pod.
2026-11-19 01:28:54 -06:00

182 lines
8.0 KiB
Python

"""
ISSSTELEÓN check on the team's cluster (patient data: group numbers only).
python -m verification issste --out processed/usuarios/alberto/tea-verify/
Reads only processed/eeg-edf-2025/ and processed/eeg-edf-2026/ (the EDFs of the
2025 and 2026 lots); writes only the summary under processed/usuarios/.
1. Lists each lot's EDFs in a worker task (a lot with no EDF is reported as not
available, and the check stops: the conversion is a separate step).
2. Age in months from each EDF header, in a worker task: measurement date minus
birthdate (EDF+ patient and recording fields), as eeg.validate.study.edad_meses.
The birthdate and dates never leave the task.
3. Runs the pipeline (legacy and modern, every biomarker) on every EDF, mains
60 Hz, through the remote Dask scheduler; remote = sequential on the first 4.
4. Compares modern with legacy per feature, on all studies and on 16-36 months.
5. Re-runs each failed study step by step: step, error type and cleaned message
and traceback only (no file name: the 2026 names carry the patient's surname).
Nothing per study leaves the runner pod: file names, paths, ages and rows stay
in its memory. The summary holds counts, percentiles and correlations, with
groups under 5 suppressed.
"""
from __future__ import annotations
import json
import math
import os
import sys
from datetime import date, datetime
from pathlib import Path
from verification.common import (ALL_BIOMARKERS, clean, compare, group_stats, run_impls, versions,
write_summary)
LOTS = {"2025": "processed/eeg-edf-2025/", "2026": "processed/eeg-edf-2026/"}
LINE_HZ = 60.0
AGE_GROUPS = (("<16", 0, 15), ("16-36", 16, 36), ("37-48", 37, 48), (">48", 49, 10_000))
def guard(path: str) -> str:
p = str(path)
p = p[len("s3://"):] if p.startswith("s3://") else p
if not any(p.startswith(lot) for lot in LOTS.values()) or ".." in p:
raise PermissionError("the ISSSTELEÓN check reads only processed/eeg-edf-2025/ and eeg-edf-2026/")
return p
def list_lot(prefix: str) -> list[str]:
"""In a task: s3 paths of the EDFs of one lot (they stay in the runner pod)."""
from tea_modulo.pipeline.storage import s3
return sorted("s3://" + guard(r) for r in s3().find(guard(prefix)) if r.lower().endswith(".edf"))
def _edf_date(text: str) -> date | None:
try:
return datetime.strptime(text, "%d-%b-%Y").date()
except ValueError:
return None
def age_from_header(header: bytes) -> float | None:
"""Age in months at the recording, from the first 256 bytes of an EDF(+) header."""
if len(header) < 176:
return None
patient = header[8:88].decode("latin-1").split()
recording = header[88:168].decode("latin-1").split()
birth = _edf_date(patient[2]) if len(patient) >= 3 else None
meas = _edf_date(recording[1]) if len(recording) >= 2 and recording[0] == "Startdate" else None
if meas is None:
try:
d, m, y = (int(x) for x in header[168:176].decode("latin-1").split("."))
meas = date(1900 + y if y >= 85 else 2000 + y, m, d)
except ValueError:
return None
if birth is None or birth > meas:
return None
return round((meas - birth).days / 30.4375, 1)
def header_age(path: str) -> float | None:
"""In a task: the age of one EDF (reads only its first 256 bytes)."""
from tea_modulo.pipeline.storage import s3
with s3().open(guard(path), "rb") as f:
return age_from_header(f.read(256))
def age_group(m) -> str:
if m is None or not math.isfinite(m):
return "no age"
for label, lo, hi in AGE_GROUPS:
if lo <= math.floor(m) <= hi:
return label
return "no age"
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 issste")
ap.add_argument("--out", required=True)
ap.add_argument("--lots", nargs="+", default=list(LOTS), choices=list(LOTS))
ap.add_argument("--cohort-only", action="store_true", help="only 16-36 months")
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--check-n", type=int, default=4)
ap.add_argument("--impl", nargs="+", default=["legacy", "modern"])
ap.add_argument("--biomarkers", nargs="+", default=list(ALL_BIOMARKERS))
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": "issste", "plan_hash": plan["hash"], "line_hz": LINE_HZ,
"commit": os.environ.get("TEA_COMMIT", ""), "lots": {}}
out_name = f"summary_issste_{summary['commit'] or 'local'}.json"
with Client(addr, direct_to_workers=False) as client:
summary["scheduler"] = versions(client)
lots = {lot: client.submit(list_lot, LOTS[lot], pure=False, priority=-10).result()
for lot in args.lots}
for lot, paths in lots.items():
summary["lots"][lot] = {"edf_files": len(paths),
"folders": len({str(Path(p).parent) for p in paths}),
"available": bool(paths)}
if not all(v["available"] for v in summary["lots"].values()):
text = json.dumps(summary, indent=1)
print(text)
client.submit(write_summary, text, args.out, out_name, pure=False).result()
print("a lot has no EDF: convert it first", file=sys.stderr)
return 3
items, lot_of = [], []
for lot, paths in lots.items():
items += paths
lot_of += [lot] * len(paths)
ages = client.gather(client.map(header_age, items, pure=False, priority=-10))
groups = [age_group(a) for a in ages]
for lot in lots:
g = [gr for gr, lo in zip(groups, lot_of) if lo == lot]
summary["lots"][lot]["age_groups"] = {k: g.count(k) for k in [x[0] for x in AGE_GROUPS] + ["no age"]}
keep = [i for i, g in enumerate(groups) if not args.cohort_only or g == "16-36"]
if args.limit:
keep = keep[: args.limit]
run_items = [(items[i], ages[i]) for i in keep]
strata = {f"lot {lot}": [j for j, i in enumerate(keep) if lot_of[i] == lot] for lot in lots}
strata.update({f"age {g}": [j for j, i in enumerate(keep) if groups[i] == g]
for g in [x[0] for x in AGE_GROUPS] + ["no age"]})
summary["n_run"] = len(run_items)
infos, tables = run_impls(client, run_items, plan=plan, impls=args.impl, biomarkers=args.biomarkers,
check_n=args.check_n, line_hz=LINE_HZ, name_files=False, strata=strata)
cohort = strata["age 16-36"]
for impl, info in infos.items():
if impl in tables:
t = tables[impl]
ok = t[(t.valid == 1) & (t.error == "") & t.key.isin(cohort)]
info["features_16_36"] = {c: group_stats(ok[c]) for c in ok.columns
if c in info.get("features", {})}
summary["impl"] = infos
if {"legacy", "modern"} <= set(tables):
leg, mod = tables["legacy"], tables["modern"]
summary["modern_vs_legacy"] = compare(leg, mod)
summary["modern_vs_legacy_16_36"] = compare(leg[leg.key.isin(cohort)], mod[mod.key.isin(cohort)])
text = json.dumps(summary, indent=1, default=str)
assert "eeg-edf-20" not in text and ".edf" not in text.lower(), "a path reached the summary"
print(text)
key = client.submit(write_summary, text, args.out, out_name, 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
__all__ = ["age_from_header", "age_group", "clean", "guard", "main"]