Files
tea/verification/common.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

199 lines
9.6 KiB
Python

"""
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)}