verify: run every biomarker registered in both implementations and compare them per study
This commit is contained in:
@@ -82,6 +82,28 @@ def group_stats(values) -> dict | None:
|
|||||||
"median": round(float(np.median(v)), 3), "p95": round(float(np.percentile(v, 95)), 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:
|
def _versions(client) -> dict:
|
||||||
v = client.get_versions(check=False)
|
v = client.get_versions(check=False)
|
||||||
return {k: v["scheduler"]["packages"].get(k) for k in ("python", "dask", "distributed")}
|
return {k: v["scheduler"]["packages"].get(k) for k in ("python", "dask", "distributed")}
|
||||||
@@ -103,6 +125,8 @@ def main(argv=None) -> int:
|
|||||||
ap.add_argument("--limit", type=int, default=None)
|
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("--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("--impl", nargs="+", default=["legacy", "modern"])
|
||||||
|
ap.add_argument("--biomarkers", nargs="+", default=["posterior_rhythm", "spindles", "gradient",
|
||||||
|
"slow_waves", "aperiodic", "mse"])
|
||||||
args = ap.parse_args(argv)
|
args = ap.parse_args(argv)
|
||||||
|
|
||||||
addr = scheduler_address()
|
addr = scheduler_address()
|
||||||
@@ -122,28 +146,27 @@ def main(argv=None) -> int:
|
|||||||
if args.limit:
|
if args.limit:
|
||||||
items = items[: args.limit]
|
items = items[: args.limit]
|
||||||
summary["n_listed"] = len(items)
|
summary["n_listed"] = len(items)
|
||||||
|
tables = {}
|
||||||
for impl in args.impl:
|
for impl in args.impl:
|
||||||
try:
|
try:
|
||||||
pipe = Pipeline.default(impl=impl)
|
pipe = Pipeline.default(impl=impl)
|
||||||
except Exception as e: # noqa: BLE001
|
except Exception as e: # noqa: BLE001
|
||||||
summary["impl"][impl] = {"skipped": f"{type(e).__name__}: {e}"[:200]}
|
summary["impl"][impl] = {"skipped": f"{type(e).__name__}: {e}"[:200]}
|
||||||
continue
|
continue
|
||||||
if "posterior_rhythm" not in pipe.modules:
|
bios = tuple(b for b in args.biomarkers if b in pipe.modules)
|
||||||
summary["impl"][impl] = {"skipped": "posterior_rhythm not registered"}
|
if not bios:
|
||||||
|
summary["impl"][impl] = {"skipped": "none of the biomarkers is registered"}
|
||||||
continue
|
continue
|
||||||
paths, ages = [p for p, _ in items], [a for _, a in items]
|
paths, ages = [p for p, _ in items], [a for _, a in items]
|
||||||
remote = Pipeline(pipe.modules, impl="modern").map(
|
remote = Pipeline(pipe.modules, impl="modern").map(
|
||||||
paths, plan=plan, ages_months=ages, biomarkers=("posterior_rhythm",),
|
paths, plan=plan, ages_months=ages, biomarkers=bios, cluster="remote", line_hz=50.0)
|
||||||
cluster="remote", line_hz=50.0)
|
tables[impl] = remote
|
||||||
# equality: the first studies again, sequentially, in one task
|
# equality: the first studies again, sequentially, in one task
|
||||||
from tea_modulo.pipeline.run_study import order_for
|
from tea_modulo.pipeline.run_study import order_for
|
||||||
mods = {n: pipe.modules[n] for n in ("validation", "preprocessing",
|
order = tuple(order_for(list(bios), pipe.modules))
|
||||||
*order_for(["posterior_rhythm"], pipe.modules),
|
mods = {n: pipe.modules[n] for n in ("validation", "preprocessing", *order, *bios)}
|
||||||
"posterior_rhythm")}
|
|
||||||
order = tuple(order_for(["posterior_rhythm"], pipe.modules))
|
|
||||||
k = min(args.check_n, len(paths))
|
k = min(args.check_n, len(paths))
|
||||||
argsets = [(i, paths[i], ages[i], plan, mods, order, ("posterior_rhythm",), 50.0)
|
argsets = [(i, paths[i], ages[i], plan, mods, order, bios, 50.0) for i in range(k)]
|
||||||
for i in range(k)]
|
|
||||||
seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False,
|
seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False,
|
||||||
priority=-10).result())
|
priority=-10).result())
|
||||||
cols = [c for c in seq.columns if c not in ("seconds",)]
|
cols = [c for c in seq.columns if c not in ("seconds",)]
|
||||||
@@ -159,11 +182,16 @@ def main(argv=None) -> int:
|
|||||||
"remote_equals_sequential": equal, "checked": k,
|
"remote_equals_sequential": equal, "checked": k,
|
||||||
"seconds_median": float(remote.seconds.median()) if len(remote) else None,
|
"seconds_median": float(remote.seconds.median()) if len(remote) else None,
|
||||||
"posterior_rhythm_hz": group_stats(ok.get("posterior_rhythm_hz", [])),
|
"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": {}}
|
"by_age_group": {}}
|
||||||
for lo, hi in ((12, 24), (24, 36)):
|
for lo, hi in ((12, 24), (24, 36)):
|
||||||
g = ok[(ok.age_months >= lo) & (ok.age_months < hi)]
|
g = ok[(ok.age_months >= lo) & (ok.age_months < hi)]
|
||||||
info["by_age_group"][f"{lo}-{hi}"] = group_stats(g.get("posterior_rhythm_hz", []))
|
info["by_age_group"][f"{lo}-{hi}"] = group_stats(g.get("posterior_rhythm_hz", []))
|
||||||
summary["impl"][impl] = info
|
summary["impl"][impl] = info
|
||||||
|
if {"legacy", "modern"} <= set(tables):
|
||||||
|
summary["modern_vs_legacy"] = compare(tables["legacy"], tables["modern"])
|
||||||
summary["reference"] = _reference()
|
summary["reference"] = _reference()
|
||||||
text = json.dumps(summary, indent=1, default=str)
|
text = json.dumps(summary, indent=1, default=str)
|
||||||
print(text)
|
print(text)
|
||||||
|
|||||||
Reference in New Issue
Block a user