contracts: shared data classes, protocols and contract test suites
Step 1 of the tea_modulo plan: Recording (MNE Raw from EDF), ValidationSummary, Preprocessed, Labels, Study, the Validator/Preprocessor/Process/Biomarker protocols with check_module(), reusable contract suites in contracts.testing, and an AST test that enforces the module boundary rule.
This commit is contained in:
@@ -1,2 +1,9 @@
|
||||
def hello() -> str:
|
||||
return "Hello from tea-modulo!"
|
||||
"""
|
||||
tea_modulo: modular EEG library (EDF in, validation, preprocessing,
|
||||
processes and biomarkers out).
|
||||
|
||||
Every biomarker and every process is its own module. Modules talk only
|
||||
through `tea_modulo.contracts`; see the architecture plan.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
The shared API of `tea_modulo`: the only code every module may import.
|
||||
|
||||
from tea_modulo.contracts import Recording, Preprocessed, Study, Labels
|
||||
from tea_modulo.contracts import check_module, CONTRACT_VERSION
|
||||
"""
|
||||
|
||||
from tea_modulo.contracts.data import (
|
||||
CONTRACT_VERSION,
|
||||
DEVIATION_COLUMNS,
|
||||
WINDOW_COLUMNS,
|
||||
Labels,
|
||||
Preprocessed,
|
||||
Recording,
|
||||
Study,
|
||||
ValidationSummary,
|
||||
sha256_of,
|
||||
)
|
||||
from tea_modulo.contracts.protocols import (
|
||||
KINDS,
|
||||
Biomarker,
|
||||
ContractError,
|
||||
Module,
|
||||
Preprocessor,
|
||||
Process,
|
||||
Validator,
|
||||
check_module,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS",
|
||||
"Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of",
|
||||
"Module", "Validator", "Preprocessor", "Process", "Biomarker",
|
||||
"KINDS", "ContractError", "check_module",
|
||||
]
|
||||
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
Data that crosses module boundaries.
|
||||
|
||||
Every module in `tea_modulo` talks to the others only through these frozen
|
||||
dataclasses and the protocols in `contracts.protocols`. A module may be
|
||||
replaced completely by any code that consumes and produces these objects.
|
||||
|
||||
Signals travel as MNE objects (`mne.io.BaseRaw`), so every module shares
|
||||
MNE's handling of units (volts inside MNE), channel types, gaps
|
||||
(`BAD_ACQ_SKIP` annotations) and timing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
CONTRACT_VERSION = "1.0"
|
||||
|
||||
# Columns of the table that Biomarker.predict returns.
|
||||
DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline")
|
||||
|
||||
# Columns that Preprocessed.windows must have.
|
||||
WINDOW_COLUMNS = ("start_s", "end_s", "clean", "gap")
|
||||
|
||||
|
||||
def sha256_of(path: str | Path, chunk: int = 1 << 20) -> str:
|
||||
"""SHA-256 of a file, read in chunks."""
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while block := f.read(chunk):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Recording:
|
||||
"""
|
||||
An EDF file in memory.
|
||||
|
||||
- `raw`: the EDF as read by `mne.io.read_raw_edf` (preloaded). Gaps are
|
||||
`BAD_ACQ_SKIP` annotations, as `ktlx2edf` writes them.
|
||||
- `age_months`: age at the recording, if known.
|
||||
- `source_sha256`: hash of the EDF file, for traceability.
|
||||
- `source_name`: file stem only (never a full path, which may hold names).
|
||||
"""
|
||||
|
||||
raw: Any # mne.io.BaseRaw (Any: contracts import mne lazily)
|
||||
age_months: float | None
|
||||
source_sha256: str
|
||||
source_name: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_edf(cls, path: str | Path, *, age_months: float | None = None) -> Recording:
|
||||
"""Read an EDF with MNE. The only EDF reader shared through contracts."""
|
||||
import mne
|
||||
|
||||
path = Path(path)
|
||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="error")
|
||||
return cls(raw=raw, age_months=age_months, source_sha256=sha256_of(path),
|
||||
source_name=path.stem)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ValidationSummary:
|
||||
"""
|
||||
What preprocessing needs from validation.
|
||||
|
||||
- `valid`: 1 = valid, 0 = not valid.
|
||||
- `level`: `completo`, `sin_referencia_auricular` or `no_analizable`.
|
||||
- `bad_channels`: channel -> reason, for every channel to exclude.
|
||||
- `ears_usable`: both ear channels usable (linked-ears reference possible).
|
||||
- `line_db`: mains line level of the study, in dB.
|
||||
- `clean_fraction`: fraction of clean 4 s windows.
|
||||
"""
|
||||
|
||||
valid: int
|
||||
level: str
|
||||
bad_channels: Mapping[str, str]
|
||||
ears_usable: bool
|
||||
line_db: float
|
||||
clean_fraction: float
|
||||
extra: Mapping[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Preprocessed:
|
||||
"""
|
||||
What preprocessing hands to every process and biomarker.
|
||||
|
||||
- `variants`: variant name (e.g. "hp05_prom") -> preprocessed `Raw`.
|
||||
EEG channels are re-referenced; EOG / ECG channels are filtered only.
|
||||
- `windows`: one row per analysis window, columns `WINDOW_COLUMNS`
|
||||
(start_s, end_s in seconds from the start of the recording; clean and
|
||||
gap as booleans). Window length and step come from the plan.
|
||||
- `plan`: the plan that produced this, as a schema-tagged dict.
|
||||
- `plan_hash`: the plan's content hash.
|
||||
"""
|
||||
|
||||
variants: Mapping[str, Any] # str -> mne.io.BaseRaw
|
||||
windows: pd.DataFrame
|
||||
age_months: float | None
|
||||
plan: Mapping[str, Any]
|
||||
plan_hash: str
|
||||
source_sha256: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
faltan = [c for c in WINDOW_COLUMNS if c not in self.windows.columns]
|
||||
if faltan:
|
||||
raise ValueError(f"Preprocessed.windows lacks columns: {', '.join(faltan)}")
|
||||
if not self.variants:
|
||||
raise ValueError("Preprocessed has no variant")
|
||||
|
||||
def variant(self, name: str):
|
||||
"""The `Raw` of one variant, with a clear error if it is missing."""
|
||||
try:
|
||||
return self.variants[name]
|
||||
except KeyError:
|
||||
raise KeyError(f"variant {name!r} not in this study; it has "
|
||||
f"{', '.join(self.variants)}") from None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Labels:
|
||||
"""
|
||||
What a process returns.
|
||||
|
||||
- `per_window`: one value per row of `Preprocessed.windows` (same index).
|
||||
- `events`: one row per event; at least `onset_s` and `duration_s`.
|
||||
"""
|
||||
|
||||
process: str
|
||||
per_window: pd.Series | None = None
|
||||
events: pd.DataFrame | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
if self.per_window is None and self.events is None:
|
||||
raise ValueError(f"Labels of {self.process!r} have neither per_window nor events")
|
||||
if self.events is not None:
|
||||
faltan = [c for c in ("onset_s", "duration_s") if c not in self.events.columns]
|
||||
if faltan:
|
||||
raise ValueError(f"events of {self.process!r} lack columns: {', '.join(faltan)}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Study:
|
||||
"""What a biomarker reads: the preprocessed study plus process outputs."""
|
||||
|
||||
prep: Preprocessed
|
||||
labels: Mapping[str, Labels] = field(default_factory=dict)
|
||||
|
||||
def label(self, process: str) -> Labels:
|
||||
try:
|
||||
return self.labels[process]
|
||||
except KeyError:
|
||||
raise KeyError(f"this study has no labels from process {process!r}; "
|
||||
f"it has {', '.join(self.labels) or 'none'}") from None
|
||||
|
||||
def with_labels(self, labels: Labels) -> Study:
|
||||
return Study(self.prep, {**self.labels, labels.process: labels})
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
What each kind of module must offer.
|
||||
|
||||
A module is replaceable: any object that satisfies its protocol (and declares
|
||||
the same `CONTRACT_VERSION`) can take its place in the pipeline. `check_module`
|
||||
verifies this when a module is loaded.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from tea_modulo.contracts.data import (
|
||||
CONTRACT_VERSION,
|
||||
Labels,
|
||||
Preprocessed,
|
||||
Study,
|
||||
ValidationSummary,
|
||||
)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Module(Protocol):
|
||||
name: str
|
||||
version: str
|
||||
contract_version: str
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Validator(Module, Protocol):
|
||||
def validate(self, edf_path, *, line_hz: float = 60.0,
|
||||
subject: str | None = None) -> tuple[dict, int]: ...
|
||||
|
||||
def summarize(self, edf_path, *, line_hz: float = 60.0) -> ValidationSummary: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Preprocessor(Module, Protocol):
|
||||
def plan_for(self, summary: ValidationSummary, base: Mapping[str, Any]) -> dict: ...
|
||||
|
||||
def run(self, edf_path, plan: Mapping[str, Any], *,
|
||||
age_months: float | None = None) -> Preprocessed: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Process(Module, Protocol):
|
||||
requires: tuple[str, ...]
|
||||
|
||||
def train(self, studies: Sequence[Study]) -> Process: ...
|
||||
|
||||
def predict(self, study: Study) -> Labels: ...
|
||||
|
||||
def save(self, path) -> None: ...
|
||||
|
||||
@classmethod
|
||||
def load(cls, path) -> Process: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Biomarker(Module, Protocol):
|
||||
requires: tuple[str, ...]
|
||||
features: tuple[str, ...]
|
||||
|
||||
def measure(self, study: Study) -> Mapping[str, float]: ...
|
||||
|
||||
def train(self, data: Sequence[Study] | pd.DataFrame,
|
||||
ages_months=None) -> Biomarker: ...
|
||||
|
||||
def predict(self, data: Study | pd.DataFrame, age_months=None) -> pd.DataFrame: ...
|
||||
|
||||
def save(self, path) -> None: ...
|
||||
|
||||
@classmethod
|
||||
def load(cls, path) -> Biomarker: ...
|
||||
|
||||
|
||||
KINDS: dict[str, type] = {
|
||||
"validator": Validator,
|
||||
"preprocessor": Preprocessor,
|
||||
"process": Process,
|
||||
"biomarker": Biomarker,
|
||||
}
|
||||
|
||||
|
||||
class ContractError(TypeError):
|
||||
"""A module does not satisfy its protocol or contract version."""
|
||||
|
||||
|
||||
def check_module(module: object, kind: str) -> object:
|
||||
"""
|
||||
Check that `module` satisfies the protocol of `kind` and was built for
|
||||
this `CONTRACT_VERSION`. Returns the module, so it can be used inline.
|
||||
"""
|
||||
try:
|
||||
proto = KINDS[kind]
|
||||
except KeyError:
|
||||
raise ValueError(f"unknown module kind {kind!r}; one of {', '.join(KINDS)}") from None
|
||||
nombre = getattr(module, "name", type(module).__name__)
|
||||
if not isinstance(module, proto):
|
||||
faltan = [a for a in _members(proto) if not hasattr(module, a)]
|
||||
raise ContractError(f"module {nombre!r} is not a {kind}: missing {', '.join(faltan)}")
|
||||
cv = getattr(module, "contract_version", None)
|
||||
if str(cv).split(".")[0] != CONTRACT_VERSION.split(".")[0]:
|
||||
raise ContractError(f"module {nombre!r} was built for contract {cv}; "
|
||||
f"this library has {CONTRACT_VERSION}")
|
||||
if kind in ("process", "biomarker"):
|
||||
req = getattr(module, "requires")
|
||||
if not isinstance(req, tuple) or not all(isinstance(r, str) for r in req):
|
||||
raise ContractError(f"module {nombre!r}: requires must be a tuple of names")
|
||||
return module
|
||||
|
||||
|
||||
def _members(proto: type) -> list[str]:
|
||||
names = []
|
||||
for klass in proto.__mro__:
|
||||
if klass in (Protocol, object):
|
||||
continue
|
||||
names += [n for n in getattr(klass, "__annotations__", {})]
|
||||
names += [n for n, v in vars(klass).items()
|
||||
if not n.startswith("_") and (callable(v) or isinstance(v, classmethod))]
|
||||
return list(dict.fromkeys(names))
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
Contract test suites: run them against any implementation of a module,
|
||||
including a replacement written outside this package.
|
||||
|
||||
from tea_modulo.contracts.testing import check_process, check_biomarker
|
||||
check_process(MyDetector(), study)
|
||||
check_biomarker(MyBiomarker(), studies, ages_months)
|
||||
|
||||
Each function raises AssertionError with a clear message on the first
|
||||
violation and returns the module's output for further checks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import tempfile
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from tea_modulo.contracts.data import (
|
||||
DEVIATION_COLUMNS,
|
||||
Labels,
|
||||
Preprocessed,
|
||||
Study,
|
||||
ValidationSummary,
|
||||
)
|
||||
from tea_modulo.contracts.protocols import check_module
|
||||
|
||||
|
||||
def check_process(module, study: Study):
|
||||
"""A process returns Labels aligned with the study's windows and round-trips save/load."""
|
||||
check_module(module, "process")
|
||||
for req in module.requires:
|
||||
assert req in study.labels, f"{module.name}: test study lacks required labels {req!r}"
|
||||
trained = module.train([study])
|
||||
assert trained is not None, f"{module.name}.train must return the module"
|
||||
out = trained.predict(study)
|
||||
assert isinstance(out, Labels), f"{module.name}.predict must return Labels, not {type(out)}"
|
||||
assert out.process == module.name, f"{module.name}: Labels.process is {out.process!r}"
|
||||
if out.per_window is not None:
|
||||
assert out.per_window.index.equals(study.prep.windows.index), \
|
||||
f"{module.name}: per_window index must equal Preprocessed.windows.index"
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
trained.save(Path(d))
|
||||
again = type(trained).load(Path(d)).predict(study)
|
||||
_same_labels(out, again, module.name)
|
||||
return out
|
||||
|
||||
|
||||
def check_biomarker(module, studies: Sequence[Study], ages_months: Sequence[float]):
|
||||
"""A biomarker measures, trains from studies and from a table, and predicts DEVIATION_COLUMNS."""
|
||||
check_module(module, "biomarker")
|
||||
vals = module.measure(studies[0])
|
||||
assert set(vals) == set(module.features), \
|
||||
f"{module.name}.measure returned {sorted(vals)}, features are {sorted(module.features)}"
|
||||
for k, v in vals.items():
|
||||
assert isinstance(v, (int, float)) and not isinstance(v, bool), \
|
||||
f"{module.name}: feature {k} must be a number, got {type(v)}"
|
||||
|
||||
fresh = copy.deepcopy(module)
|
||||
trained = module.train(list(studies), list(ages_months))
|
||||
out = trained.predict(studies[0], age_months=ages_months[0])
|
||||
_check_deviation(out, module)
|
||||
|
||||
table = pd.DataFrame([fresh.measure(s) for s in studies])
|
||||
table["age_months"] = list(ages_months)
|
||||
trained2 = fresh.train(table)
|
||||
out2 = trained2.predict(table.iloc[[0]])
|
||||
_check_deviation(out2, module)
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
trained.save(Path(d))
|
||||
again = type(trained).load(Path(d)).predict(studies[0], age_months=ages_months[0])
|
||||
pd.testing.assert_frame_equal(out.reset_index(drop=True), again.reset_index(drop=True))
|
||||
return out
|
||||
|
||||
|
||||
def check_preprocessed(prep: Preprocessed):
|
||||
"""The output of a Preprocessor."""
|
||||
assert isinstance(prep, Preprocessed)
|
||||
w = prep.windows
|
||||
assert (w["end_s"] > w["start_s"]).all(), "windows must have end_s > start_s"
|
||||
assert w["clean"].dtype == bool and w["gap"].dtype == bool, "clean and gap must be boolean"
|
||||
assert isinstance(prep.plan, dict) and "schema" in prep.plan, "plan must be a schema-tagged dict"
|
||||
assert prep.plan_hash, "plan_hash is empty"
|
||||
return prep
|
||||
|
||||
|
||||
def check_validation(fhir: dict, valid: int, summary: ValidationSummary | None = None):
|
||||
"""The output of a Validator."""
|
||||
assert valid in (0, 1), f"valid must be 0 or 1, not {valid!r}"
|
||||
assert fhir.get("resourceType") == "Bundle", "validate must return a FHIR Bundle"
|
||||
reports = [e["resource"] for e in fhir.get("entry", [])
|
||||
if e["resource"].get("resourceType") == "DiagnosticReport"]
|
||||
assert len(reports) == 1, "the Bundle must hold exactly one DiagnosticReport"
|
||||
code = reports[0]["conclusionCode"][0]["coding"][0]["code"]
|
||||
assert code == ("valid" if valid else "not-valid"), \
|
||||
f"conclusionCode {code!r} disagrees with valid={valid}"
|
||||
if summary is not None:
|
||||
assert summary.valid == valid, "summary.valid disagrees with validate()"
|
||||
|
||||
|
||||
def _check_deviation(df: pd.DataFrame, module):
|
||||
assert isinstance(df, pd.DataFrame), f"{module.name}.predict must return a DataFrame"
|
||||
assert tuple(df.columns[: len(DEVIATION_COLUMNS)]) == DEVIATION_COLUMNS, \
|
||||
f"{module.name}.predict columns {list(df.columns)} must start with {DEVIATION_COLUMNS}"
|
||||
assert set(df["feature"]) <= set(module.features), f"{module.name}: unknown feature in predict"
|
||||
assert df["outside"].isin([-1, 0, 1]).all(), f"{module.name}: outside must be -1, 0 or 1"
|
||||
|
||||
|
||||
def _same_labels(a: Labels, b: Labels, name: str):
|
||||
if a.per_window is not None:
|
||||
pd.testing.assert_series_equal(a.per_window, b.per_window, obj=f"{name} per_window")
|
||||
if a.events is not None:
|
||||
pd.testing.assert_frame_equal(a.events.reset_index(drop=True),
|
||||
b.events.reset_index(drop=True), obj=f"{name} events")
|
||||
Reference in New Issue
Block a user