Files
tea/tests/test_pipeline.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

156 lines
6.4 KiB
Python

"""Pipeline: module lookup, dependency order, executors and cluster rules."""
from __future__ import annotations
import os
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from synth_edf import SCALP, make_edf
from tea_modulo.pipeline import NotValid, Pipeline, order_for
from tea_modulo.pipeline import dask_runner
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
BIOS = ("posterior_rhythm",)
@pytest.fixture(scope="module")
def edfs(tmp_path_factory):
d = tmp_path_factory.mktemp("pipe")
good = [make_edf(d / f"s{i}.edf", minutes=3, seed=i, rhythm_hz=6.5 + 0.5 * i) for i in range(2)]
bad = make_edf(d / "bad.edf", minutes=3, bad={"flat": SCALP[:9]}) # 10 usable < 12
broken = d / "broken.edf"
broken.write_bytes(b"not an edf at all")
return good, bad, broken
def _cmp(a: pd.DataFrame, b: pd.DataFrame):
cols = [c for c in a.columns if c != "seconds"]
pd.testing.assert_frame_equal(a[cols].reset_index(drop=True), b[cols].reset_index(drop=True))
def test_order_is_topological():
class M:
def __init__(self, *req):
self.requires = req
mods = {"a": M(), "b": M("a"), "c": M("b", "a"), "bio": M("c")}
assert order_for(["bio"], mods) == ["a", "b", "c"]
mods["a"] = M("c")
with pytest.raises(ValueError, match="cycle"):
order_for(["bio"], mods)
def test_legacy_pipeline_is_registered():
for impl in ("legacy", "modern"):
pipe = Pipeline.default(impl=impl)
assert set(pipe.process_names()) == {"annotation_mask", "window_selection", "sleep_state",
"slow_wave_staging", "spindle_detection"}, impl
assert set(pipe.biomarker_names()) == {"posterior_rhythm", "spindles", "gradient", "slow_waves",
"aperiodic", "mse", "coupling", "spindle_topography",
"spikes"}, impl
def test_legacy_loop_rows_and_errors(edfs):
good, bad, broken = edfs
pipe = Pipeline.default(impl="legacy")
t = pipe.map([*good, bad, broken], plan=DIRECTOR_CLUSTER, ages_months=[24, 30, 26, 28],
biomarkers=BIOS)
assert list(t.key) == [0, 1, 2, 3]
assert t.valid.tolist()[:3] == [1, 1, 0]
assert t.posterior_rhythm_hz.iloc[0] == pytest.approx(6.5, abs=0.3)
assert t.posterior_rhythm_hz.iloc[1] == pytest.approx(7.0, abs=0.3)
assert "electrodos de cuero" in t.reasons.iloc[2]
assert t.error.iloc[3] and "/" not in t.error.iloc[3] # no path in errors
for c in ("path", "file", "name"):
assert c not in t.columns
def test_dask_sync_and_local_equal_legacy_loop(edfs):
good, bad, _ = edfs
paths, ages = [*good, bad], [24, 30, 26]
legacy = Pipeline.default(impl="legacy")
ref = legacy.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS)
modern = Pipeline(legacy.modules, impl="modern") # same modules, Dask runner
_cmp(modern.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS, cluster="sync"), ref)
_cmp(modern.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS,
cluster="local", n_workers=2, memory_per_worker="2GiB"), ref)
def test_no_posterior_channels_is_not_an_error(tmp_path):
"""HK1K K7535V: no O1 O2 P3 P4 left. Every module must give NaN / no events, not raise."""
from synth_edf import AUX, EARS
keep = [c for c in SCALP if c not in ("O1", "O2", "P3", "P4")] + list(EARS) + list(AUX)
p = make_edf(tmp_path / "noposterior.edf", minutes=6, channels=keep)
bios = tuple(Pipeline.default(impl="legacy").biomarker_names())
for impl in ("legacy", "modern"):
t = Pipeline.default(impl=impl).map([p], plan=DIRECTOR_CLUSTER, ages_months=[24], biomarkers=bios,
**({"cluster": "sync"} if impl == "modern" else {}))
assert t.error.iloc[0] == "", (impl, t.error.iloc[0])
assert t.valid.iloc[0] == 1, (impl, t.reasons.iloc[0])
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)
def test_remote_client_is_closed_never_shut_down(monkeypatch):
calls = []
class FakeClient:
def __init__(self, addr, direct_to_workers=None):
calls.append(("init", addr, direct_to_workers))
def get_versions(self, check=False):
calls.append(("versions", check))
def close(self):
calls.append(("close",))
def shutdown(self):
calls.append(("shutdown",))
def restart(self):
calls.append(("restart",))
import distributed
monkeypatch.setattr(distributed, "Client", FakeClient)
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
monkeypatch.delenv("DASK_SCHEDULER", raising=False)
with dask_runner.client_for("auto"):
pass
assert calls == [("init", "tcp://scheduler:8786", False), ("versions", True), ("close",)]
def test_study_raises_not_valid(edfs):
_, bad, _ = edfs
with pytest.raises(NotValid, match="electrodos de cuero"):
Pipeline.default(impl="legacy").study(bad, plan=DIRECTOR_CLUSTER, age_months=26)
@pytest.mark.cluster
@pytest.mark.skipif(not dask_runner.scheduler_address(), reason="no DASK_SCHEDULER")
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
(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]