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