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.
This commit is contained in:
AlbertoPMDM
2026-11-19 01:28:54 -06:00
parent 624774bfd9
commit 0e942e04c1
18 changed files with 665 additions and 304 deletions
+1
View File
@@ -0,0 +1 @@
"""Cluster checks of tea_modulo (testing only; not part of the distributed package)."""
+22
View File
@@ -0,0 +1,22 @@
"""python -m verification {hk1k|issste} --out processed/usuarios/<name>/tea-verify/
Cluster checks of tea_modulo. They live outside the package (not in the wheel):
they are for testing only, and run from the tea-verify image (PYTHONPATH=/opt/tea-modulo)."""
import sys
def main(argv=None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
if not argv or argv[0] not in ("hk1k", "issste"):
print(__doc__, file=sys.stderr)
return 2
if argv[0] == "hk1k":
from verification import hk1k as check
else:
from verification import issste as check
return check.main(argv[1:])
if __name__ == "__main__":
sys.exit(main())
+198
View File
@@ -0,0 +1,198 @@
"""
What both cluster checks share: run the pipeline (legacy and modern) on a list of
S3 EDFs through the remote scheduler, check remote = sequential, compare modern
with legacy, diagnose the failures, and keep everything to group numbers.
Only group numbers leave the tasks and the runner pod: counts, medians,
percentiles, correlations. Groups with fewer than 5 studies are suppressed.
"""
from __future__ import annotations
import math
import re
from pathlib import Path
MIN_GROUP = 5
FEATURE_PREFIXES = ("posterior_", "spindle_", "gradient_", "slow_wave_", "aperiodic_", "mse_",
"coupling_", "spike_", "spikes_", "topography_")
ALL_BIOMARKERS = ("posterior_rhythm", "spindles", "gradient", "slow_waves", "aperiodic", "mse",
"coupling", "spindle_topography", "spikes")
def clean(text) -> str:
"""No paths, file names or study codes in anything that leaves a task (the 2026 file
names carry the patient's surname)."""
t = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(text))
t = re.sub(r"eeg_\d+", "<study>", t)
return re.sub(r"[^\s:'\"(),\[\]]*\.(edf|EDF|erd|eeg|stc|json|npz|parquet)\b", "<file>", t)
def write_summary(text: str, out_prefix: str, name: str) -> str:
"""In a task: write the summary JSON under processed/usuarios/... (never raw/ or eeg-edf)."""
from tea_modulo.pipeline.storage import s3
if not out_prefix.startswith("processed/usuarios/") or ".." in out_prefix:
raise PermissionError("summaries go only under processed/usuarios/<name>/")
key = out_prefix.rstrip("/") + "/" + name
with s3().open(key, "w") as f:
f.write(text)
return key
def sequential(fn, argsets):
"""A plain loop inside one task (the reference for the remote run)."""
return [fn(*a) for a in argsets]
def group_stats(values) -> dict:
import numpy as np
v = np.asarray([x for x in values if x is not None and math.isfinite(x)], float)
if len(v) < MIN_GROUP:
return {"n": int(len(v)), "suppressed": True}
return {"n": int(len(v)), "p5": round(float(np.percentile(v, 5)), 3),
"median": round(float(np.median(v)), 3), "p95": round(float(np.percentile(v, 95)), 3)}
def features_of(table) -> list[str]:
return [c for c in table.columns if c.startswith(FEATURE_PREFIXES)]
def compare(legacy, modern) -> dict:
"""Per feature, over studies valid in both: n, median |modern - legacy|, Pearson r. Also how
often the verdicts agree. Group numbers only."""
import numpy as np
m = legacy.merge(modern, on="key", suffixes=("_l", "_m"))
out = {"n": int(len(m)),
"verdict_agreement": round(float((m.valid_l == m.valid_m).mean()), 4) if len(m) else None,
"features": {}}
feats = [c[:-2] for c in m.columns if c.endswith("_l") and c[:-2] + "_m" in m.columns
and c.startswith(FEATURE_PREFIXES)]
for f in feats:
a, b = m[f + "_l"].astype(float).to_numpy(), m[f + "_m"].astype(float).to_numpy()
ok = np.isfinite(a) & np.isfinite(b)
if ok.sum() < MIN_GROUP:
out["features"][f] = {"n": int(ok.sum()), "suppressed": True}
continue
same = np.allclose(a[ok], b[ok]) or np.ptp(a[ok]) == 0 or np.ptp(b[ok]) == 0
out["features"][f] = {"n": int(ok.sum()),
"median_abs_diff": round(float(np.median(np.abs(a[ok] - b[ok]))), 4),
"r": None if same else round(float(np.corrcoef(a[ok], b[ok])[0, 1]), 4),
"identical": bool(np.allclose(a[ok], b[ok])),
"nan_mismatch": int((np.isfinite(a) != np.isfinite(b)).sum())}
return out
def diagnose(path, age_months, plan, modules, order, biomarkers, line_hz, name_file: bool) -> dict:
"""In a task: re-run one failed study step by step, without catching, and report the step
that raised, the message and the last frames of the traceback (cleaned). The file name is
reported only when `name_file` (public data)."""
import traceback
from tea_modulo.contracts import Study
from tea_modulo.pipeline import storage
out = {"file": Path(str(path)).name if name_file else None, "step": None, "error": "",
"traceback": ""}
step = "read"
try:
with storage.local_copy(path) as p:
step = "validation"
summary = modules["validation"].summarize(p, line_hz=line_hz)
step = "preprocessing"
prep = modules["preprocessing"].run(p, modules["preprocessing"].plan_for(summary, plan),
age_months=age_months)
study = Study(prep)
for name in order:
step = name
study = study.with_labels(modules[name].predict(study))
for name in biomarkers:
step = name
modules[name].measure(study)
out["step"] = "none (did not fail again)"
except Exception as e: # noqa: BLE001
out.update(step=step, error=clean(f"{type(e).__name__}: {e}")[:500],
traceback=clean("".join(traceback.format_exception(e)[-12:]))[-4000:])
return out
def versions(client) -> dict:
v = client.get_versions(check=False)
return {k: v["scheduler"]["packages"].get(k) for k in ("python", "dask", "distributed")}
def run_impls(client, items, *, plan, impls, biomarkers, check_n, line_hz, name_files: bool,
strata: dict | None = None, max_diagnoses: int = 20) -> tuple[dict, dict]:
"""Run every implementation on `items` [(s3 path, age months)] through the remote scheduler.
Returns (summary per impl, tables per impl); the tables stay in the runner pod. `strata`
maps a group label to the item indices it holds (e.g. lot, age group)."""
import pandas as pd
from tea_modulo.pipeline import Pipeline, run_study
from tea_modulo.pipeline.run_study import order_for
paths, ages = [p for p, _ in items], [a for _, a in items]
infos, tables = {}, {}
for impl in impls:
try:
pipe = Pipeline.default(impl=impl)
except Exception as e: # noqa: BLE001
infos[impl] = {"skipped": clean(f"{type(e).__name__}: {e}")[:200]}
continue
bios = tuple(b for b in biomarkers if b in pipe.modules)
if not bios:
infos[impl] = {"skipped": "none of the biomarkers is registered"}
continue
remote = Pipeline(pipe.modules, impl="modern").map(
paths, plan=plan, ages_months=ages, biomarkers=bios, cluster="remote", line_hz=line_hz)
remote["error"] = remote["error"].fillna("").map(clean)
tables[impl] = remote
# equality: the first studies again, sequentially, in one task
order = tuple(order_for(list(bios), pipe.modules))
mods = {n: pipe.modules[n] for n in ("validation", "preprocessing", *order, *bios)}
k = min(check_n, len(paths))
argsets = [(i, paths[i], ages[i], plan, mods, order, bios, line_hz) for i in range(k)]
seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False, priority=-10).result())
seq["error"] = seq["error"].fillna("").map(clean)
cols = [c for c in seq.columns if c != "seconds"]
a = remote[remote.key < k][cols].reset_index(drop=True)
b = seq[cols].reset_index(drop=True)
equal = bool(a.equals(b) or a.fillna(-999).astype(str).equals(b.fillna(-999).astype(str)))
err = remote.error != ""
ok = remote[(remote.valid == 1) & ~err]
info = {"biomarkers": list(bios), "n": int(len(remote)), "valid": int((remote.valid == 1).sum()),
"not_valid": int((remote.valid == 0).sum()), "errors": int(err.sum()),
"error_types": remote.loc[err, "error"].str.split(":").str[0].value_counts().to_dict(),
"not_valid_reasons": _reason_counts(remote.loc[remote.valid == 0, "reasons"]),
"remote_equals_sequential": equal, "checked": k,
"seconds_median": float(remote.seconds.median()) if len(remote) else None,
"seconds_p95": float(remote.seconds.quantile(0.95)) if len(remote) else None,
"features": {c: group_stats(ok[c]) for c in features_of(ok)}}
if strata:
info["by_group"] = {}
for label, idx in strata.items():
g = remote[remote.key.isin(idx)]
info["by_group"][label] = {"n": int(len(g)), "valid": int((g.valid == 1).sum()),
"errors": int((g.error != "").sum())}
failed = remote.loc[err, "key"].tolist()[:max_diagnoses]
info["diagnosis"] = []
for i in failed:
try:
d = client.submit(diagnose, paths[i], ages[i], plan, mods, order, bios, line_hz,
name_files, pure=False, priority=-10, retries=0).result()
except Exception as e: # noqa: BLE001 - e.g. KilledWorker
d = {"file": Path(paths[i]).name if name_files else None, "step": "task",
"error": clean(f"{type(e).__name__}: {e}")[:300], "traceback": ""}
d["first_error"] = remote.loc[remote.key == i, "error"].iloc[0][:300]
info["diagnosis"].append(d)
infos[impl] = info
return infos, tables
def _reason_counts(reasons) -> dict:
"""How often each not-valid reason appears (numbers stripped so they group)."""
from collections import Counter
c = Counter()
for r in reasons.fillna(""):
for part in str(r).split("; "):
if part:
c[re.sub(r"[\d.]+", "#", clean(part))[:80]] += 1
return {k: v for k, v in c.most_common(15)}
+121
View File
@@ -0,0 +1,121 @@
"""
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))
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()
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")}
+181
View File
@@ -0,0 +1,181 @@
"""
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"]