Files
tea/tests/contracts/test_contracts.py
T
AlbertoPMDM 449acf8b44 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.
2026-11-18 19:54:15 -06:00

155 lines
4.8 KiB
Python

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