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:
@@ -61,11 +61,19 @@ with `tea_modulo.contracts.testing`.
|
||||
## Tests and cluster verification
|
||||
|
||||
- `uv run pytest` (synthetic EDFs only; no patient data).
|
||||
- `deploy/verify.sh` builds `tea-verify:<commit>` from this checkout, runs the
|
||||
test suite and the HK1K check (`python -m tea_modulo.verify hk1k`) in a
|
||||
`DaskJob` of its own; `deploy/verify.sh --logs`, `--delete`.
|
||||
- Cluster checks live in `verification/`, outside the package (not in the
|
||||
wheel). `deploy/verify.sh` builds `tea-verify:<commit>` from this checkout and
|
||||
runs one in a `DaskJob` of its own:
|
||||
- `deploy/verify.sh` (`hk1k`): the test suite plus `python -m verification hk1k`
|
||||
(HK1K, public, `raw/eeg-helsinki/`);
|
||||
- `deploy/verify.sh issste`: `python -m verification issste` on
|
||||
`processed/eeg-edf-2025/` and `eeg-edf-2026/`, with every biomarker in both
|
||||
implementations.
|
||||
- `deploy/verify.sh --logs`, `--delete`.
|
||||
- `python tools/vendor_legacy.py --check` confirms the legacy copies are
|
||||
unchanged.
|
||||
|
||||
Patient data (ISSSTELEÓN) is never read by these tests; the HK1K check reads
|
||||
only `raw/eeg-helsinki/` and writes group summaries only.
|
||||
The unit tests never read patient data. Both cluster checks write group
|
||||
summaries only, to `processed/usuarios/`. The ISSSTELEÓN check keeps file
|
||||
names, paths, birthdates and per-study rows inside the job (the 2026 file names
|
||||
carry the patient's surname), and suppresses groups under 5.
|
||||
|
||||
@@ -14,3 +14,6 @@ ENV TEA_COMMIT=$TEA_COMMIT
|
||||
LABEL tea_modulo.commit=$TEA_COMMIT
|
||||
RUN pip install --no-cache-dir --no-deps -e /opt/tea-modulo
|
||||
WORKDIR /opt/tea-modulo
|
||||
# verification/ (cluster checks) is not in the package: import it from the checkout,
|
||||
# on the runner and on the workers
|
||||
ENV PYTHONPATH=/opt/tea-modulo
|
||||
|
||||
+12
-10
@@ -1,9 +1,9 @@
|
||||
# tea-verify: test suite + HK1K check, in its own Dask cluster: 9 pods x 4
|
||||
# worker processes (1 thread, 4.25 GiB each), the size of the former "test"
|
||||
# cluster less one pod (runner + scheduler use part of a node). If other
|
||||
# clusters share the nodes, lower replicas / requests.
|
||||
# Applied by deploy/verify.sh (it substitutes COMMIT). HK1K (public) only;
|
||||
# the eeg-data PVC (patient data) is NOT mounted.
|
||||
# tea-verify: a cluster check of tea_modulo in its own Dask cluster, 9 pods.
|
||||
# hk1k: test suite + HK1K check; 4 workers per pod x 4.25 GiB
|
||||
# issste: ISSSTELEÓN check on processed/eeg-edf-2025|2026 (group summaries
|
||||
# only); 3 workers per pod x 6 GiB (long recordings)
|
||||
# Applied by deploy/verify.sh, which substitutes COMMIT, CHECK, NWORKERS and
|
||||
# MEMLIMIT. The eeg-data PVC is NOT mounted; S3 is read in the tasks only.
|
||||
apiVersion: kubernetes.dask.org/v1
|
||||
kind: DaskJob
|
||||
metadata:
|
||||
@@ -22,9 +22,11 @@ spec:
|
||||
set -e
|
||||
export DASK_SCHEDULER="$DASK_SCHEDULER_ADDRESS"
|
||||
export MLFLOW_DISABLE_AGENT_HINT=1
|
||||
python -m pytest -q -p no:cacheprovider -m "not cluster"
|
||||
python -m pytest -q -p no:cacheprovider -m cluster
|
||||
python -m tea_modulo.verify hk1k --out processed/usuarios/alberto/tea-verify/
|
||||
if [ "CHECK" = hk1k ]; then
|
||||
python -m pytest -q -p no:cacheprovider -m "not cluster"
|
||||
python -m pytest -q -p no:cacheprovider -m cluster
|
||||
fi
|
||||
python -m verification CHECK --out processed/usuarios/alberto/tea-verify/
|
||||
env:
|
||||
- {name: OMP_NUM_THREADS, value: "1"}
|
||||
- {name: OPENBLAS_NUM_THREADS, value: "1"}
|
||||
@@ -40,7 +42,7 @@ spec:
|
||||
containers:
|
||||
- name: worker
|
||||
image: 192.168.20.18:5000/tea-verify:COMMIT
|
||||
args: [dask-worker, --name, $(DASK_WORKER_NAME), --nworkers, "4", --nthreads, "1", --memory-limit, 4.25GiB]
|
||||
args: [dask-worker, --name, $(DASK_WORKER_NAME), --nworkers, "NWORKERS", --nthreads, "1", --memory-limit, MEMLIMIT]
|
||||
resources:
|
||||
requests: {memory: 19Gi, cpu: "4"}
|
||||
limits: {memory: 19Gi}
|
||||
|
||||
+8
-3
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build, push and run the tea-verify DaskJob for the current commit.
|
||||
# deploy/verify.sh build + push + apply
|
||||
# deploy/verify.sh [hk1k] build + push + apply: tests + HK1K check
|
||||
# deploy/verify.sh issste build + push + apply: ISSSTELEÓN check (group numbers only)
|
||||
# deploy/verify.sh --logs follow the job pod's log
|
||||
# deploy/verify.sh --delete remove the DaskJob
|
||||
set -euo pipefail
|
||||
@@ -9,6 +10,9 @@ REG=192.168.20.18:5000
|
||||
case "${1:-}" in
|
||||
--logs) exec kubectl logs -f tea-verify-runner ;;
|
||||
--delete) exec kubectl delete daskjob tea-verify --ignore-not-found ;;
|
||||
""|hk1k) CHECK=hk1k; NW=4; MEM=4.25GiB ;;
|
||||
issste) CHECK=issste; NW=3; MEM=6GiB ;;
|
||||
*) echo "usage: deploy/verify.sh [hk1k|issste|--logs|--delete]" >&2; exit 2 ;;
|
||||
esac
|
||||
if [ -n "$(git status --porcelain --ignore-submodules=none)" ]; then
|
||||
echo "uncommitted changes: commit first, so the image tag is a real commit" >&2; exit 1
|
||||
@@ -17,5 +21,6 @@ C=$(git rev-parse --short HEAD)
|
||||
docker build -f deploy/Dockerfile.verify --build-arg TEA_COMMIT="$C" -t "$REG/tea-verify:$C" .
|
||||
docker push "$REG/tea-verify:$C"
|
||||
kubectl delete daskjob tea-verify --ignore-not-found
|
||||
sed "s/tea-verify:COMMIT/tea-verify:$C/g" deploy/dask-verify.yaml | kubectl apply -f -
|
||||
echo "applied tea-verify:$C — follow with: deploy/verify.sh --logs"
|
||||
sed -e "s/tea-verify:COMMIT/tea-verify:$C/g" -e "s/CHECK/$CHECK/g" -e "s/NWORKERS/$NW/g" \
|
||||
-e "s/MEMLIMIT/$MEM/g" deploy/dask-verify.yaml | kubectl apply -f -
|
||||
echo "applied tea-verify:$C ($CHECK) — follow with: deploy/verify.sh --logs"
|
||||
|
||||
+1
-1
@@ -81,5 +81,5 @@ dev = [
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["tests"]
|
||||
pythonpath = ["tests", "."] # "." for verification/ (cluster checks, not in the wheel)
|
||||
markers = ["cluster: needs a Dask scheduler (DASK_SCHEDULER or DASK_SCHEDULER_ADDRESS)"]
|
||||
|
||||
@@ -121,5 +121,16 @@ class Pipeline:
|
||||
from . import dask_runner
|
||||
rows = dask_runner.run(run_study, argsets, cluster=cluster, scheduler=scheduler,
|
||||
priority=priority, memory_per_worker=memory_per_worker,
|
||||
n_workers=n_workers, on_result=on_result)
|
||||
n_workers=n_workers, on_result=on_result, on_error=_error_row)
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _error_row(args, exc) -> dict:
|
||||
"""A study whose task failed at the Dask level (e.g. KilledWorker): an error row like
|
||||
run_study's, with no path in the message."""
|
||||
import re
|
||||
key, _path, age, plan = args[:4]
|
||||
msg = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
||||
return {"key": key, "age_months": age, "valid": None, "level": None, "reasons": "",
|
||||
"plan_hash": plan.get("hash", ""), "error": f"{type(exc).__name__}: {msg}",
|
||||
"versions": "", "seconds": float("nan")}
|
||||
|
||||
@@ -79,8 +79,13 @@ def client_for(cluster: str = "auto", scheduler: str | None = None,
|
||||
|
||||
def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=None,
|
||||
priority: int = -10, retries: int = 1, memory_per_worker="4.25GiB",
|
||||
n_workers: int | None = None, on_result: Callable | None = None) -> list:
|
||||
"""Run fn(*args) for every args in argsets; results in the input order."""
|
||||
n_workers: int | None = None, on_result: Callable | None = None,
|
||||
on_error: Callable | None = None) -> list:
|
||||
"""Run fn(*args) for every args in argsets; results in the input order.
|
||||
|
||||
`on_error(args, exc)`, when given, turns a task that failed at the Dask level (a worker
|
||||
killed for memory, say, after its retries) into a result, so one study does not stop
|
||||
the batch; without it the exception propagates."""
|
||||
import dask
|
||||
|
||||
if priority > 0:
|
||||
@@ -99,7 +104,12 @@ def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=Non
|
||||
index = {f.key: i for i, f in enumerate(futures)}
|
||||
out = [None] * len(futures)
|
||||
for f in as_completed(futures):
|
||||
r = f.result()
|
||||
try:
|
||||
r = f.result()
|
||||
except Exception as e: # noqa: BLE001
|
||||
if on_error is None:
|
||||
raise
|
||||
r = on_error(argsets[index[f.key]], e)
|
||||
out[index[f.key]] = r
|
||||
if on_result:
|
||||
on_result(r)
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Verification commands run on the team's cluster (HK1K only)."""
|
||||
@@ -1,17 +0,0 @@
|
||||
"""python -m tea_modulo.verify hk1k --out processed/usuarios/<name>/tea-verify/"""
|
||||
|
||||
import sys
|
||||
|
||||
from tea_modulo.verify import hk1k
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if not argv or argv[0] != "hk1k":
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
return hk1k.main(argv[1:])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,250 +0,0 @@
|
||||
"""
|
||||
HK1K verification on the team's cluster (public data only).
|
||||
|
||||
python -m tea_modulo.verify 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 when registered) on every study with
|
||||
age in --ages (default 16-36 months) through the remote Dask scheduler,
|
||||
mains line 50 Hz (Helsinki).
|
||||
3. Checks that the remote run equals a sequential run of the same first
|
||||
studies inside one task (same code path, one worker, plain loop).
|
||||
4. Compares the posterior rhythm by HK1K age group with the reference table
|
||||
(normas/referencia_hk1k.csv, ritmo_posterior / vigilia), when present.
|
||||
5. Prints a JSON summary and writes it to S3 under --out (worker task).
|
||||
|
||||
Only group numbers leave the tasks: counts, medians, percentiles; groups with
|
||||
fewer than 5 children are suppressed. Input paths other than raw/eeg-helsinki/
|
||||
are refused.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HK1K = "raw/eeg-helsinki/"
|
||||
MIN_GROUP = 5
|
||||
REF = Path(__file__).resolve().parents[3] / "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"verification 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 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/"):
|
||||
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 diagnose(path, age_months, plan, modules, order, biomarkers, line_hz) -> dict:
|
||||
"""In a task: re-run one failed HK1K study step by step, without catching, and report
|
||||
the step that raised, the message and the traceback (paths removed). HK1K only."""
|
||||
import re
|
||||
import traceback
|
||||
|
||||
from tea_modulo.contracts import Study
|
||||
from tea_modulo.pipeline import storage
|
||||
path = "s3://" + guard(path)
|
||||
out = {"file": Path(path).name, "step": None, "error": "", "traceback": ""}
|
||||
clean = lambda s: re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", s) # noqa: E731
|
||||
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 group_stats(values) -> dict | None:
|
||||
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 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 = {"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(("posterior_", "spindle_", "gradient_", "slow_wave_", "aperiodic_", "mse_"))]
|
||||
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
|
||||
out["features"][f] = {"n": int(ok.sum()),
|
||||
"median_abs_diff": round(float(np.median(np.abs(a[ok] - b[ok]))), 4),
|
||||
"r": round(float(np.corrcoef(a[ok], b[ok])[0, 1]), 4),
|
||||
"nan_mismatch": int((np.isfinite(a) != np.isfinite(b)).sum())}
|
||||
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 main(argv=None) -> int:
|
||||
import argparse
|
||||
|
||||
import pandas as pd
|
||||
from distributed import Client
|
||||
|
||||
from tea_modulo.pipeline import Pipeline, run_study
|
||||
from tea_modulo.pipeline.dask_runner import scheduler_address
|
||||
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m tea_modulo.verify 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=["posterior_rhythm", "spindles", "gradient",
|
||||
"slow_waves", "aperiodic", "mse"])
|
||||
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": 50.0}
|
||||
summary = {"plan_hash": plan["hash"], "line_hz": 50.0, "ages": list(args.ages), "impl": {},
|
||||
"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 = [(p, a) for p, a in items if args.ages[0] <= a <= args.ages[1]]
|
||||
items.sort()
|
||||
if args.limit:
|
||||
items = items[: args.limit]
|
||||
summary["n_listed"] = len(items)
|
||||
tables = {}
|
||||
for impl in args.impl:
|
||||
try:
|
||||
pipe = Pipeline.default(impl=impl)
|
||||
except Exception as e: # noqa: BLE001
|
||||
summary["impl"][impl] = {"skipped": f"{type(e).__name__}: {e}"[:200]}
|
||||
continue
|
||||
bios = tuple(b for b in args.biomarkers if b in pipe.modules)
|
||||
if not bios:
|
||||
summary["impl"][impl] = {"skipped": "none of the biomarkers is registered"}
|
||||
continue
|
||||
paths, ages = [p for p, _ in items], [a for _, a in items]
|
||||
remote = Pipeline(pipe.modules, impl="modern").map(
|
||||
paths, plan=plan, ages_months=ages, biomarkers=bios, cluster="remote", line_hz=50.0)
|
||||
tables[impl] = remote
|
||||
# equality: the first studies again, sequentially, in one task
|
||||
from tea_modulo.pipeline.run_study import order_for
|
||||
order = tuple(order_for(list(bios), pipe.modules))
|
||||
mods = {n: pipe.modules[n] for n in ("validation", "preprocessing", *order, *bios)}
|
||||
k = min(args.check_n, len(paths))
|
||||
argsets = [(i, paths[i], ages[i], plan, mods, order, bios, 50.0) for i in range(k)]
|
||||
seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False,
|
||||
priority=-10).result())
|
||||
cols = [c for c in seq.columns if c not in ("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)))
|
||||
ok = remote[(remote.valid == 1) & (remote.error == "")]
|
||||
info = {"n": int(len(remote)), "valid": int((remote.valid == 1).sum()),
|
||||
"not_valid": int((remote.valid == 0).sum()),
|
||||
"errors": int((remote.error != "").sum()),
|
||||
"error_types": remote.loc[remote.error != "", "error"].str.split(":").str[0]
|
||||
.value_counts().to_dict(),
|
||||
"remote_equals_sequential": equal, "checked": k,
|
||||
"seconds_median": float(remote.seconds.median()) if len(remote) else None,
|
||||
"posterior_rhythm_hz": group_stats(ok.get("posterior_rhythm_hz", [])),
|
||||
"features": {c: group_stats(ok[c]) for c in ok.columns
|
||||
if c.startswith(("posterior_", "spindle_", "gradient_", "slow_wave_",
|
||||
"aperiodic_", "mse_"))},
|
||||
"by_age_group": {}}
|
||||
failed = remote.loc[remote.error != "", "key"].tolist()[:10]
|
||||
info["diagnosis"] = [client.submit(diagnose, paths[i], ages[i], plan, mods, order, bios, 50.0,
|
||||
pure=False, priority=-10).result() for i in failed]
|
||||
for lo, hi in ((12, 24), (24, 36)):
|
||||
g = ok[(ok.age_months >= lo) & (ok.age_months < hi)]
|
||||
info["by_age_group"][f"{lo}-{hi}"] = group_stats(g.get("posterior_rhythm_hz", []))
|
||||
summary["impl"][impl] = info
|
||||
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 summary["impl"].items() if isinstance(v, dict)
|
||||
and 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")}
|
||||
@@ -22,7 +22,6 @@ EXTRA = {
|
||||
"validation": {"fhir"},
|
||||
"serving": {"mlflow"},
|
||||
"pipeline": {"dask", "distributed", "s3fs", "fsspec", "psutil"},
|
||||
"verify": {"dask", "distributed", "s3fs", "fsspec"},
|
||||
"export": set(),
|
||||
}
|
||||
# lazy imports inside the director's figure / HDF5 helpers (never reached by legacy)
|
||||
@@ -90,8 +89,6 @@ def test_imports_respect_boundaries(path):
|
||||
if top == "tea_modulo":
|
||||
if unit and unit[0] == "export":
|
||||
ok = mod == own or mod.startswith(own + ".")
|
||||
elif unit == ("verify",):
|
||||
ok = True # an application: it wires everything, like tests do
|
||||
elif not unit:
|
||||
ok = mod in ("tea_modulo", "tea_modulo.contracts") or mod.startswith("tea_modulo.contracts.")
|
||||
else:
|
||||
|
||||
+14
-1
@@ -93,6 +93,19 @@ def test_no_posterior_channels_is_not_an_error(tmp_path):
|
||||
assert not np.isfinite(t.posterior_rhythm_hz.iloc[0]), impl
|
||||
|
||||
|
||||
def _inverse(x):
|
||||
return 1 / x
|
||||
|
||||
|
||||
def test_task_failure_becomes_a_row_not_a_stopped_batch():
|
||||
"""A task that fails at the Dask level (KilledWorker on the cluster) must not stop the batch."""
|
||||
out = dask_runner.run(_inverse, [(1,), (0,), (4,)], cluster="local", n_workers=1,
|
||||
memory_per_worker="1GiB", on_error=lambda a, e: f"{type(e).__name__} {a[0]}")
|
||||
assert out == [1.0, "ZeroDivisionError 0", 0.25]
|
||||
with pytest.raises(ZeroDivisionError):
|
||||
dask_runner.run(_inverse, [(0,)], cluster="local", n_workers=1, memory_per_worker="1GiB")
|
||||
|
||||
|
||||
def test_positive_priority_refused():
|
||||
with pytest.raises(ValueError, match="positive priorities"):
|
||||
dask_runner.run(lambda: 1, [()], cluster="sync", priority=1)
|
||||
@@ -137,6 +150,6 @@ def test_study_raises_not_valid(edfs):
|
||||
def test_remote_equals_sync(edfs):
|
||||
"""On the cluster job: the synthetic files are local to the job pod, so they are
|
||||
read by the driver-side sync run only; the remote run uses the HK1K check instead
|
||||
(tea_modulo.verify). Here we only check the remote scheduler answers a trivial graph."""
|
||||
(verification/, python -m verification hk1k). Here we only check the remote scheduler answers a trivial graph."""
|
||||
out = dask_runner.run(lambda x: x * 2, [(1,), (2,)], cluster="remote")
|
||||
assert out == [2, 4]
|
||||
|
||||
+66
-9
@@ -1,27 +1,84 @@
|
||||
"""The HK1K verification command refuses everything but the public HK1K prefix."""
|
||||
"""The cluster checks (verification/, outside the package): input guards, privacy, ages."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from tea_modulo.verify import hk1k
|
||||
from verification import common, hk1k, issste
|
||||
|
||||
|
||||
@pytest.mark.parametrize("p", ["raw/eeg-data/eeg_001/x.edf", "processed/eeg-edf/eeg_001/eeg_001.edf",
|
||||
@pytest.mark.parametrize("p", ["raw/eeg-data/eeg_001/x.edf", "processed/eeg-edf-2025/a/x.edf",
|
||||
"raw/2021-204/a.edf", "raw/eeg-helsinki/../eeg-data/x.edf"])
|
||||
def test_guard_refuses_other_prefixes(p):
|
||||
def test_hk1k_guard_refuses_other_prefixes(p):
|
||||
with pytest.raises(PermissionError):
|
||||
hk1k.guard(p)
|
||||
|
||||
|
||||
def test_guard_accepts_hk1k():
|
||||
def test_hk1k_guard_accepts_hk1k():
|
||||
assert hk1k.guard("s3://raw/eeg-helsinki/sub-1/x.edf") == "raw/eeg-helsinki/sub-1/x.edf"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("p", ["raw/eeg-data/eeg_001/x.edf", "raw/eeg-data-2026/a/x.erd",
|
||||
"raw/2021-204/a.edf", "processed/eeg-edf/eeg_001.edf",
|
||||
"processed/eeg-edf-2025/../cohort-edf-2025/x.edf", "raw/eeg-helsinki/x.edf"])
|
||||
def test_issste_guard_refuses_other_prefixes(p):
|
||||
with pytest.raises(PermissionError):
|
||||
issste.guard(p)
|
||||
|
||||
|
||||
def test_issste_guard_accepts_the_two_lots():
|
||||
for lot in ("2025", "2026"):
|
||||
p = f"processed/eeg-edf-{lot}/a/b.edf"
|
||||
assert issste.guard("s3://" + p) == p
|
||||
|
||||
|
||||
def test_group_stats_suppresses_small_groups():
|
||||
assert hk1k.group_stats([1.0, 2.0, 3.0]) == {"n": 3, "suppressed": True}
|
||||
s = hk1k.group_stats([6.0, 6.5, 7.0, 7.5, 8.0])
|
||||
assert common.group_stats([1.0, 2.0, 3.0]) == {"n": 3, "suppressed": True}
|
||||
s = common.group_stats([6.0, 6.5, 7.0, 7.5, 8.0])
|
||||
assert s["n"] == 5 and s["median"] == 7.0
|
||||
|
||||
|
||||
def test_summary_writes_only_to_user_area():
|
||||
@pytest.mark.parametrize("out", ["processed/eeg-edf-2025/", "raw/x/", "processed/usuarios/../eeg-edf/"])
|
||||
def test_summary_writes_only_to_user_area(out):
|
||||
with pytest.raises(PermissionError):
|
||||
hk1k.write_summary("{}", "processed/eeg-edf/", "x.json")
|
||||
common.write_summary("{}", out, "x.json")
|
||||
|
||||
|
||||
def test_clean_removes_paths_file_names_and_study_codes():
|
||||
msg = ("ValueError: bad header in /tmp/tea_s3_x/PEREZ~ GARCIA_1a2b.edf (eeg_017) "
|
||||
"and 'LOPEZ_3c.edf', [MARTINEZ.EDF]")
|
||||
out = common.clean(msg)
|
||||
for s in ("PEREZ", "GARCIA", "LOPEZ", "MARTINEZ", "eeg_017", "/tmp", ".edf", ".EDF"):
|
||||
assert s not in out, (s, out)
|
||||
assert out.startswith("ValueError: bad header")
|
||||
|
||||
|
||||
def test_age_from_a_real_edf_header(tmp_path):
|
||||
from edfio import Edf, EdfSignal, Patient, Recording
|
||||
p = tmp_path / "a.edf"
|
||||
Edf([EdfSignal(np.zeros(256), 256.0, label="Fz")],
|
||||
patient=Patient(birthdate=date(2023, 1, 15)),
|
||||
recording=Recording(startdate=date(2025, 4, 1))).write(p)
|
||||
head = p.read_bytes()[:256]
|
||||
assert issste.age_from_header(head) == round((date(2025, 4, 1) - date(2023, 1, 15)).days / 30.4375, 1)
|
||||
|
||||
|
||||
def test_age_missing_or_impossible_is_none(tmp_path):
|
||||
from edfio import Edf, EdfSignal, Patient, Recording
|
||||
p = tmp_path / "b.edf"
|
||||
Edf([EdfSignal(np.zeros(256), 256.0, label="Fz")], patient=Patient(),
|
||||
recording=Recording(startdate=date(2025, 4, 1))).write(p)
|
||||
assert issste.age_from_header(p.read_bytes()[:256]) is None
|
||||
assert issste.age_from_header(b"short") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("m, g", [(15.9, "<16"), (16.0, "16-36"), (36.9, "16-36"), (37.0, "37-48"),
|
||||
(49.0, ">48"), (None, "no age"), (float("nan"), "no age")])
|
||||
def test_age_groups(m, g):
|
||||
assert issste.age_group(m) == g
|
||||
|
||||
|
||||
def test_verification_is_not_in_the_package():
|
||||
import importlib.util
|
||||
assert importlib.util.find_spec("tea_modulo.verify") is None
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Cluster checks of tea_modulo (testing only; not part of the distributed package)."""
|
||||
@@ -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())
|
||||
@@ -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)}
|
||||
@@ -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")}
|
||||
@@ -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"]
|
||||
Reference in New Issue
Block a user