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:
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
|
||||
def make_prep(seconds=60.0, fs=250.0, channels=("Fp1", "Fp2", "O1", "O2"), seed=0,
|
||||
window_s=4.0, step_s=2.0):
|
||||
"""A small Preprocessed made in memory (white noise, one variant)."""
|
||||
import mne
|
||||
from tea_modulo.contracts import Preprocessed
|
||||
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(seconds * fs)
|
||||
info = mne.create_info(list(channels), fs, ch_types="eeg")
|
||||
raw = mne.io.RawArray(rng.normal(0, 20e-6, (len(channels), n)), info, verbose="error")
|
||||
starts = np.arange(0, seconds - window_s + 1e-9, step_s)
|
||||
windows = pd.DataFrame({"start_s": starts, "end_s": starts + window_s,
|
||||
"clean": np.ones(len(starts), bool),
|
||||
"gap": np.zeros(len(starts), bool)})
|
||||
plan = {"schema": 1, "name": "test"}
|
||||
return Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
|
||||
plan=plan, plan_hash="test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def prep():
|
||||
return make_prep()
|
||||
@@ -0,0 +1,154 @@
|
||||
"""
|
||||
The contracts themselves, and the contract suites run against fake modules
|
||||
(the shape a replacement module must have).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tea_modulo.contracts import (
|
||||
CONTRACT_VERSION,
|
||||
DEVIATION_COLUMNS,
|
||||
ContractError,
|
||||
Labels,
|
||||
Preprocessed,
|
||||
Study,
|
||||
check_module,
|
||||
)
|
||||
from tea_modulo.contracts.testing import check_biomarker, check_process
|
||||
|
||||
|
||||
class ConstantState:
|
||||
"""A fake process: every window is 'vigilia'."""
|
||||
|
||||
name = "sleep_state"
|
||||
version = "0.0.1"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ()
|
||||
|
||||
def train(self, studies):
|
||||
return self
|
||||
|
||||
def predict(self, study):
|
||||
w = study.prep.windows
|
||||
return Labels(self.name, per_window=pd.Series("vigilia", index=w.index))
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "params.json").write_text("{}")
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
return cls()
|
||||
|
||||
|
||||
class MeanAmplitude:
|
||||
"""A fake biomarker: mean absolute amplitude in µV, baseline = median and MAD."""
|
||||
|
||||
name = "mean_amplitude"
|
||||
version = "0.0.1"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("sleep_state",)
|
||||
features = ("mean_abs_uv",)
|
||||
|
||||
def __init__(self):
|
||||
self.median = None
|
||||
self.mad = None
|
||||
|
||||
def measure(self, study):
|
||||
x = study.prep.variant("hp05_prom").get_data() * 1e6
|
||||
return {"mean_abs_uv": float(np.mean(np.abs(x)))}
|
||||
|
||||
def train(self, data, ages_months=None):
|
||||
if isinstance(data, pd.DataFrame):
|
||||
v = data["mean_abs_uv"].to_numpy()
|
||||
else:
|
||||
v = np.array([self.measure(s)["mean_abs_uv"] for s in data])
|
||||
self.median = float(np.median(v))
|
||||
self.mad = float(np.median(np.abs(v - self.median))) or 1.0
|
||||
return self
|
||||
|
||||
def predict(self, data, age_months=None):
|
||||
if isinstance(data, pd.DataFrame):
|
||||
rows = data.to_dict("records")
|
||||
else:
|
||||
rows = [{**self.measure(data), "age_months": age_months}]
|
||||
out = []
|
||||
for r in rows:
|
||||
z = (r["mean_abs_uv"] - self.median) / self.mad
|
||||
out.append({"feature": "mean_abs_uv", "value": r["mean_abs_uv"],
|
||||
"age_months": r.get("age_months"), "outside": int(np.sign(z)) if abs(z) > 3 else 0,
|
||||
"z": z, "baseline": "median_mad"})
|
||||
return pd.DataFrame(out, columns=list(DEVIATION_COLUMNS))
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "baseline.json").write_text(json.dumps({"median": self.median, "mad": self.mad}))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
m = cls()
|
||||
d = json.loads(Path(path, "baseline.json").read_text())
|
||||
m.median, m.mad = d["median"], d["mad"]
|
||||
return m
|
||||
|
||||
|
||||
def _study(prep):
|
||||
return Study(prep).with_labels(ConstantState().predict(Study(prep)))
|
||||
|
||||
|
||||
def test_preprocessed_requires_window_columns(prep):
|
||||
with pytest.raises(ValueError, match="lacks columns"):
|
||||
Preprocessed(variants=prep.variants, windows=prep.windows.drop(columns="gap"),
|
||||
age_months=None, plan={"schema": 1}, plan_hash="x")
|
||||
|
||||
|
||||
def test_missing_variant_and_label_messages(prep):
|
||||
with pytest.raises(KeyError, match="hp05_orejas"):
|
||||
prep.variant("hp05_orejas")
|
||||
with pytest.raises(KeyError, match="no labels from process 'spindle_detection'"):
|
||||
Study(prep).label("spindle_detection")
|
||||
|
||||
|
||||
def test_labels_need_content_and_event_columns():
|
||||
with pytest.raises(ValueError, match="neither"):
|
||||
Labels("x")
|
||||
with pytest.raises(ValueError, match="duration_s"):
|
||||
Labels("x", events=pd.DataFrame({"onset_s": [1.0]}))
|
||||
|
||||
|
||||
def test_check_module_refuses_wrong_kind_and_version():
|
||||
with pytest.raises(ContractError, match="missing"):
|
||||
check_module(object(), "process")
|
||||
old = ConstantState()
|
||||
old.contract_version = "0.9"
|
||||
with pytest.raises(ContractError, match="contract 0.9"):
|
||||
check_module(old, "process")
|
||||
|
||||
|
||||
def test_fake_process_passes_the_suite(prep):
|
||||
check_process(ConstantState(), Study(prep))
|
||||
|
||||
|
||||
def test_fake_biomarker_passes_the_suite():
|
||||
from conftest import make_prep
|
||||
studies = [_study(make_prep(seed=i)) for i in range(6)]
|
||||
out = check_biomarker(MeanAmplitude(), studies, [20, 22, 24, 26, 28, 30])
|
||||
assert out["feature"].iloc[0] == "mean_abs_uv"
|
||||
|
||||
|
||||
def test_recording_from_edf(tmp_path):
|
||||
"""Recording.from_edf reads an EDF with MNE and keeps only the file stem."""
|
||||
import mne
|
||||
from tea_modulo.contracts import Recording
|
||||
info = mne.create_info(["Fp1", "O1"], 250.0, "eeg")
|
||||
raw = mne.io.RawArray(np.random.default_rng(0).normal(0, 20e-6, (2, 2500)), info, verbose="error")
|
||||
p = tmp_path / "study.edf"
|
||||
mne.export.export_raw(p, raw, fmt="edf", verbose="error")
|
||||
rec = Recording.from_edf(p, age_months=30)
|
||||
assert rec.raw.ch_names == ["Fp1", "O1"]
|
||||
assert rec.source_name == "study" and len(rec.source_sha256) == 64
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
The boundary rule: a module imports only `tea_modulo.contracts`, the standard
|
||||
library and its approved third-party libraries. It never imports another
|
||||
`tea_modulo` module, so any module can be replaced without touching the rest.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "src" / "tea_modulo"
|
||||
|
||||
# Approved third-party libraries (top-level import names).
|
||||
BASE = {"numpy", "scipy", "pandas", "mne", "sklearn", "antropy", "fooof", "yasa",
|
||||
"meegkit", "edfio"}
|
||||
LEGACY = {"numpy", "scipy", "pandas", "sklearn"}
|
||||
EXTRA = {
|
||||
"validation": {"fhir"},
|
||||
"serving": {"mlflow"},
|
||||
"pipeline": {"dask", "distributed", "s3fs", "fsspec"},
|
||||
"verify": {"dask", "distributed", "s3fs", "fsspec"},
|
||||
"export": set(),
|
||||
}
|
||||
# files allowed to touch MNE / FHIR inside legacy (the contract adapters)
|
||||
LEGACY_ADAPTERS = {"_adapter.py", "fhir.py", "api.py", "__init__.py"}
|
||||
|
||||
|
||||
def unit_of(path: Path) -> tuple[str, ...]:
|
||||
"""The replaceable unit a file belongs to, as a path tuple under tea_modulo."""
|
||||
rel = path.relative_to(SRC).parts
|
||||
if rel[0] == "legacy":
|
||||
rest = rel[1:]
|
||||
if len(rest) >= 2 and rest[0] in ("processes", "biomarkers") and len(rest) > 2:
|
||||
return ("legacy", rest[0], rest[1])
|
||||
if len(rest) >= 2:
|
||||
return ("legacy", rest[0])
|
||||
return ("legacy",)
|
||||
if rel[0] in ("processes", "biomarkers") and len(rel) > 2:
|
||||
return (rel[0], rel[1])
|
||||
if len(rel) == 1:
|
||||
return ()
|
||||
return (rel[0],)
|
||||
|
||||
|
||||
def imports_of(path: Path):
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
pkg = list(path.relative_to(SRC.parent).with_suffix("").parts)
|
||||
if path.name != "__init__.py":
|
||||
pkg = pkg[:-1]
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for a in node.names:
|
||||
yield a.name, node.lineno
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
if node.level:
|
||||
base = pkg[: len(pkg) - (node.level - 1)]
|
||||
mod = ".".join(base + ([node.module] if node.module else []))
|
||||
yield mod, node.lineno
|
||||
else:
|
||||
yield node.module or "", node.lineno
|
||||
|
||||
|
||||
def allowed_third_party(unit: tuple[str, ...], fname: str) -> set[str]:
|
||||
if not unit:
|
||||
return set()
|
||||
if unit[0] == "legacy":
|
||||
extra = {"mne", "fhir", "edfio"} if fname in LEGACY_ADAPTERS else set()
|
||||
return LEGACY | extra
|
||||
if unit[0] == "export":
|
||||
return {"numpy", "edfio"}
|
||||
return BASE | EXTRA.get(unit[0], set())
|
||||
|
||||
|
||||
FILES = sorted(p for p in SRC.rglob("*.py"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", FILES, ids=[str(p.relative_to(SRC)) for p in FILES])
|
||||
def test_imports_respect_boundaries(path):
|
||||
unit = unit_of(path)
|
||||
own = "tea_modulo." + ".".join(unit) if unit else "tea_modulo"
|
||||
bad = []
|
||||
for mod, line in imports_of(path):
|
||||
top = mod.split(".")[0]
|
||||
if top == "tea_modulo":
|
||||
if unit and unit[0] == "export":
|
||||
ok = mod == own or mod.startswith(own + ".")
|
||||
elif not unit:
|
||||
ok = mod in ("tea_modulo", "tea_modulo.contracts") or mod.startswith("tea_modulo.contracts.")
|
||||
else:
|
||||
ok = (mod == "tea_modulo.contracts" or mod.startswith("tea_modulo.contracts.")
|
||||
or mod == own or mod.startswith(own + "."))
|
||||
if unit == ("contracts",):
|
||||
ok = mod.startswith("tea_modulo.contracts")
|
||||
elif top in sys.stdlib_module_names or top == "__future__":
|
||||
ok = True
|
||||
else:
|
||||
ok = top in allowed_third_party(unit, path.name)
|
||||
if not ok:
|
||||
bad.append(f"line {line}: {mod}")
|
||||
assert not bad, f"{path.relative_to(SRC)} ({'.'.join(unit) or 'root'}) breaks the boundary: " + "; ".join(bad)
|
||||
|
||||
|
||||
def test_legacy_never_imports_dask():
|
||||
for p in (SRC / "legacy").rglob("*.py") if (SRC / "legacy").exists() else []:
|
||||
for mod, line in imports_of(p):
|
||||
assert mod.split(".")[0] not in ("dask", "distributed"), f"{p}:{line} imports {mod}"
|
||||
Reference in New Issue
Block a user