diff --git a/pyproject.toml b/pyproject.toml index 70b5a04..82e6671 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,18 @@ dependencies = [ export = ["edfio>=0.4.18"] s3 = ["s3fs"] +[project.entry-points."tea_modulo.legacy_modules"] +validation = "tea_modulo.legacy.validation:MODULE" +preprocessing = "tea_modulo.legacy.preprocessing:MODULE" +annotation_mask = "tea_modulo.legacy.processes.annotation_mask:MODULE" +sleep_state = "tea_modulo.legacy.processes.sleep_state:MODULE" +posterior_rhythm = "tea_modulo.legacy.biomarkers.posterior_rhythm:MODULE" + +[project.entry-points."tea_modulo.modules"] + +[project.entry-points."tea_modulo.executors"] +legacy = "tea_modulo.legacy.executor:run_serial" + [project.scripts] ktlx2edf = "tea_modulo.export.cli:main" diff --git a/src/tea_modulo/legacy/executor.py b/src/tea_modulo/legacy/executor.py new file mode 100644 index 0000000..8edd7ef --- /dev/null +++ b/src/tea_modulo/legacy/executor.py @@ -0,0 +1,20 @@ +""" +The legacy executor: a plain, single-threaded Python loop. No Dask. + + run_serial(fn, argsets) == [fn(*a) for a in argsets] + +`fn` is expected to turn failures into rows itself (pipeline.run_study does), +so one bad study never stops the batch. +""" + +from __future__ import annotations + + +def run_serial(fn, argsets, on_result=None, **_ignored) -> list: + out = [] + for a in argsets: + r = fn(*a) + out.append(r) + if on_result: + on_result(r) + return out diff --git a/src/tea_modulo/pipeline/__init__.py b/src/tea_modulo/pipeline/__init__.py new file mode 100644 index 0000000..55975b2 --- /dev/null +++ b/src/tea_modulo/pipeline/__init__.py @@ -0,0 +1,12 @@ +""" +Pipeline: wires modules by name and runs studies. + + from tea_modulo.pipeline import Pipeline + pipe = Pipeline.default(impl="legacy") + table = pipe.map(paths, plan=plan, ages_months=ages, biomarkers=("posterior_rhythm",)) +""" + +from tea_modulo.pipeline.core import NotValid, Pipeline +from tea_modulo.pipeline.run_study import order_for, run_study + +__all__ = ["Pipeline", "NotValid", "run_study", "order_for"] diff --git a/src/tea_modulo/pipeline/core.py b/src/tea_modulo/pipeline/core.py new file mode 100644 index 0000000..804ebae --- /dev/null +++ b/src/tea_modulo/pipeline/core.py @@ -0,0 +1,125 @@ +""" +Pipeline: the only place where modules meet. + + pipe = Pipeline.default() # modern modules (Dask-native batches) + pipe = Pipeline.default(impl="legacy") # director's code, plain serial loop + pipe = pipe.replace("spindle_detection", MyDetector()) + study = pipe.study("s.edf", age_months=27.5, plan=plan_dict) + table = pipe.map(paths, ages_months=ages, plan=plan_dict, + biomarkers=("posterior_rhythm",), cluster="auto") + +Modules are looked up by name through entry points and checked against their +protocol (`contracts.check_module`). Objects passed between them are only +`contracts` objects. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +import pandas as pd + +from tea_modulo.contracts import Study, check_module + +from . import registry +from .run_study import order_for, run_study + + +class NotValid(Exception): + """The study failed validation (or a plan gate).""" + + def __init__(self, summary, reasons): + super().__init__("; ".join(reasons) or "not valid") + self.summary = summary + self.reasons = reasons + + +def _plan_dict(plan) -> dict: + if hasattr(plan, "to_dict"): + return plan.to_dict() + if isinstance(plan, Mapping): + return dict(plan) + raise TypeError(f"plan must be a dict or have to_dict(), not {type(plan).__name__}") + + +class Pipeline: + def __init__(self, modules: Mapping[str, Any], impl: str = "modern"): + self.impl = impl + self.modules = {} + for name, m in modules.items(): + self.modules[name] = check_module(m, registry.kind_of(name, m)) + + @classmethod + def default(cls, impl: str = "modern") -> Pipeline: + if impl not in registry.GROUPS: + raise ValueError(f"impl must be one of {', '.join(registry.GROUPS)}") + return cls({n: registry.load(t) for n, t in registry.available(impl).items()}, impl) + + def replace(self, name: str, module) -> Pipeline: + """Another implementation under `name`: an object, or 'legacy' / 'modern'.""" + if isinstance(module, str): + module = registry.resolve(name, module) + return Pipeline({**self.modules, name: module}, self.impl) + + def module(self, name: str): + try: + return self.modules[name] + except KeyError: + raise KeyError(f"no module {name!r} in this pipeline; it has {', '.join(sorted(self.modules))}") from None + + biomarker = module + + # ------------------------------------------------------------------ one study + def study(self, edf_path, *, plan, age_months: float | None = None, + processes: Sequence[str] | None = None, line_hz: float = 60.0) -> Study: + """Validate, plan, preprocess and run the processes. Raises NotValid.""" + plan = _plan_dict(plan) + summary = self.module("validation").summarize(edf_path, line_hz=line_hz) + if not summary.valid: + raise NotValid(summary, list(summary.extra.get("reasons", []))) + prep_mod = self.module("preprocessing") + prep = prep_mod.run(edf_path, prep_mod.plan_for(summary, plan), age_months=age_months) + study = Study(prep) + names = list(processes) if processes is not None else self.process_names() + for name in self._process_order(names): + study = study.with_labels(self.module(name).predict(study)) + return study + + def process_names(self) -> list[str]: + return [n for n, m in self.modules.items() if registry.kind_of(n, m) == "process"] + + def biomarker_names(self) -> list[str]: + return [n for n, m in self.modules.items() if registry.kind_of(n, m) == "biomarker"] + + def _process_order(self, names): + fake = {"__all__": type("X", (), {"requires": tuple(names)})()} + return order_for(["__all__"], {**self.modules, **fake}) + + # ------------------------------------------------------------------ batches + def map(self, edf_paths: Sequence, *, plan, ages_months: Sequence | None = None, + biomarkers: Sequence[str] = (), cluster: str = "auto", scheduler: str | None = None, + priority: int = -10, memory_per_worker="4.25GiB", n_workers: int | None = None, + line_hz: float = 60.0, keys: Sequence | None = None, on_result=None) -> pd.DataFrame: + """ + One row per study. Modern: a Dask graph (cluster='auto'|'remote'|'local'|'sync'). + Legacy: the plain single-threaded loop (`cluster` is ignored). + """ + plan = _plan_dict(plan) + biomarkers = tuple(biomarkers) + for b in biomarkers: + self.module(b) + order = tuple(order_for(biomarkers, self.modules)) + needed = {n: self.modules[n] for n in ("validation", "preprocessing", *order, *biomarkers)} + ages = list(ages_months) if ages_months is not None else [None] * len(edf_paths) + keys = list(keys) if keys is not None else list(range(len(edf_paths))) + argsets = [(k, str(p), a, plan, needed, order, biomarkers, line_hz) + for k, p, a in zip(keys, edf_paths, ages)] + if self.impl == "legacy": + rows = registry.executor("legacy")(run_study, argsets, on_result=on_result) + else: + 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) + return pd.DataFrame(rows) diff --git a/src/tea_modulo/pipeline/dask_runner.py b/src/tea_modulo/pipeline/dask_runner.py new file mode 100644 index 0000000..5bca351 --- /dev/null +++ b/src/tea_modulo/pipeline/dask_runner.py @@ -0,0 +1,106 @@ +""" +The modern pipeline's batch runner: Dask-native. + +A batch is a graph of `dask.delayed(run_study)` tasks, one per study, built +under `dask.annotate(priority=..., retries=1)`. The same graph runs on: + + cluster="remote" (or an address) the team's cluster: Client(addr, direct_to_workers=False) + cluster="local" a LocalCluster on this computer (processes, 1 thread each, + worker count from free RAM / memory_per_worker) + cluster="sync" Dask's synchronous scheduler: one task at a time in + this process (debugging, tests) + cluster="auto" scheduler= / DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS if + set, otherwise local + +Cluster rules (biomarcadores-tea/CLAUDE.md) are built in: positive priorities +are refused, a remote cluster is only ever `client.close()`d (never restart or +shutdown), and a LocalCluster is closed only if this runner started it. +""" + +from __future__ import annotations + +import contextlib +import os +from collections.abc import Callable, Sequence + +BLAS_ENV = {"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREADS": "1"} + + +def scheduler_address(scheduler: str | None = None) -> str | None: + return scheduler or os.environ.get("DASK_SCHEDULER") or os.environ.get("DASK_SCHEDULER_ADDRESS") + + +def _bytes(s) -> int: + from dask.utils import parse_bytes + return parse_bytes(s) if isinstance(s, str) else int(s) + + +def local_workers(memory_per_worker="4.25GiB", n_workers: int | None = None) -> int: + if n_workers: + return int(n_workers) + import psutil + by_mem = int(psutil.virtual_memory().available // _bytes(memory_per_worker)) + return max(1, min(os.cpu_count() or 1, by_mem)) + + +@contextlib.contextmanager +def client_for(cluster: str = "auto", scheduler: str | None = None, + memory_per_worker="4.25GiB", n_workers: int | None = None, check_versions=True): + """Yields a distributed Client, or None for the synchronous scheduler.""" + if cluster == "sync": + yield None + return + from distributed import Client, LocalCluster + + addr = scheduler_address(scheduler) if cluster in ("auto", "remote") else None + if cluster not in ("auto", "remote", "local", "sync") and "://" in str(cluster): + addr = cluster + if cluster == "remote" and not addr: + raise ValueError("cluster='remote' needs scheduler= or DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS") + if addr: + client = Client(addr, direct_to_workers=False) + try: + if check_versions: + client.get_versions(check=True) + yield client + finally: + client.close() # never restart() or shutdown(): shared cluster + return + lc = LocalCluster(n_workers=local_workers(memory_per_worker, n_workers), threads_per_worker=1, + processes=True, memory_limit=memory_per_worker, dashboard_address=None, + env=BLAS_ENV) + client = Client(lc) + try: + yield client + finally: + client.close() + lc.close() # this runner started it, so it closes it + + +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.""" + import dask + + if priority > 0: + raise ValueError("positive priorities are not allowed on the shared cluster (use <= 0)") + with dask.annotate(priority=priority, retries=retries): + tasks = [dask.delayed(fn, pure=False)(*a) for a in argsets] + with client_for(cluster, scheduler, memory_per_worker, n_workers) as client: + if client is None: + out = list(dask.compute(*tasks, scheduler="synchronous")) + if on_result: + for r in out: + on_result(r) + return out + from distributed import as_completed + futures = client.compute(tasks) + index = {f.key: i for i, f in enumerate(futures)} + out = [None] * len(futures) + for f in as_completed(futures): + r = f.result() + out[index[f.key]] = r + if on_result: + on_result(r) + return out diff --git a/src/tea_modulo/pipeline/registry.py b/src/tea_modulo/pipeline/registry.py new file mode 100644 index 0000000..e6a8a5c --- /dev/null +++ b/src/tea_modulo/pipeline/registry.py @@ -0,0 +1,52 @@ +""" +Module lookup by name, through entry points. The pipeline never imports a +module directly, so a replacement registered under the same name (in this +package or another) is picked up with no code change. + +Groups (pyproject.toml): + tea_modulo.modules modern modules name = "pkg.mod:MODULE" + tea_modulo.legacy_modules legacy modules + tea_modulo.executors plain executors (legacy = single-threaded loop) +""" + +from __future__ import annotations + +import importlib +from importlib.metadata import entry_points + +GROUPS = {"modern": "tea_modulo.modules", "legacy": "tea_modulo.legacy_modules"} +KIND_OF = {"validation": "validator", "preprocessing": "preprocessor"} + + +def kind_of(name: str, module) -> str: + if name in KIND_OF: + return KIND_OF[name] + return "biomarker" if hasattr(module, "measure") else "process" + + +def available(impl: str = "modern") -> dict[str, str]: + """{name: 'pkg.mod:attr'} registered for an implementation.""" + return {ep.name: ep.value for ep in entry_points(group=GROUPS[impl])} + + +def load(target: str): + """'pkg.mod:attr' -> the object (no import at module level of the pipeline).""" + mod, _, attr = target.partition(":") + obj = importlib.import_module(mod) + for part in attr.split(".") if attr else (): + obj = getattr(obj, part) + return obj + + +def resolve(name: str, impl: str = "modern"): + targets = available(impl) + if name not in targets: + raise KeyError(f"no {impl} module named {name!r}; registered: {', '.join(sorted(targets)) or 'none'}") + return load(targets[name]) + + +def executor(name: str): + eps = {ep.name: ep.value for ep in entry_points(group="tea_modulo.executors")} + if name not in eps: + raise KeyError(f"no executor {name!r}; registered: {', '.join(eps)}") + return load(eps[name]) diff --git a/src/tea_modulo/pipeline/run_study.py b/src/tea_modulo/pipeline/run_study.py new file mode 100644 index 0000000..468fd68 --- /dev/null +++ b/src/tea_modulo/pipeline/run_study.py @@ -0,0 +1,84 @@ +""" +One study from EDF to measured features: the unit of work of every executor +(Dask task or legacy loop iteration). Pure: everything it needs comes in as +arguments, everything it produces goes out as one small row. + +The row carries no file name, path or date: only the caller's `key`, the +verdict, the features, the plan hash and the module versions. A failure is a +row with `error` set (exception type and message, with paths removed). +""" + +from __future__ import annotations + +import re +import time +from collections.abc import Mapping, Sequence +from typing import Any + +from tea_modulo.contracts import Study + +from . import storage + + +def run_study(key, path, age_months: float | None, plan: Mapping[str, Any], + modules: Mapping[str, Any], order: Sequence[str], biomarkers: Sequence[str], + line_hz: float = 60.0) -> dict: + t0 = time.time() + row: dict[str, Any] = {"key": key, "age_months": age_months, "valid": None, "level": None, + "reasons": "", "plan_hash": plan.get("hash", ""), "error": "", + "versions": ";".join(f"{n}={getattr(modules[n], 'version', '?')}" + for n in ["validation", "preprocessing", *order, + *biomarkers])} + try: + with storage.local_copy(path) as p: + summary = modules["validation"].summarize(p, line_hz=line_hz) + reasons = list(summary.extra.get("reasons", [])) + gates = plan.get("gates", {}) + if gates.get("skip_no_analizable", True) and summary.level == "no_analizable" \ + and not reasons: + reasons.append("triage level no_analizable") + mc = gates.get("min_clean") + if mc is not None and summary.clean_fraction == summary.clean_fraction \ + and summary.clean_fraction < mc: + reasons.append(f"plan gate: {100 * summary.clean_fraction:.0f}% clean < {100 * mc:.0f}%") + valid = int(summary.valid and not reasons) + row.update(valid=valid, level=summary.level, reasons="; ".join(reasons), + clean_fraction=summary.clean_fraction, n_bad_channels=len(summary.bad_channels)) + if valid: + plan_s = modules["preprocessing"].plan_for(summary, plan) + prep = modules["preprocessing"].run(p, plan_s, age_months=age_months) + study = Study(prep) + for name in order: + study = study.with_labels(modules[name].predict(study)) + for name in biomarkers: + for feat, v in modules[name].measure(study).items(): + row[feat] = float(v) + except Exception as e: # noqa: BLE001 - becomes an error row + msg = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "", str(e))[:300] + row["error"] = f"{type(e).__name__}: {msg}" + row["seconds"] = round(time.time() - t0, 1) + return row + + +def order_for(biomarkers: Sequence[str], modules: Mapping[str, Any]) -> list[str]: + """Processes needed by the biomarkers, in dependency order (topological).""" + needed, order, visiting = set(), [], set() + + def visit(name): + if name in needed: + return + if name in visiting: + raise ValueError(f"cycle in module requirements at {name!r}") + if name not in modules: + raise KeyError(f"module {name!r} is required but not in the pipeline") + visiting.add(name) + for r in getattr(modules[name], "requires", ()): + visit(r) + visiting.discard(name) + needed.add(name) + order.append(name) + + for b in biomarkers: + for r in getattr(modules[b], "requires", ()): + visit(r) + return order diff --git a/src/tea_modulo/pipeline/storage.py b/src/tea_modulo/pipeline/storage.py new file mode 100644 index 0000000..f0320bc --- /dev/null +++ b/src/tea_modulo/pipeline/storage.py @@ -0,0 +1,42 @@ +""" +Where an EDF comes from: a local path, or an S3 object fetched to a temporary +file inside the task (on the team's cluster S3 is reachable only from the +workers). The S3 filesystem is created inside the task with the worker's +AWS_ENDPOINT_URL and path addressing; keys come from the environment, never +from code. Nothing is ever written back to S3 from here. +""" + +from __future__ import annotations + +import contextlib +import os +import tempfile +from pathlib import Path + + +def is_s3(path) -> bool: + return str(path).startswith("s3://") + + +def s3(): + import s3fs + endpoint = os.environ.get("AWS_ENDPOINT_URL", "http://seaweedfs-s3.seaweedfs:8333") + return s3fs.S3FileSystem(client_kwargs={"endpoint_url": endpoint}, + config_kwargs={"s3": {"addressing_style": "path"}}) + + +@contextlib.contextmanager +def local_copy(path): + """A local path for `path` for the duration of the block.""" + if not is_s3(path): + yield Path(path) + return + key = str(path)[len("s3://"):] + with tempfile.TemporaryDirectory(prefix="tea_s3_") as tmp: + dest = Path(tmp) / Path(key).name + s3().get_file(key, str(dest)) + yield dest + + +def stem(path) -> str: + return Path(str(path)).stem diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 6190ba4..4b07514 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -21,7 +21,7 @@ LEGACY = {"numpy", "scipy", "pandas", "sklearn"} EXTRA = { "validation": {"fhir"}, "serving": {"mlflow"}, - "pipeline": {"dask", "distributed", "s3fs", "fsspec"}, + "pipeline": {"dask", "distributed", "s3fs", "fsspec", "psutil"}, "verify": {"dask", "distributed", "s3fs", "fsspec"}, "export": set(), } diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000..b3eee46 --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,123 @@ +"""Pipeline: module lookup, dependency order, executors and cluster rules.""" + +from __future__ import annotations + +import os +from pathlib import Path + +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(): + pipe = Pipeline.default(impl="legacy") + assert {"validation", "preprocessing", "annotation_mask", "sleep_state", "posterior_rhythm"} <= set(pipe.modules) + assert pipe.biomarker_names() == ["posterior_rhythm"] + + +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_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 + (tea_modulo.verify). 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]