TEA: ADOS-2 association job, EEG zone values, spike minutes as exposure and the count baselines' reference range; tea library 0.3.0
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
"""An invented ADOS-2 association cohort: one row per child in the `tea` library's cohort columns, with two planted
|
||||
effects (spikes in temporal_izq raise item 18, spindles in central lower the CSS) and everything else null."""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from tea.associations.ados2 import _items as items
|
||||
from tea.contracts import ZONES
|
||||
|
||||
ITEM_CODES = sorted({c for _, _, codes in items.ITEMS.values() for c in codes.values()})
|
||||
|
||||
|
||||
def cohort(n: int = 60, seed: int = 4, with_items: bool = True) -> pd.DataFrame:
|
||||
rng = np.random.default_rng(seed)
|
||||
age = rng.uniform(16, 37, n).round(1)
|
||||
module = np.where(age < 31, "TODDLER", np.where(rng.random(n) < .7, "MODULO_1", "MODULO_2"))
|
||||
t = pd.DataFrame({"key": [f"e-{i:03d}" for i in range(n)], "age_months": age, "ados_module": module})
|
||||
shared = rng.normal(0, 1, n)
|
||||
for zone in ZONES:
|
||||
t[f"z_spikes_{zone}"] = (.5 * shared + .85 * rng.normal(0, 1, n)).round(3)
|
||||
t[f"z_spindles_{zone}"] = rng.normal(0, 1, n).round(3)
|
||||
t["z_posterior_rhythm"] = rng.normal(0, 1, n).round(3)
|
||||
t["z_gradient"] = rng.normal(0, 1, n).round(3)
|
||||
for number, (_, _, codes) in items.ITEMS.items():
|
||||
latent = rng.logistic(0, 1, n) + (1.6 * t["z_spikes_temporal_izq"].to_numpy() if number == 18 else 0)
|
||||
level = np.digitize(latent, [-.3, 1.4, 3.2])
|
||||
for m, code in codes.items():
|
||||
if code not in t:
|
||||
t[code] = np.nan
|
||||
t.loc[t.ados_module == m, code] = level[t.ados_module.to_numpy() == m]
|
||||
severity = rng.normal(0, 1, n) - .9 * t["z_spindles_central"].to_numpy()
|
||||
t["css"] = np.clip(np.round(6 + 1.8 * severity), 1, 10).astype(int)
|
||||
for code in ITEM_CODES:
|
||||
if code not in t:
|
||||
t[code] = np.nan
|
||||
return t if with_items else t.drop(columns=ITEM_CODES)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""What this module covers: the `tea` library's ADOS-2 association (`tea.associations.ados2`, modern, and
|
||||
`tea.legacy.associations.ados2`, the research code vendored): the pairs it tests, the module-independent outcome
|
||||
codes, recovery of planted effects, legacy and modern agreeing, the per-child scores and the saved state.
|
||||
|
||||
Fixtures: `cohort_items`, 60 invented children of 16 to 37 months (Toddler module under 31 months, Module 1 or 2
|
||||
above) with item scores and a CSS, whose spike z in temporal_izq raises item 18 (intonation) and whose spindle z in
|
||||
central lowers the CSS, everything else null; `cohort_css`, the same children without item scores; `fits`, both
|
||||
implementations fitted once on each cohort.
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from ados2_cohort import ITEM_CODES, cohort
|
||||
|
||||
from tea.associations.ados2 import Ados2Association
|
||||
from tea.associations.ados2 import _items as items
|
||||
from tea.contracts import ASSOCIATION_COLUMNS, SCORE_COLUMNS, ZONES
|
||||
from tea.legacy.associations.ados2 import LegacyAdos2Association
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cohort_items():
|
||||
"""60 children with item scores: spikes in temporal_izq raise item 18, spindles in central lower the CSS."""
|
||||
return cohort()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cohort_css(cohort_items):
|
||||
"""The same children with the CSS only, as when the psychologist reports no items."""
|
||||
return cohort_items.drop(columns=[c for c in ITEM_CODES if c in cohort_items])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fits(cohort_items, cohort_css):
|
||||
"""Modern and legacy, each fitted once on both cohorts, by (impl, level)."""
|
||||
return {(impl, level): cls().fit(c) for impl, cls in (("modern", Ados2Association),
|
||||
("legacy", LegacyAdos2Association))
|
||||
for level, c in (("item", cohort_items), ("domain", cohort_css))}
|
||||
|
||||
|
||||
def test_level_follows_the_cohort_and_codes_are_module_independent(fits):
|
||||
"""Pins down: a cohort with items is fitted by item and one without by the CSS; item outcomes carry
|
||||
`ados2_item_NN` and domain outcomes `CSS`, with events `>=1` and `>=8`; zones are the library's, `posterior`
|
||||
or `global`. Fails if the level stops following the data, an outcome goes back to a per-module column code (one
|
||||
code is another item in another module), or a zone code leaves the shared list."""
|
||||
for impl in ("modern", "legacy"):
|
||||
assert fits[impl, "item"].fitted["level"] == "item"
|
||||
assert fits[impl, "domain"].fitted["level"] == "domain"
|
||||
a = fits[impl, "item"].associations()
|
||||
assert list(a.columns) == list(ASSOCIATION_COLUMNS)
|
||||
assert set(a.outcome_code) <= {items.item_code(n) for n in items.ITEMS} | {"CSS"}
|
||||
assert set(a.loc[a.kind == "item", "event"]) == {">=1"}
|
||||
assert set(a.loc[a.kind == "domain", "event"]) == {">=8"}
|
||||
assert set(a.zone) <= set(ZONES) | {"posterior", "global"}
|
||||
assert set(fits[impl, "domain"].associations().outcome_code) == {"CSS"}
|
||||
|
||||
|
||||
def test_the_planted_effects_are_found(fits):
|
||||
"""Pins down: the item fit finds spikes in temporal_izq raising item 18 (odds ratio above 1, q < 0.05) and the CSS
|
||||
fit finds spindles in central lowering the CSS (odds ratio below 1, q < 0.05). Fails if the Firth or ordinal fit,
|
||||
the item read per module, or the q values break."""
|
||||
a = fits["modern", "item"].associations().set_index(["biomarker", "zone", "outcome_code"])
|
||||
item = a.loc[("spikes", "temporal_izq", "ados2_item_18")]
|
||||
assert item.odds_ratio > 1 and item.q < .05
|
||||
d = fits["modern", "domain"].associations().set_index(["biomarker", "zone", "outcome_code"])
|
||||
css = d.loc[("spindles", "central", "CSS")]
|
||||
assert css.odds_ratio < 1 and css.q < .05
|
||||
|
||||
|
||||
@pytest.mark.parametrize("level", ["item", "domain"])
|
||||
def test_legacy_and_modern_agree(fits, cohort_items, cohort_css, level):
|
||||
"""Pins down: the modern port gives the vendored research code's odds ratios, intervals, p, q and per-child
|
||||
probabilities exactly, at both levels. Fails if either side's design matrix, fit, interval search, FLIC
|
||||
intercept or pair list drifts from the other."""
|
||||
cohort = cohort_items if level == "item" else cohort_css
|
||||
m, legacy = fits["modern", level], fits["legacy", level]
|
||||
keys = ["biomarker", "zone", "outcome_code"]
|
||||
joined = m.associations().merge(legacy.associations(), on=keys, suffixes=("_m", "_l"), validate="1:1")
|
||||
assert len(joined) == len(m.associations()) == len(legacy.associations())
|
||||
for c in ("odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio"):
|
||||
np.testing.assert_allclose(joined[f"{c}_m"].astype(float), joined[f"{c}_l"].astype(float), rtol=1e-9)
|
||||
scores = m.score(cohort).merge(legacy.score(cohort), on=["key", *keys], suffixes=("_m", "_l"), validate="1:1")
|
||||
assert len(scores) == len(legacy.score(cohort)) > 0
|
||||
np.testing.assert_allclose(scores.probability_m, scores.probability_l, atol=1e-9)
|
||||
np.testing.assert_allclose(scores.reference_probability_m, scores.reference_probability_l, atol=1e-9)
|
||||
|
||||
|
||||
def test_an_item_is_read_from_the_column_of_the_childs_module(cohort_items):
|
||||
"""Pins down: item 11 (showing) is `sa_b12` in the Toddler module, `sa_b9` in Module 1 and `sa_b5` in Module 2,
|
||||
and each child's score comes from its own module's column, with 3 as 2 and 7 as 0. Fails if items are read by
|
||||
one column code for every module."""
|
||||
t = pd.DataFrame({"ados_module": ["TODDLER", "MODULO_1", "MODULO_2", "MODULO_2"],
|
||||
"sa_b12": [1, 2, 0, 0], "sa_b9": [0, 3, 0, 0], "sa_b5": [2, 0, 7, np.nan]})
|
||||
assert items.item_scores(t, 11).tolist()[:3] == [1.0, 2.0, 0.0]
|
||||
assert np.isnan(items.item_scores(t, 11).iloc[3])
|
||||
|
||||
|
||||
def test_scores_cover_only_the_modules_with_the_item_and_survive_save_and_load(fits, cohort_items, tmp_path):
|
||||
"""Pins down: a child is scored on an item only when its module has that item, every score row has a z and a
|
||||
probability in [0, 1], and a saved and reloaded fit scores the same. Fails if scoring ignores the module, the
|
||||
saved state misses what scoring needs, or the columns drift from `SCORE_COLUMNS`."""
|
||||
m = fits["modern", "item"]
|
||||
scores = m.score(cohort_items)
|
||||
assert list(scores.columns) == list(SCORE_COLUMNS)
|
||||
modules = cohort_items.set_index("key").ados_module
|
||||
item_16 = scores[scores.outcome_code == "ados2_item_16"] # Module 2 only
|
||||
assert set(modules[item_16.key]) <= {"MODULO_2"}
|
||||
assert scores.probability.between(0, 1).all() and scores.z.notna().all()
|
||||
m.save(tmp_path)
|
||||
again = Ados2Association.load(tmp_path).score(cohort_items)
|
||||
pd.testing.assert_frame_equal(scores, again)
|
||||
|
||||
|
||||
def test_registered_under_the_association_groups():
|
||||
"""Pins down: both implementations resolve through the entry points and pass the association protocol, and
|
||||
the per-study pipeline does not load them. Fails if a registration is dropped or the association lands in the
|
||||
pipeline's module groups."""
|
||||
from tea.pipeline import registry
|
||||
|
||||
assert registry.association("ados2_association").impl == "modern"
|
||||
assert registry.association("ados2_association", "legacy").impl == "legacy"
|
||||
assert "ados2_association" not in registry.available("modern")
|
||||
|
||||
|
||||
def test_a_module_the_fit_never_saw_is_not_scored_as_the_reference(fits, cohort_items):
|
||||
"""Pins down: a child whose module was not in the pair's fit (here an unknown `MODULO_3`) gets no probability
|
||||
instead of the reference module's. Fails if unseen levels fall back to all-zero indicators."""
|
||||
m = fits["modern", "domain"]
|
||||
other = cohort_items.head(3).assign(ados_module="MODULO_3", key=["x-1", "x-2", "x-3"])
|
||||
assert m.score(other).empty
|
||||
|
||||
|
||||
def test_a_singular_pair_or_an_infinite_z_does_not_stop_the_fit(cohort_css):
|
||||
"""Pins down: a predictor equal to the module indicator (a rank-deficient design) leaves that pair with a reason
|
||||
and no estimate while every other pair is fitted, and an infinite z is dropped rather than fitted. Fails if a
|
||||
singular information matrix aborts the whole fit, or `inf` reaches the design."""
|
||||
t = cohort_css.copy()
|
||||
t["z_gradient"] = (t["ados_module"] == "TODDLER").astype(float)
|
||||
t.loc[0, "z_posterior_rhythm"] = np.inf
|
||||
a = Ados2Association().fit(t).associations().set_index(["biomarker", "zone"])
|
||||
assert a["odds_ratio"].notna().sum() >= len(a) - 2
|
||||
assert a.loc[("posterior_rhythm", "posterior"), "n"] == len(t) - 1
|
||||
@@ -0,0 +1,140 @@
|
||||
"""What this module covers: the ADOS-2 association against the TEA database (`models.ados2_relation`): the cohort
|
||||
it builds from bronze (first valid EEG and first ADOS-2 per child), the rows it writes to `relacion_ados2` and
|
||||
`relacion_ados2_paciente`, and versions (a new cohort is a later version, the same cohort writes nothing).
|
||||
|
||||
Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, the invented cohort of `ados2_cohort` without item
|
||||
scores (60 children, spindles in central lowering the CSS) written to bronze: each child with an ADOS-2 and a valid
|
||||
analysed EEG `e-NNN` whose metric z and zone z are the cohort's, plus a later valid EEG `e-000-b` of child 1, an
|
||||
invalid EEG of child 2 and a child 99 with an EEG and no ADOS-2.
|
||||
"""
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from ados2_cohort import ITEM_CODES, cohort
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from core.tea.models import Ados2, Eeg, EegMetrica, EegMetricaZona, Pacientes, RelacionAdos2, RelacionAdos2Paciente
|
||||
from models import ados2_relation as rel
|
||||
from tea.contracts import ZONES
|
||||
|
||||
CODES = {"spikes": "PICOS_PAROXISTICOS", "spindles": "HUSOS_SUENO_N2", "posterior_rhythm": "RITMO_POSTERIOR",
|
||||
"gradient": "GRADIENTE_ANTEROPOSTERIOR"}
|
||||
|
||||
|
||||
def _eeg(session, eeg_id, pac_id, row, *, studied=date(2025, 6, 1), valid=1):
|
||||
session.add(Eeg(eeg_id=eeg_id, eeg_pac_id=pac_id, eeg_fecha_estudio=studied, eeg_valido=valid,
|
||||
eeg_edad_meses=float(row.age_months)))
|
||||
for biomarker, code in CODES.items():
|
||||
met_id = f"{eeg_id}/{code}"
|
||||
zoned = biomarker in rel.ZONED
|
||||
session.add(EegMetrica(met_id=met_id, met_eeg_id=eeg_id, met_codigo=code,
|
||||
met_z=None if zoned else float(row[f"z_{biomarker}"])))
|
||||
if zoned:
|
||||
session.add_all([EegMetricaZona(mez_id=f"{met_id}/{z}", mez_met_id=met_id, mez_zona=z,
|
||||
mez_z=float(row[f"z_{biomarker}_{z}"])) for z in ZONES])
|
||||
|
||||
|
||||
def _engine():
|
||||
from persistance.db import get_tea_engine
|
||||
|
||||
return get_tea_engine()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stored(tea_db):
|
||||
"""The CSS-only invented cohort in bronze, with the extra EEGs and child the module docstring lists."""
|
||||
t = cohort().drop(columns=ITEM_CODES)
|
||||
with Session(_engine()) as s:
|
||||
for i, row in t.iterrows():
|
||||
pac_id = i + 1
|
||||
s.add(Pacientes(pac_id=pac_id, pac_id_hospital=f"H-{pac_id}"))
|
||||
s.add(Ados2(ado_id=f"a-{pac_id}", ado_pac_id=pac_id, ado_fecha=date(2025, 5, 1),
|
||||
ado_modulo=row.ados_module, ado_css=int(row.css)))
|
||||
_eeg(s, row.key, pac_id, row)
|
||||
_eeg(s, "e-000-b", 1, t.iloc[0], studied=date(2025, 9, 1))
|
||||
_eeg(s, "e-001-x", 2, t.iloc[1], studied=date(2025, 3, 1), valid=0)
|
||||
s.add(Pacientes(pac_id=99, pac_id_hospital="H-99"))
|
||||
_eeg(s, "e-099", 99, t.iloc[2])
|
||||
s.commit()
|
||||
return t
|
||||
|
||||
|
||||
def _read():
|
||||
with Session(_engine()) as s:
|
||||
return s.exec(select(RelacionAdos2)).all(), s.exec(select(RelacionAdos2Paciente)).all()
|
||||
|
||||
|
||||
def test_a_fit_writes_one_version_of_estimated_rows_on_the_platform_codes(stored):
|
||||
"""Pins down: one fit writes a `tea-<time>-<fingerprint>` version, unvalidated, over the 60 children with a
|
||||
valid EEG and an ADOS-2, with the metric codes, `CSS` outcomes and an `>=8` event, and finds the planted
|
||||
spindle effect in central. Fails if the cohort takes the child without ADOS-2 or the invalid EEG, the
|
||||
biomarker codes stop following `model.toml`, or the written estimates stop being the library's."""
|
||||
summary = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
models, patients = _read()
|
||||
assert summary.children == 60 and summary.level == "domain"
|
||||
assert summary.version.startswith("tea-20261121T120000-") and len(summary.version) <= 32
|
||||
assert {m.rel_version for m in models} == {summary.version} and len(models) == summary.associations
|
||||
assert {m.rel_validado for m in models} == {0} and {m.rel_n_cohorte for m in models} == {60}
|
||||
assert {m.rel_resultado for m in models} == {"CSS"} and {m.rel_evento for m in models} == {">=8"}
|
||||
assert {m.rel_biomarcador for m in models} <= set(CODES.values())
|
||||
central = next(m for m in models if m.rel_biomarcador == "HUSOS_SUENO_N2" and m.rel_zona == "central")
|
||||
assert central.rel_or < 1 and central.rel_q < .05
|
||||
assert len(patients) == summary.scored
|
||||
|
||||
|
||||
def test_every_valid_eeg_of_the_cohort_is_scored_and_no_other(stored):
|
||||
"""Pins down: child 1's later valid EEG gets probabilities too (the gold view shows the study's EEG, whichever
|
||||
it is), while the invalid EEG and the EEG of the child without ADOS-2 get none. Fails if scoring stops at the
|
||||
fit's EEGs or starts scoring outside the cohort."""
|
||||
rel.relate()
|
||||
_, patients = _read()
|
||||
eegs = {p.rap_eeg_id for p in patients}
|
||||
assert {"e-000", "e-000-b"} <= eegs
|
||||
assert not {"e-001-x", "e-099"} & eegs
|
||||
assert all(0 <= p.rap_probabilidad <= 1 and 0 <= p.rap_probabilidad_referencia <= 1 for p in patients)
|
||||
|
||||
|
||||
def test_the_same_cohort_writes_nothing_and_a_new_one_is_a_later_version(stored):
|
||||
"""Pins down: fitting the same cohort again writes nothing and names the latest version; a changed z is a new
|
||||
version that sorts after the first, so the gold view's greatest version is the newest fit. Fails if reruns
|
||||
duplicate versions, or the version stops sorting by time."""
|
||||
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
again = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
||||
assert again.unchanged and again.version == first.version
|
||||
assert len({m.rel_version for m in _read()[0]}) == 1
|
||||
with Session(_engine()) as s:
|
||||
zone = s.get(EegMetricaZona, "e-000/HUSOS_SUENO_N2/central")
|
||||
zone.mez_z = 3.0
|
||||
s.add(zone)
|
||||
s.commit()
|
||||
later = rel.relate(at=datetime(2026, 11, 23, 12, 0, 0))
|
||||
assert not later.unchanged and later.version > first.version
|
||||
assert {m.rel_version for m in _read()[0]} == {first.version, later.version}
|
||||
|
||||
|
||||
def test_an_open_interval_is_stored_as_null():
|
||||
"""Pins down: an infinite interval limit (the profile never crossed the threshold) is stored as NULL, which every
|
||||
engine accepts. Fails if `inf` reaches the database (MySQL and SQL Server reject it)."""
|
||||
assert rel._finite(float("inf")) is None and rel._finite(None) is None and rel._finite(2.5) == 2.5
|
||||
|
||||
|
||||
def test_the_fit_uses_the_first_eeg_with_predictors_and_a_new_eeg_is_a_new_version(stored):
|
||||
"""Pins down: a child whose earliest valid EEG has no metric rows is fitted on its next EEG, and a valid EEG
|
||||
added for a child already in the fit (so the fit table is the same) is still a new version that scores it.
|
||||
Fails if the fit takes an EEG without predictors (the child would drop out of every model), or the fingerprint
|
||||
covers only the fit table (the new EEG would stay unscored)."""
|
||||
with Session(_engine()) as s:
|
||||
s.add(Eeg(eeg_id="e-000-a", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 1, 1), eeg_valido=1,
|
||||
eeg_edad_meses=20.0))
|
||||
s.commit()
|
||||
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
assert first.children == 60
|
||||
assert "e-000-a" not in {p.rap_eeg_id for p in _read()[1]}
|
||||
with Session(_engine()) as s:
|
||||
_eeg(s, "e-000-c", 1, stored.iloc[0], studied=date(2025, 12, 1))
|
||||
s.commit()
|
||||
later = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
||||
assert not later.unchanged and later.version > first.version
|
||||
models, patients = _read()
|
||||
latest = {m.rel_id for m in models if m.rel_version == later.version}
|
||||
assert "e-000-c" in {p.rap_eeg_id for p in patients if p.rap_rel_id in latest}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Outside markers for centile and age-block references in modern and legacy tea.
|
||||
|
||||
Fixtures: parameterized baseline modules and in-memory synthetic control values.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from tea.biomarkers.spindles import _baseline as modern
|
||||
from tea.legacy.biomarkers.spindles import _baseline as legacy
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", (modern, legacy))
|
||||
def test_centile_outside_requires_a_reference(baseline):
|
||||
"""Pin float -1/0/+1 and missing values. Fails if missing data, uncovered ages or sparse controls give zero."""
|
||||
curve = baseline.CentileCurves().fit(np.tile([1, 2, 3], 50), np.repeat([12, 24, 36], 50))
|
||||
outside, _ = curve.deviation([0, 2, 4, np.nan, 2, 2], [24, 24, 24, 24, 60, np.nan])
|
||||
assert outside.dtype.kind == "f"
|
||||
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan, np.nan])
|
||||
sparse = baseline.CentileCurves().fit([1, 2], [12, 36])
|
||||
assert np.isnan(sparse.deviation([2], [24])[0][0])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", (modern, legacy))
|
||||
def test_age_block_outside_requires_a_z_score(baseline):
|
||||
"""Pin float markers with a valid score. Fails if a missing score or degenerate MAD is classified in range."""
|
||||
fitted = baseline.AgeBlockZ().fit(np.arange(30), np.full(30, 24))
|
||||
outside, _ = fitted.deviation([-2, 15, 40, np.nan, 15], [24, 24, 24, 24, np.nan])
|
||||
assert outside.dtype.kind == "f"
|
||||
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan])
|
||||
flat = baseline.AgeBlockZ().fit(np.ones(30), np.full(30, 24))
|
||||
assert np.isnan(flat.deviation([1], [24])[0][0])
|
||||
@@ -144,7 +144,34 @@ def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves)
|
||||
(1, "tea-eeg-posterior-rhythm/3")
|
||||
assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None
|
||||
electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo))
|
||||
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"))
|
||||
mapped = [m.code for m in settings().metrics if m.electrodes]
|
||||
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in mapped)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ("uncovered_age", "missing_cutoffs"))
|
||||
def test_missing_reference_stores_null_outside(bronze, curves, case):
|
||||
"""Pin SQL NULL when a reference interval is absent. Fails if a missing marker is cast to int or stored as zero."""
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
age = 60.0
|
||||
if case == "missing_cutoffs":
|
||||
from tea.biomarkers.posterior_rhythm._baseline import AgeBlockZ
|
||||
|
||||
age = 26.0
|
||||
reference = AgeBlockZ().fit([5.0, 6.0, 7.0], [age] * 3)
|
||||
reference.state["cortes"] = [float("nan")] * 2
|
||||
curves.module("eeg-posterior-rhythm").baseline = reference
|
||||
|
||||
measurement = fake_measure("e-1", b"edf", age, settings())
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, "e-1", rows(measurement, settings(), curves))
|
||||
session.commit()
|
||||
metric = next(row for row in _all(EegMetrica) if row.met_codigo == "RITMO_POSTERIOR")
|
||||
assert metric.met_valor == 9.0
|
||||
assert metric.met_modelo == "tea-eeg-posterior-rhythm/3"
|
||||
assert metric.met_fuera is None
|
||||
if case == "missing_cutoffs":
|
||||
assert metric.met_z == pytest.approx(3.0 / 1.4826)
|
||||
|
||||
|
||||
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""What this module covers: the zone values of the EEG analysis (`models.tea.eeg.settings` zones,
|
||||
`analyze._metrics`, `models.eeg_analysis.rows` and `save`): which metrics read zones, how a biomarker's
|
||||
`<zone_prefix><zone>` features become a metric's zones, and the `eeg_metrica_zona` rows with the z of the zone's
|
||||
baseline, replaced on the next analysis.
|
||||
|
||||
Fixtures: `tea_db` (an empty SQLite TEA database); `spike_zones`, `Baselines` whose only production version is
|
||||
`tea-eeg-spikes/2`, a spikes module with one centile curve, 0.5/1/2 spikes per minute at p5/median/p95 at every age,
|
||||
for `spike_zone_rate_nrem_temporal_izq` alone.
|
||||
"""
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from core.tea.models import Eeg, EegMetrica, EegMetricaZona, Pacientes
|
||||
from models.eeg_analysis import rows, save
|
||||
from models.tea.eeg.analyze import Measurement, MetricValue, _metrics
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
from models.tea.eeg.settings import settings
|
||||
from tea.contracts import ZONES
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def spike_zones():
|
||||
"""Spikes in production with a curve for the temporal_izq zone feature only."""
|
||||
from tea.biomarkers.spikes._baseline import CentileCurves
|
||||
|
||||
curve = pd.DataFrame({"edad_meses": [12.0, 36.0], "n_efectivo": [50.0] * 2, "p5": [0.5] * 2, "p25": [0.8] * 2,
|
||||
"mediana": [1.0] * 2, "p75": [1.4] * 2, "p95": [2.0] * 2})
|
||||
module = SimpleNamespace(baselines={"spike_zone_rate_nrem_temporal_izq": CentileCurves(curva=curve)})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="2", model_uri="models:/tea-eeg-spikes/2")
|
||||
|
||||
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
|
||||
|
||||
|
||||
def test_spikes_and_spindles_read_zones_and_their_scenarios_are_trained():
|
||||
"""Pins down: the spike metric reads `spike_zone_rate_nrem_<zone>` and the per-electrode `spike_density_nrem_<E>`
|
||||
from spikes with `spike_minutes_nrem` as exposure, both spindle metrics read `spindle_zone_<zone>` from spindles
|
||||
at their stage, and no scenario is added for them (the zone features train with the metric's own biomarker).
|
||||
Fails if `model.toml` loses the zones the ADOS-2 association reads, or zones start a scenario of their own."""
|
||||
s = settings()
|
||||
by_code = {m.code: m for m in s.metrics}
|
||||
spikes = by_code["PICOS_PAROXISTICOS"]
|
||||
assert (spikes.zones, spikes.zone_prefix, spikes.electrodes, spikes.electrode_prefix) == (
|
||||
"spikes", "spike_zone_rate_nrem_", "spikes", "spike_density_nrem_")
|
||||
assert spikes.exposure == "spike_minutes_nrem"
|
||||
assert spikes.zone_scenario == spikes.scenario == "eeg-spikes"
|
||||
for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"):
|
||||
assert (by_code[code].zones, by_code[code].zone_prefix) == ("spindles", "spindle_zone_")
|
||||
assert set(s.scenarios) == {"eeg-posterior-rhythm", "eeg-spindles-n2", "eeg-spindles-n3",
|
||||
"eeg-spindle-topography-n2", "eeg-spindle-topography-n3", "eeg-spikes",
|
||||
"eeg-gradient"}
|
||||
|
||||
|
||||
def test_a_biomarkers_zone_features_become_the_metrics_zones():
|
||||
"""Pins down: the features named `<zone_prefix><zone>` are the metric's zones by zone code, the electrode map
|
||||
keeps its own prefix, and a feature whose name only starts like the prefix's biomarker is left out. Fails if
|
||||
the prefix is not stripped or zone and electrode features mix."""
|
||||
s = settings()
|
||||
spikes = {"spike_rate_nrem": 0.7, "spike_density_nrem_T3": 1.2,
|
||||
**{f"spike_zone_rate_nrem_{z}": float(i) for i, z in enumerate(ZONES)},
|
||||
"spike_zone_rate_awake_central": 9.0, "spike_minutes_nrem": 12.5}
|
||||
measured = {("posterior_rhythm", None): {}, ("spindles", "N2"): {}, ("spindles", "N3"): {},
|
||||
("spindle_topography", "N2"): {}, ("spindle_topography", "N3"): {}, ("spikes", None): spikes,
|
||||
("gradient", None): {}}
|
||||
value = {v.code: v for v in _metrics(measured, s)}["PICOS_PAROXISTICOS"]
|
||||
assert value.value == 0.7
|
||||
assert value.electrodes == {"T3": 1.2}
|
||||
assert value.zones == {z: float(i) for i, z in enumerate(ZONES)}
|
||||
assert value.exposure == 12.5
|
||||
|
||||
|
||||
def test_zone_rows_carry_the_zone_baselines_z_and_are_replaced(tea_db, spike_zones):
|
||||
"""Pins down: each zone of a metric is an `eeg_metrica_zona` row of that metric, with the z of the zone's own
|
||||
curve where one is in production and null elsewhere, and a new analysis replaces them. Fails if zone rows are
|
||||
not written, read another feature's baseline, or pile up across analyses."""
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
s = settings()
|
||||
with eeg_repository.open_session() as session:
|
||||
session.add_all([Pacientes(pac_id=1), Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1))])
|
||||
session.commit()
|
||||
zones = {"temporal_izq": 2.0, "central": 1.0}
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {}, zones if x.code == "PICOS_PAROXISTICOS" else {})
|
||||
for x in s.metrics))
|
||||
for _ in range(2):
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, "e-1", rows(m, s, spike_zones))
|
||||
session.commit()
|
||||
with eeg_repository.open_session() as session:
|
||||
found = {z.mez_zona: z for z in session.exec(select(EegMetricaZona)).all()}
|
||||
met_id = session.exec(select(EegMetrica.met_id).where(EegMetrica.met_codigo == "PICOS_PAROXISTICOS")).one()
|
||||
assert set(found) == {"temporal_izq", "central"}
|
||||
assert {z.mez_met_id for z in found.values()} == {met_id}
|
||||
assert found["temporal_izq"].mez_z == pytest.approx(1.645) and found["temporal_izq"].mez_valor == 2.0
|
||||
assert found["central"].mez_z is None
|
||||
|
||||
|
||||
def test_a_count_baseline_gets_the_metrics_minutes(tea_db):
|
||||
"""Pins down: a baseline whose `deviation` takes `exposure` gets the metric's minutes for the value, every
|
||||
electrode and every zone, and one without that parameter is called as before. Fails if the minutes stop reaching
|
||||
count baselines (spike z would be computed against no exposure) or curves start receiving them."""
|
||||
import numpy as np
|
||||
|
||||
seen = []
|
||||
|
||||
class Count:
|
||||
def deviation(self, values, ages_months, exposure=None):
|
||||
seen.append(float(exposure[0]))
|
||||
return np.array([0.0]), np.array([1.0])
|
||||
|
||||
module = SimpleNamespace(baselines={"spike_rate_nrem": Count(), "spike_density_nrem_T3": Count(),
|
||||
"spike_zone_rate_nrem_central": Count()})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
|
||||
|
||||
s = settings()
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {"T3": 0.5}, {"central": 0.2}, 12.5)
|
||||
if x.code == "PICOS_PAROXISTICOS" else MetricValue(x.code, 1.0)
|
||||
for x in s.metrics))
|
||||
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
|
||||
assert seen == [12.5, 12.5, 12.5]
|
||||
assert [z.mez_z for z in out.zones] == [1.0] and [e.mel_z for e in out.electrodes] == [1.0]
|
||||
|
||||
|
||||
def test_a_count_baselines_range_is_its_own_for_the_minutes(tea_db):
|
||||
"""Pins down: a baseline with `percentiles` gives the metric's p5, median and p95 from the metric's minutes, and
|
||||
the metric row stores them, so a spike metric with a z has a reference range. Fails if count baselines lose their
|
||||
range (the patient summary then refuses the EEG: a metric with a z and no reference)."""
|
||||
import numpy as np
|
||||
|
||||
class Count:
|
||||
def deviation(self, values, ages_months, exposure=None):
|
||||
return np.array([0.0]), np.array([0.5])
|
||||
|
||||
def percentiles(self, ages_months, exposure):
|
||||
return np.array([[0.0, 0.1, 0.4]]) * 10 / exposure[0]
|
||||
|
||||
module = SimpleNamespace(baselines={"spike_rate_nrem": Count()})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
|
||||
|
||||
s = settings()
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {}, {}, 20.0) if x.code == "PICOS_PAROXISTICOS"
|
||||
else MetricValue(x.code, 1.0) for x in s.metrics))
|
||||
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
|
||||
spikes = next(r for r in out.metrics if r.met_codigo == "PICOS_PAROXISTICOS")
|
||||
assert (spikes.met_p5, spikes.met_mediana, spikes.met_p95) == (0.0, 0.05, 0.2)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""What this module covers: the spikes biomarker's baselines around the per-electrode and
|
||||
per-zone features: training from a feature table that predates them, and loading a baseline
|
||||
saved before they existed. Both implementations, modern and legacy.
|
||||
|
||||
Fixtures: `old_table`, a DataFrame with only the original seven study-wide spikes features and
|
||||
an age column, as a reference cohort measured before the density features existed; `full_table`,
|
||||
the same rows plus every current feature.
|
||||
"""
|
||||
import importlib
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
ORIGINAL = ("spike_rate_awake", "spike_rate_nrem", "spike_nrem_activation", "spike_focus_frac",
|
||||
"spike_laterality", "spike_frac_generalized", "spike_index_nrem")
|
||||
MODULES = (("tea.biomarkers.spikes.api", "Spikes"),
|
||||
("tea.legacy.biomarkers.spikes.api", "LegacySpikes"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def old_table():
|
||||
"""Twelve synthetic children with only the study-wide spikes features and their ages."""
|
||||
rng = np.random.default_rng(0)
|
||||
t = pd.DataFrame({f: rng.uniform(0.0, 2.0, size=12) for f in ORIGINAL})
|
||||
t["age_months"] = np.linspace(16.0, 36.0, 12)
|
||||
return t
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def full_table(old_table):
|
||||
"""`old_table` plus every per-electrode, per-zone and inherited feature the module has now."""
|
||||
rng = np.random.default_rng(1)
|
||||
t = old_table.copy()
|
||||
cls = getattr(importlib.import_module(MODULES[0][0]), MODULES[0][1])
|
||||
for f in cls.features:
|
||||
if f not in t.columns:
|
||||
t[f] = rng.uniform(0.0, 2.0, size=len(t))
|
||||
return t
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_training_skips_features_the_table_lacks(path, name, old_table, tmp_path):
|
||||
"""Pins down: training from a table without the new columns works, fits only the columns
|
||||
it has, and saving then loading that baseline keeps predicting those features only.
|
||||
|
||||
Fails if `train` starts requiring the new columns, or if save/load stops round-tripping
|
||||
a baseline that knows nothing about them.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
module = cls().train(old_table)
|
||||
out = module.predict(old_table)
|
||||
assert set(out.feature) == set(ORIGINAL)
|
||||
module.save(tmp_path)
|
||||
loaded = cls.load(tmp_path)
|
||||
assert set(loaded.predict(old_table).feature) == set(ORIGINAL)
|
||||
assert len(cls.features) > len(ORIGINAL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_a_baseline_saved_before_the_new_features_loads_and_predicts(path, name, old_table,
|
||||
full_table, tmp_path):
|
||||
"""Pins down: a baseline bundle written before the new features existed (no new
|
||||
parameters in params.json, none of the new features in baseline.json) loads into the
|
||||
current module and predicts; the new features simply have no baseline and are not
|
||||
evaluated.
|
||||
|
||||
Fails if load starts requiring the new parameters, if a saved baseline stops being
|
||||
readable after the feature list grows, or if predict evaluates a feature that has no
|
||||
fitted baseline.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
cls().train(old_table).save(tmp_path)
|
||||
params = json.loads((tmp_path / "params.json").read_text())
|
||||
for k in ("vent_s", "rechazar_transitorio", "herencia_s"):
|
||||
params.pop(k, None)
|
||||
(tmp_path / "params.json").write_text(json.dumps(params))
|
||||
loaded = cls.load(tmp_path)
|
||||
out = loaded.predict(full_table)
|
||||
assert set(out.feature) == set(ORIGINAL)
|
||||
assert len(out) == len(full_table) * len(ORIGINAL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_a_full_baseline_round_trips(path, name, full_table, tmp_path):
|
||||
"""Pins down: with every column present, train fits all features and save/load predicts
|
||||
the same deviations.
|
||||
|
||||
Fails if the per-electrode and per-zone features stop getting their own baselines when
|
||||
the training table has them.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
module = cls().train(full_table)
|
||||
before = module.predict(full_table)
|
||||
assert set(before.feature) == set(cls.features)
|
||||
module.save(tmp_path)
|
||||
after = cls.load(tmp_path).predict(full_table)
|
||||
pd.testing.assert_frame_equal(before, after)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""What this module covers: the count reference of spike candidates (`_baseline.CountRate` of both spikes modules)
|
||||
and how `Spikes` / `LegacySpikes` use it: the aggregate rate and its dispersion, a child's z from the tail of its
|
||||
own count in its own minutes, NaN without exposure, the per-electrode zone scale, and which features it serves.
|
||||
|
||||
Fixtures: `count_rate`, parametrized over the modern and legacy `CountRate` classes; `reference`, 200 invented
|
||||
children of 16 to 36 months with 5 to 15 clean NREM minutes and Poisson candidates at 0.02 per minute (most have
|
||||
none), as rates.
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from scipy import stats
|
||||
|
||||
from tea.biomarkers.spikes import _baseline as modern_baseline
|
||||
from tea.biomarkers.spikes import api as modern
|
||||
from tea.legacy.biomarkers.spikes import _baseline as legacy_baseline
|
||||
from tea.legacy.biomarkers.spikes import api as legacy
|
||||
|
||||
|
||||
@pytest.fixture(params=["modern", "legacy"])
|
||||
def count_rate(request):
|
||||
"""The implementation's `CountRate` class."""
|
||||
return {"modern": modern_baseline, "legacy": legacy_baseline}[request.param].CountRate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reference():
|
||||
"""(rates, ages, minutes) of 200 children with Poisson candidates at 0.02 per minute."""
|
||||
rng = np.random.default_rng(3)
|
||||
minutes = rng.uniform(5, 15, 200).round(2)
|
||||
counts = rng.poisson(0.02 * minutes)
|
||||
return counts / minutes, rng.uniform(16, 36, 200), minutes
|
||||
|
||||
|
||||
def test_the_reference_is_the_aggregate_rate_with_its_dispersion(count_rate):
|
||||
"""Pins down: the rate is all candidates over all minutes of the children within the ages (one child of 50
|
||||
months left out) and the dispersion is the research code's moments estimate, Poisson (inf) without excess.
|
||||
Fails if the rate becomes a mean of per-child rates, the age range stops filtering, or the moments change."""
|
||||
rates = np.array([0, 0.1, 0.2, 0])
|
||||
b = count_rate().fit(rates, np.array([20, 20, 30, 50.0]), exposure=np.array([10, 10, 20, 30.0]))
|
||||
assert b.state["rate"] == pytest.approx(5 / 40) and b.state["reference"] == 3 and b.state["events"] == 5
|
||||
n, mu = np.array([0, 1, 4]), 5 / 40 * np.array([10, 10, 20])
|
||||
excess = ((n - mu) ** 2 - n).sum()
|
||||
assert b.state["k"] == (pytest.approx((mu ** 2).sum() / excess) if excess > 0 else np.inf)
|
||||
flat = count_rate().fit(np.array([0.1, 0.1]), np.array([20, 20.0]), exposure=np.array([10, 10.0]))
|
||||
assert flat.state["k"] == np.inf
|
||||
|
||||
|
||||
def test_a_count_is_judged_in_its_own_minutes(count_rate, reference):
|
||||
"""Pins down: no candidates is a mildly negative z (never -inf), the same one candidate is rarer in fewer
|
||||
minutes, many candidates in few minutes are outside +1 with a large z, and z is the normal quantile of the mid-p
|
||||
tail. Fails if z stops using the child's minutes, the mid-p correction, or the 0.05 cut for `outside`."""
|
||||
b = count_rate().fit(*reference[:2], exposure=reference[2])
|
||||
outside, z = b.deviation(np.array([0.0, 1 / 5, 1 / 40, 8 / 5]), np.full(4, 24.0),
|
||||
exposure=np.array([10.0, 5.0, 40.0, 5.0]))
|
||||
assert -1 < z[0] < 0
|
||||
assert z[1] > z[2]
|
||||
assert outside.tolist() == [0.0, 0.0, 0.0, 1.0] and z[3] > 3
|
||||
mu = b.state["rate"] * 5.0
|
||||
tail = stats.poisson.sf(0, mu) if np.isinf(b.state["k"]) else stats.nbinom.sf(0, b.state["k"],
|
||||
b.state["k"] / (b.state["k"] + mu))
|
||||
at = (stats.poisson.pmf(1, mu) if np.isinf(b.state["k"])
|
||||
else stats.nbinom.pmf(1, b.state["k"], b.state["k"] / (b.state["k"] + mu)))
|
||||
assert z[1] == pytest.approx(stats.norm.ppf(1 - (tail - at / 2)))
|
||||
|
||||
|
||||
def test_no_exposure_value_age_or_reference_is_nan(count_rate, reference):
|
||||
"""Pins down: without minutes, with zero minutes, without a value, at an age outside the range, or against a
|
||||
reference with no minutes, z and outside are NaN, and a reference with no candidates at all clips z instead of
|
||||
reaching infinity. Fails if any of them reads as within the reference, or `inf` leaves the baseline."""
|
||||
b = count_rate().fit(*reference[:2], exposure=reference[2])
|
||||
outside, z = b.deviation(np.array([0.1, 0.1, np.nan, 0.1]), np.array([24, 24, 24, 60.0]),
|
||||
exposure=np.array([np.nan, 0.0, 10.0, 10.0]))
|
||||
assert np.isnan(z).all() and np.isnan(outside).all()
|
||||
assert np.isnan(b.deviation(np.array([0.1]), np.array([24.0]))[1]).all()
|
||||
empty = count_rate().fit(np.array([0.1]), np.array([24.0]), exposure=np.array([np.nan]))
|
||||
assert np.isnan(empty.deviation(np.array([0.1]), np.array([24.0]), exposure=np.array([10.0]))[1]).all()
|
||||
none = count_rate().fit(np.zeros(5), np.full(5, 24.0), exposure=np.full(5, 10.0))
|
||||
assert none.deviation(np.array([0.5]), np.array([24.0]), exposure=np.array([10.0]))[1][0] == count_rate.Z_MAX
|
||||
|
||||
|
||||
def test_the_reference_range_is_the_rates_expected_in_the_childs_minutes(count_rate, reference):
|
||||
"""Pins down: the p5, median and p95 of a count reference are the reference count's quantiles in the child's own
|
||||
minutes (times the zone scale) as rates, ordered, narrower in rate with more minutes, and NaN where z is NaN.
|
||||
Fails if the range stops using the child's minutes or the scale, or a child without minutes gets one (the
|
||||
patient summary shows it as the metric's reference)."""
|
||||
b = count_rate(scale=2.0).fit(*reference[:2], exposure=reference[2])
|
||||
out = b.percentiles(np.array([24.0, 24.0, 24.0, 60.0]), np.array([5.0, 400.0, np.nan, 10.0]))
|
||||
mu, k = b.state["rate"] * 400.0 * 2.0, b.state["k"]
|
||||
p95 = stats.poisson.ppf(0.95, mu) if np.isinf(k) else stats.nbinom.ppf(0.95, k, k / (k + mu))
|
||||
assert out[1, 2] == pytest.approx(p95 / 800.0)
|
||||
assert (np.diff(out[:2], axis=1) >= 0).all()
|
||||
assert out[1, 2] - out[1, 0] < out[0, 2] - out[0, 0] or out[0, 2] == 0
|
||||
assert np.isnan(out[2:]).all()
|
||||
|
||||
|
||||
def test_round_trip_and_scale(count_rate, reference):
|
||||
"""Pins down: `to_dict` / `from_dict` keep the state and the scale, and a per-electrode zone value is counted
|
||||
back through its electrodes (0.1 per minute per electrode over 3 electrodes in 10 minutes is 3 candidates).
|
||||
Fails if the scale is lost on save or not applied."""
|
||||
b = count_rate(scale=3.0).fit(*reference[:2], exposure=reference[2])
|
||||
again = count_rate.from_dict(b.to_dict())
|
||||
args = (np.array([0.1]), np.array([24.0]))
|
||||
assert again.deviation(*args, exposure=np.array([10.0]))[1] == pytest.approx(
|
||||
b.deviation(*args, exposure=np.array([10.0]))[1])
|
||||
assert again.scale == 3.0
|
||||
counts, exposure = b._counts(np.array([0.1]), np.array([10.0]))
|
||||
assert counts.tolist() == [3.0] and exposure.tolist() == [30.0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", [modern, legacy], ids=["modern", "legacy"])
|
||||
def test_the_rates_are_counted_against_their_minutes(module, reference):
|
||||
"""Pins down: every rate and density feature (overall, per electrode, per zone, unnormalised zone, inherited)
|
||||
has a count baseline whose exposure is the minutes of its own state and variant, the minutes themselves have no
|
||||
baseline, and the other spike features keep the configured one; a table without the minutes gives NaN for the
|
||||
counted features. Fails if a rate falls back to centile curves (collapsed at 0 in the reference) or reads
|
||||
another state's minutes."""
|
||||
spikes = (module.Spikes if module is modern else module.LegacySpikes)()
|
||||
assert set(module.EXPOSURE) == {f for f in module.FEATURES if f.startswith(
|
||||
("spike_rate_", "spike_density_", "spike_zone_", "spike_inherited_rate_", "spike_inherited_zone_"))}
|
||||
assert all(module.EXPOSURE[f].endswith(("_nrem" if "nrem" in f else "_awake")) for f in module.EXPOSURE)
|
||||
assert not set(module.MINUTES) & set(module.FEATURES)
|
||||
assert {spikes.baselines[f].name for f in module.EXPOSURE} == {"count_rate"}
|
||||
assert spikes.baselines["spike_laterality"].name == "curves"
|
||||
rates, ages, minutes = reference
|
||||
table = pd.DataFrame({"spike_rate_nrem": rates, "spike_minutes_nrem": minutes, "age_months": ages})
|
||||
spikes.train(table)
|
||||
out = spikes.predict(table.iloc[:3]).set_index("feature")
|
||||
assert out.loc["spike_rate_nrem", "z"].notna().all()
|
||||
blind = spikes.predict(table.iloc[:3].drop(columns="spike_minutes_nrem")).set_index("feature")
|
||||
assert blind.loc["spike_rate_nrem", "z"].isna().all()
|
||||
|
||||
|
||||
def test_legacy_and_modern_count_alike(reference):
|
||||
"""Pins down: both implementations' count baselines give the same reference and the same z. Fails if one copy
|
||||
of `CountRate` drifts from the other."""
|
||||
rates, ages, minutes = reference
|
||||
a = modern_baseline.CountRate().fit(rates, ages, exposure=minutes)
|
||||
b = legacy_baseline.CountRate().fit(rates, ages, exposure=minutes)
|
||||
assert a.state == b.state
|
||||
np.testing.assert_array_equal(a.deviation(rates, ages, exposure=minutes)[1],
|
||||
b.deviation(rates, ages, exposure=minutes)[1])
|
||||
@@ -0,0 +1,424 @@
|
||||
"""What this module covers: the spikes biomarker's density features: only useful candidates
|
||||
count (a field and no vertex/POSTS/ocular mark), the per-electrode and per-zone density per
|
||||
state, the 0-vs-NaN convention, and the inherited-state variant where a stretch without a
|
||||
clean-window state takes the nearest labeled window's state (30 s, conservative on
|
||||
transitions, never before the stable start). Both implementations, modern and legacy, are
|
||||
exercised and must agree.
|
||||
|
||||
Fixtures: synthetic in-memory studies built around 1/f noise with spike waveforms injected
|
||||
(`density_study`: 40 field spikes at C3 in sleep and 20 isolated artifacts on O2 in wake;
|
||||
`rejected_study`: all sleep, a 20 s stretch the QC left without a state, and 20 s annotated
|
||||
as crying; `edge_study`: a single clean sleep window at 10-14 s with one field spike at 13 s;
|
||||
`montage_study`: sleep windows at 2-6 s and 30-34 s with field spikes at 10 s, 24 s and 31 s)
|
||||
and a quiet all-wake study. Nothing comes from a patient.
|
||||
"""
|
||||
import contextlib
|
||||
import importlib
|
||||
import io
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
FS = 250.0
|
||||
DUR = 600.0
|
||||
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
C3_NEIGHBORS = ("F3", "T3", "Cz", "P3")
|
||||
DENSITY_MODULES = ("tea.biomarkers.spikes._density", "tea.legacy.biomarkers.spikes._density")
|
||||
|
||||
|
||||
def _fondo(n, n_ch, rng):
|
||||
"""1/f noise at ~20 µV per channel, as the director's spike-detector validation uses."""
|
||||
f = np.fft.rfftfreq(n, 1 / FS)
|
||||
f[0] = f[1]
|
||||
out = np.empty((n, n_ch))
|
||||
for j in range(n_ch):
|
||||
esp = (1.0 / f) * np.exp(1j * rng.uniform(0, 2 * np.pi, len(f)))
|
||||
y = np.fft.irfft(esp, n)
|
||||
out[:, j] = y / np.std(y) * 20.0
|
||||
return out
|
||||
|
||||
|
||||
def _punta(dur_ms=50.0, amp=120.0, post=60.0):
|
||||
"""A spike with its slow posterior wave, as the director's criterion 3 describes."""
|
||||
n = int(dur_ms * FS / 1000)
|
||||
t = np.linspace(-1, 1, max(n, 3))
|
||||
p = amp * (1 - t ** 2) ** 2
|
||||
m = int(0.30 * FS)
|
||||
s = -post * np.sin(np.pi * np.linspace(0, 1, m))
|
||||
return np.concatenate([p, s])
|
||||
|
||||
|
||||
def _add_spikes(x, rng, canal, spans, field):
|
||||
"""`spikes` per (start_s, end_s) span on `canal`, with the field on its 10-20 neighbors
|
||||
when `field`, as one simultaneous discharge."""
|
||||
idx = {c: i for i, c in enumerate(SCALP)}
|
||||
pun = _punta()
|
||||
for a, b, k in spans:
|
||||
for t in np.sort(rng.uniform(a, b, k)):
|
||||
i = int(t * FS)
|
||||
x[i:i + len(pun), idx[canal]] += pun
|
||||
if field:
|
||||
for v in C3_NEIGHBORS:
|
||||
x[i:i + len(pun), idx[v]] += 0.6 * pun
|
||||
return x
|
||||
|
||||
|
||||
def _study(x, labels, annotations=()):
|
||||
"""The contracts' Study around an in-memory (samples, channels) µV array: one variant,
|
||||
4 s windows at a 2 s step labeled by sleep_state, and the annotated states as
|
||||
annotation_mask events (the same annotations ride the variant for the legacy adapter,
|
||||
whose director code translates them itself)."""
|
||||
import mne
|
||||
|
||||
from tea.contracts import Labels, Preprocessed, Study
|
||||
from tea.processes.annotation_mask.api import state_of
|
||||
|
||||
n = x.shape[0]
|
||||
raw = mne.io.RawArray(x.T * 1e-6, mne.create_info(SCALP[: x.shape[1]], FS, ch_types="eeg"),
|
||||
verbose="error")
|
||||
anns = [(float(t0), float(d), e) for t0, d, e in annotations]
|
||||
if anns:
|
||||
onsets, durs, descs = zip(*anns)
|
||||
raw.set_annotations(mne.Annotations(list(onsets), list(durs), list(descs)))
|
||||
starts = np.arange(0.0, n / FS - 4.0 + 1e-9, 2.0)
|
||||
windows = pd.DataFrame({"start_s": starts, "end_s": starts + 4.0, "clean": True, "gap": False})
|
||||
prep = Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
|
||||
plan={"name": "synthetic"}, plan_hash="synthetic")
|
||||
sleep_state = Labels("sleep_state",
|
||||
per_window=pd.Series(labels, index=windows.index, name="vigilancia"))
|
||||
events = pd.DataFrame([{"onset_s": t0, "duration_s": d, "estado": state_of(e)}
|
||||
for t0, d, e in anns if state_of(e)],
|
||||
columns=["onset_s", "duration_s", "estado"])
|
||||
annotation_mask = Labels("annotation_mask", events=events)
|
||||
return Study(prep, {"sleep_state": sleep_state, "annotation_mask": annotation_mask})
|
||||
|
||||
|
||||
def _labels_for(edits):
|
||||
"""A 600 s window at 2 s step labeled 'sueno' everywhere, with `edits` {start_s: label}."""
|
||||
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sueno", dtype=object)
|
||||
for t0, e in edits.items():
|
||||
labels[starts == float(t0)] = e
|
||||
return list(labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def density_study():
|
||||
"""Half sleep, half wake: 40 spikes with field at C3 in the sleep half, 20 isolated
|
||||
artifacts on O2 in the wake half (no field: they must not count as useful)."""
|
||||
rng = np.random.default_rng(5)
|
||||
x = _fondo(int(DUR * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(200.0, 290.0, 40)], field=True)
|
||||
solo = _punta(dur_ms=50.0, amp=150.0, post=0.0)
|
||||
idx = {c: i for i, c in enumerate(SCALP)}
|
||||
for t in np.sort(rng.uniform(310.0, 590.0, 20)):
|
||||
i = int(t * FS)
|
||||
x[i:i + len(solo), idx["O2"]] += 1.4 * solo
|
||||
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
|
||||
labels = np.where(starts < 300.0, "sueno", "vigilia")
|
||||
return _study(x, labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rejected_study():
|
||||
"""All sleep: 6 spikes in a 20 s stretch the QC left without a state (150-170 s), 6 in
|
||||
clean sleep, 6 in a stretch annotated as crying (400-420 s)."""
|
||||
rng = np.random.default_rng(8)
|
||||
x = _fondo(int(DUR * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(152.0, 168.0, 6), (200.0, 216.0, 6), (402.0, 418.0, 6)],
|
||||
field=True)
|
||||
labels = _labels_for({t0: "sin_estado" for t0 in range(148, 170, 2)})
|
||||
return _study(x, labels, annotations=((400.0, 20.0, "Llanto"),))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wake_study():
|
||||
"""Two quiet minutes of wake: no spike, no sleep."""
|
||||
rng = np.random.default_rng(2)
|
||||
labels = ["vigilia"] * len(np.arange(0.0, 120.0 - 4.0 + 1e-9, 2.0))
|
||||
return _study(_fondo(int(120 * FS), len(SCALP), rng), labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edge_study():
|
||||
"""One minute with a single clean sleep window at 10-14 s and one field spike at 13 s:
|
||||
inside the 4 s window the state was classified on, beyond the 2 s grid step."""
|
||||
rng = np.random.default_rng(11)
|
||||
x = _fondo(int(60 * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(12.9, 13.1, 1)], field=True)
|
||||
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sin_estado", dtype=object)
|
||||
labels[starts == 10.0] = "sueno"
|
||||
return _study(x, list(labels))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def montage_study():
|
||||
"""One minute with clean sleep windows at 2-6 s and 30-34 s and field spikes at 10 s
|
||||
(unlabeled gap before the stable start), 24 s (unlabeled gap after it) and 31 s
|
||||
(inside the second window)."""
|
||||
rng = np.random.default_rng(13)
|
||||
x = _fondo(int(60 * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(9.9, 10.1, 1), (23.9, 24.1, 1), (30.9, 31.1, 1)],
|
||||
field=True)
|
||||
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sin_estado", dtype=object)
|
||||
labels[starts == 2.0] = "sueno"
|
||||
labels[starts == 30.0] = "sueno"
|
||||
return _study(x, list(labels))
|
||||
|
||||
|
||||
def _measure(impl, study, **kwargs):
|
||||
path = "tea.legacy.biomarkers.spikes.api" if impl == "legacy" else "tea.biomarkers.spikes.api"
|
||||
cls = getattr(importlib.import_module(path), "LegacySpikes" if impl == "legacy" else "Spikes")
|
||||
return cls(**kwargs).measure(study)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_density(density_study):
|
||||
"""The density study measured by both implementations, {'modern': {...}, 'legacy': {...}}."""
|
||||
return {impl: _measure(impl, density_study) for impl in ("modern", "legacy")}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_rejected(rejected_study):
|
||||
"""The rejected-stretch study measured by both implementations."""
|
||||
return {impl: _measure(impl, rejected_study) for impl in ("modern", "legacy")}
|
||||
|
||||
|
||||
def test_useful_candidates_map_to_c3_and_the_central_zone(measured_density):
|
||||
"""Pins down: with field spikes at C3 in sleep, the NREM density lands on C3 and the
|
||||
central zone (per electrode, so it divides by the zone's 3 electrodes), every other
|
||||
electrode is exactly 0, and the isolated wake artifacts on O2 count nowhere.
|
||||
|
||||
Fails if candidates without a field start counting, if canal_max stops being the
|
||||
electrode a discharge is attributed to, or if the zone density stops being normalised
|
||||
per electrode.
|
||||
"""
|
||||
m = measured_density["modern"]
|
||||
assert m["spike_rate_nrem"] > 0
|
||||
# the density divides by the unrounded minutes (the por_canal convention) and the
|
||||
# rate by the two-decimal minutes (the indicadores convention), so they can differ
|
||||
# by that rounding
|
||||
assert m["spike_density_nrem_C3"] == pytest.approx(m["spike_rate_nrem"], rel=0.01)
|
||||
assert m["spike_density_nrem_C3"] > 10 * max(m["spike_rate_awake"], 0.01)
|
||||
for e in SCALP:
|
||||
esperado = m["spike_rate_nrem"] if e == "C3" else 0.0
|
||||
assert m[f"spike_density_nrem_{e}"] == pytest.approx(esperado, rel=0.01), e
|
||||
assert m["spike_zone_nrem_central"] == pytest.approx(m["spike_rate_nrem"] / 3, rel=0.01)
|
||||
assert m["spike_zone_nrem_frontal_izq"] == 0.0
|
||||
assert m["spike_zone_nrem_occipital"] == 0.0
|
||||
assert m["spike_density_awake_O2"] == 0.0
|
||||
|
||||
|
||||
def test_a_quiet_present_electrode_is_zero_and_a_state_without_minutes_is_nan(wake_study):
|
||||
"""Pins down: an electrode present with no candidates reads 0, never NaN, while a state
|
||||
with no clean minutes (no sleep in an all-wake study) makes every feature of that state
|
||||
NaN, inherited ones included.
|
||||
|
||||
Fails if the densities stop distinguishing 'no candidates' (0) from 'no denominator'
|
||||
(NaN), or if the inherited variant stops honouring the same convention.
|
||||
"""
|
||||
m = _measure("modern", wake_study)
|
||||
for e in SCALP:
|
||||
assert m[f"spike_density_nrem_{e}"] != m[f"spike_density_nrem_{e}"] # NaN
|
||||
assert m[f"spike_density_awake_{e}"] == 0.0
|
||||
for z in ("central", "occipital", "temporal_der"):
|
||||
assert m[f"spike_zone_nrem_{z}"] != m[f"spike_zone_nrem_{z}"]
|
||||
assert m[f"spike_zone_awake_{z}"] == 0.0
|
||||
assert m[f"spike_inherited_zone_nrem_{z}"] != m[f"spike_inherited_zone_nrem_{z}"]
|
||||
assert m["spike_inherited_rate_nrem"] != m["spike_inherited_rate_nrem"]
|
||||
assert m["spike_inherited_rate_awake"] == pytest.approx(0.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_absent_electrode_and_zone_are_nan(module):
|
||||
"""Pins down: an electrode missing from the montage has a NaN density (it cannot be
|
||||
measured), and a zone with no present electrode is NaN too.
|
||||
|
||||
Fails if absent electrodes start reading as a measured 0.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
ev = pd.DataFrame({"canal_max": ["C3", "C3"], "fase": ["sueno", "sueno"],
|
||||
"vertice": [False, False], "posts": [False, False],
|
||||
"ocular": [False, False], "vecinos": [2, 2]})
|
||||
out = mod.electrode_densities(ev, {"sueno": 2.0}, electrodes=("C3", "T6"), present=("C3",))
|
||||
assert out["spike_density_nrem_C3"] == pytest.approx(1.0)
|
||||
assert out["spike_density_nrem_T6"] != out["spike_density_nrem_T6"]
|
||||
zonas = mod.zone_densities(ev, {"sueno": 2.0}, present=("C3",))
|
||||
assert zonas["spike_zone_nrem_central"] == pytest.approx(1.0)
|
||||
assert zonas["spike_zone_nrem_temporal_der"] != zonas["spike_zone_nrem_temporal_der"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_states_inherit_from_the_nearest_labeled_window(module):
|
||||
"""Pins down (port of the research repo's inheritance test): a stretch the QC left
|
||||
unlabeled takes the nearest clean window's state up to 30 s away; farther, or before
|
||||
the first labeled window (or `t_min`), it stays without a state; intervals never
|
||||
overlap.
|
||||
|
||||
Fails if the 30 s reach, the nearest-window rule or the `t_min` floor stop being
|
||||
applied.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
t0 = np.r_[np.arange(20, 40, 2.0), np.arange(60, 98, 2.0), np.arange(200, 240, 2.0)]
|
||||
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": "sueno"})
|
||||
v = mod.inherit_states(labeled, 300.0, inherit_s=30.0, t_min=15.0)
|
||||
|
||||
def etq(t):
|
||||
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
|
||||
return (v.etiqueta[m].iloc[0], bool(v.heredado[m].iloc[0])) if m.any() else (None, None)
|
||||
|
||||
assert etq(30) == ("sueno", False) # clean window
|
||||
assert etq(50) == ("sueno", True) # 20 s gap between clean windows
|
||||
assert etq(120) == ("sueno", True) # 20 s after the last clean window
|
||||
assert etq(150) == (None, None) # more than 30 s away from both
|
||||
assert etq(18) == (None, None) # before the first clean window (t_min 15)
|
||||
assert not (v.t_ini_s.to_numpy()[1:] < v.t_fin_s.to_numpy()[:-1]).any()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_inheritance_is_conservative_across_state_transitions(module):
|
||||
"""Pins down (port of the research repo's conservative-transition test): an unlabeled
|
||||
stretch between two different states stays 'transicion' and counts in neither; between
|
||||
two windows of the same state it inherits that state.
|
||||
|
||||
Fails if the transition rule starts assigning one of the two states.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
t0 = np.r_[np.arange(0, 40, 2.0), np.arange(60, 100, 2.0), np.arange(110, 150, 2.0)]
|
||||
e = np.r_[["somnolencia"] * 20, ["sueno"] * 20, ["sueno"] * 20]
|
||||
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": e})
|
||||
v = mod.inherit_states(labeled, 160.0)
|
||||
|
||||
def etq(t):
|
||||
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
|
||||
return v.etiqueta[m].iloc[0] if m.any() else None
|
||||
|
||||
assert etq(45) == "transicion" and etq(58) == "transicion"
|
||||
assert etq(105) == "sueno"
|
||||
assert etq(30) == "somnolencia" and etq(70) == "sueno"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_candidate_category_marks_isolated_and_marked(module):
|
||||
"""Pins down: a candidate is 'util' only with a field and no mark; the director's mark
|
||||
order (posts, vertice, ocular) wins over 'aislado'.
|
||||
|
||||
Fails if the category rule starts counting marked or fieldless candidates as useful.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
ev = pd.DataFrame({"vecinos": [2, 0, 3, 1, 0],
|
||||
"posts": [False, False, True, False, False],
|
||||
"vertice": [False, False, False, True, False],
|
||||
"ocular": [False, False, False, False, True]})
|
||||
assert list(mod.candidate_category(ev)) == ["util", "aislado", "posts", "vertice", "ocular"]
|
||||
|
||||
|
||||
def test_rejected_stretch_counts_only_when_inherited(measured_rejected):
|
||||
"""Pins down (port of the research repo's rejected-window test): spikes in a stretch
|
||||
the QC left without a state count in NREM only through inheritance — the direct rate
|
||||
sees only the clean-stretch spikes — and spikes in a stretch annotated as crying count
|
||||
nowhere, because the detector's own gate rejects those windows.
|
||||
|
||||
Fails if the inherited variant starts using the direct states, or if annotated states
|
||||
stop gating the detector.
|
||||
"""
|
||||
for m in measured_rejected.values():
|
||||
assert 0 < m["spike_rate_nrem"] < m["spike_inherited_rate_nrem"]
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(2 * m["spike_rate_nrem"], rel=0.2)
|
||||
assert m["spike_inherited_zone_nrem_central"] > m["spike_zone_nrem_central"]
|
||||
assert m["spike_inherited_rate_awake"] != m["spike_inherited_rate_awake"] # no wake
|
||||
|
||||
|
||||
def test_without_inheritance_the_inherited_variant_matches_the_direct(rejected_study):
|
||||
"""Pins down: with the inheritance reach at 0 the inherited variant reduces to the
|
||||
direct one (same candidates, same minutes).
|
||||
|
||||
Fails if the inherited run stops deriving its states from the inheritance intervals.
|
||||
"""
|
||||
m = _measure("modern", rejected_study, herencia_s=0.0)
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(m["spike_rate_nrem"], rel=1e-9)
|
||||
assert m["spike_inherited_zone_nrem_central"] == pytest.approx(m["spike_zone_nrem_central"],
|
||||
rel=1e-9)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_candidate_inside_the_classified_window_counts_as_direct(impl, edge_study):
|
||||
"""Pins down (the reviewer's 13 s scenario): a candidate at 13 s with a single clean
|
||||
4 s sleep window starting at 10 s lies inside the window's own state, so the direct
|
||||
NREM rate counts it (1 spike over the 4 clean gate minutes of [10, 14)); the inherited
|
||||
run labels 13 s as direct too and only stretches [14, 44) inherit.
|
||||
|
||||
Fails if `_vig` shortens the state windows to the 2 s grid step again: the spike would
|
||||
fall outside every window, the direct rate would read 0 and only the inherited run
|
||||
would count it.
|
||||
"""
|
||||
m = _measure(impl, edge_study)
|
||||
assert m["spike_rate_nrem"] == pytest.approx(14.286, abs=0.001) # 1 / 0.07 rounded minutes
|
||||
assert m["spike_density_nrem_C3"] == pytest.approx(15.0, abs=0.01) # 1 over 4/60 unrounded
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(1.754, abs=0.001)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_no_inherited_state_before_the_stable_start(impl, montage_study):
|
||||
"""Pins down (the reviewer's stable-start scenario): with the stable start at 20 s,
|
||||
the spike at 10 s — in the gap after an early labeled window but before the stable
|
||||
start — gets no state anywhere, while the spike at 24 s inherits and the spike at
|
||||
31 s is direct. The direct run sees only 31 s (0.13 clean sleep minutes, rate 7.692);
|
||||
the inherited run counts 24 s and 31 s but not 10 s (0.73 minutes, rate 2.74). With
|
||||
the default stable start of 0 the 10 s spike inherits as well (0.97 minutes, 3.093).
|
||||
|
||||
Fails if `measure` stops passing the stable start to the inheritance (the 10 s spike
|
||||
would count in the inherited rate) or if the early window's reach is clamped wrongly.
|
||||
"""
|
||||
m = _measure(impl, montage_study, stable_start_s=20.0)
|
||||
assert m["spike_rate_nrem"] == pytest.approx(7.692, abs=0.001)
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(2.74, abs=0.001)
|
||||
sin_montaje = _measure(impl, montage_study)
|
||||
assert sin_montaje["spike_inherited_rate_nrem"] == pytest.approx(3.093, abs=0.001)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_crying_annotation_rejects_gate_windows(impl, rejected_study):
|
||||
"""Pins down (port of the research repo's annotated-window test): the detector's 2 s
|
||||
gate rejects the windows of the crying stretch and nothing else.
|
||||
|
||||
Fails if annotated states stop reaching the quality gate (the crying spikes would then
|
||||
count as sleep).
|
||||
"""
|
||||
if impl == "modern":
|
||||
from tea.biomarkers.spikes import _density
|
||||
from tea.biomarkers.spikes.api import Spikes
|
||||
|
||||
module = Spikes()
|
||||
est, canales = module._prepare(rejected_study)
|
||||
gate = _density.gate_windows(est, canales, module.vent_s, module.rechazar_transitorio)
|
||||
else:
|
||||
from tea.legacy.biomarkers.spikes import _adapter, _density
|
||||
from tea.legacy.biomarkers.spikes._director import eeg_io
|
||||
|
||||
module = _density
|
||||
with _adapter.estudio(rejected_study.prep, "hp05_prom", eeg_io) as est, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
gate = _density.gate_windows(est, eeg_io, 2.0, False)
|
||||
lloro = gate.motivo.str.contains("estado llanto", regex=False)
|
||||
assert lloro.sum() >= 8 and not gate[lloro].apta.any()
|
||||
assert gate[~lloro].apta.all()
|
||||
|
||||
|
||||
def test_legacy_and_modern_agree_on_every_feature(measured_density, measured_rejected):
|
||||
"""Pins down: both implementations expose the same 79 features with the same values on
|
||||
the same study, old and new alike.
|
||||
|
||||
Fails if one implementation's port of the detector, the densities or the inheritance
|
||||
drifts from the other's.
|
||||
"""
|
||||
for nombre, medido in (("density", measured_density), ("rejected", measured_rejected)):
|
||||
moderno, legado = medido["modern"], medido["legacy"]
|
||||
assert set(moderno) == set(legado)
|
||||
for f, v in moderno.items():
|
||||
otro = legado[f]
|
||||
iguales = v == otro or (np.isnan(v) and np.isnan(otro))
|
||||
assert iguales or v == pytest.approx(otro, rel=1e-6, abs=1e-12), (nombre, f, v, otro)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Spindle detection and summaries, plus loading partial spindle baselines.
|
||||
|
||||
Fixtures: `sleep_recording` supplies synthetic EEG with short, long or sustained
|
||||
sigma bursts. `tmp_path` holds a saved spindle baseline.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tea.biomarkers.spindles.api import Spindles
|
||||
from tea.legacy.biomarkers.spindles.api import LegacySpindles
|
||||
from tea.legacy.processes.spindle_detection.api import LegacySpindleDetection
|
||||
from tea.processes.spindle_detection.api import SpindleDetection
|
||||
|
||||
CHANNELS = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
FS = 250
|
||||
DENSITY = "spindle_density_per_min_channel"
|
||||
NO_LONG = "spindle_density_per_min_channel_no_long"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sleep_recording():
|
||||
"""Make 600 s of sleep on the 10-20 montage with selectable sigma bursts."""
|
||||
|
||||
def make(mode):
|
||||
rng = np.random.default_rng(1)
|
||||
duration = 600
|
||||
freq = np.fft.rfftfreq(duration * FS, 1 / FS)
|
||||
freq[0] = freq[1]
|
||||
voltages = np.empty((duration * FS, len(CHANNELS)))
|
||||
for i in range(len(CHANNELS)):
|
||||
spectrum = np.exp(1j * rng.uniform(0, 2 * np.pi, len(freq))) / freq
|
||||
background = np.fft.irfft(spectrum)
|
||||
voltages[:, i] = background * (20 / background.std())
|
||||
|
||||
def inject(start, length, hz, amplitude, gains):
|
||||
t = np.arange(int(length * FS)) / FS
|
||||
envelope = np.hanning(len(t)) if length < 2 else np.clip(np.minimum(t, length - t) / 0.5, 0, 1)
|
||||
wave = amplitude * envelope * np.sin(2 * np.pi * hz * t)
|
||||
for channel, gain in gains.items():
|
||||
a = int(start * FS)
|
||||
voltages[a:a + len(t), CHANNELS.index(channel)] += gain * wave
|
||||
|
||||
short = dict.fromkeys(("F3", "F4", "C3", "C4", "Cz"), 1.0) | {"Fz": 0.8, "P3": 0.7, "P4": 0.7}
|
||||
starts = np.arange(5, duration - 10, 9.0)
|
||||
if mode != "empty":
|
||||
for start in starts + rng.uniform(-1, 1, len(starts)):
|
||||
if mode == "long" and (200 < start < 240 or 400 < start < 410):
|
||||
continue
|
||||
inject(start, 1, 12.5, 50, short)
|
||||
if mode == "long":
|
||||
inject(205, 25, 13, 60, {"C3": 1, "C4": 1, "Cz": 1, "F3": 0.8, "F4": 0.8})
|
||||
inject(402, 5, 12, 60, {"Fz": 1, "F3": 0.6, "F4": 0.6})
|
||||
if mode == "continuous":
|
||||
inject(0, duration * 0.6, 13, 60, short)
|
||||
if mode == "empty":
|
||||
voltages.fill(0)
|
||||
|
||||
class Raw:
|
||||
n_times = len(voltages)
|
||||
ch_names = CHANNELS
|
||||
info = {"sfreq": FS}
|
||||
annotations = ()
|
||||
|
||||
def get_channel_types(self):
|
||||
return ["eeg"] * len(self.ch_names)
|
||||
|
||||
def get_data(self, picks):
|
||||
return voltages[:, [self.ch_names.index(name) for name in picks]].T / 1e6
|
||||
|
||||
windows = pd.DataFrame({"start_s": np.arange(0, duration, 4.0)})
|
||||
return SimpleNamespace(variant=lambda _: Raw(), windows=windows)
|
||||
|
||||
return make
|
||||
|
||||
|
||||
IMPLEMENTATIONS = ((SpindleDetection, Spindles), (LegacySpindleDetection, LegacySpindles))
|
||||
|
||||
|
||||
def measure(prep, implementation, phase="N2"):
|
||||
detector, biomarker = implementation
|
||||
labels = {"sleep_state": SimpleNamespace(per_window=["sueno"] * len(prep.windows)),
|
||||
"slow_wave_staging": SimpleNamespace(per_window=["N2"] * len(prep.windows))}
|
||||
study = SimpleNamespace(prep=prep, label=labels.__getitem__)
|
||||
labels["spindle_detection"] = detector(phase=phase).predict(study)
|
||||
return biomarker().measure(study), labels["spindle_detection"].events
|
||||
|
||||
|
||||
def test_long_runs_split_events_and_density(sleep_recording):
|
||||
"""Pin long/extreme counts and the existing density. Fails if split events disappear from the old density."""
|
||||
prep = sleep_recording("long")
|
||||
outputs = []
|
||||
for implementation in IMPLEMENTATIONS:
|
||||
result, events = measure(prep, implementation)
|
||||
assert ((events.channel == "C3") & events.onset_s.between(204, 231)).sum() >= 6
|
||||
assert result["spindle_n_long_runs"] == 6
|
||||
assert result["spindle_n_extreme"] == 5
|
||||
assert 24 <= result["spindle_max_run_s"] <= 27
|
||||
assert result[DENSITY] == round(len(events) / 10 / 13, 3)
|
||||
assert result[NO_LONG] < result[DENSITY]
|
||||
outputs.append(result)
|
||||
for feature in ("spindle_n_long_runs", "spindle_n_extreme", "spindle_max_run_s",
|
||||
"spindle_sigma_occupancy_median", "spindle_sigma_occupancy_max", NO_LONG):
|
||||
assert outputs[0][feature] == pytest.approx(outputs[1][feature], abs=0.01)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_short_bursts_and_sustained_sigma(sleep_recording, implementation):
|
||||
"""Pin zero long runs with short spindles and occupancy with sustained sigma. Fails if occupancy uses event thresholds."""
|
||||
short, _ = measure(sleep_recording("short"), implementation)
|
||||
sustained, _ = measure(sleep_recording("continuous"), implementation)
|
||||
assert short["spindle_n_long_runs"] == short["spindle_n_extreme"] == 0
|
||||
assert short[NO_LONG] == short[DENSITY]
|
||||
assert short["spindle_sigma_occupancy_max"] < 0.45
|
||||
assert sustained["spindle_sigma_occupancy_max"] >= 0.55
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_spindle_density_by_electrode_and_zone(sleep_recording, implementation):
|
||||
"""Pin event counts per sleep minute and per searched electrode, NaN on a channel the detector never searches
|
||||
(O1, and so the occipital zone). Fails if empty searched channels are omitted, an unsearched channel reports a
|
||||
density, or a phase leaks."""
|
||||
prep = sleep_recording("short")
|
||||
result, events = measure(prep, implementation)
|
||||
counts = events.channel.value_counts()
|
||||
assert counts["C3"] > 0 and counts["Fz"] > 0
|
||||
assert result["spindle_electrode_C3"] == counts["C3"] / 10
|
||||
assert np.isnan(result["spindle_electrode_O1"])
|
||||
assert np.isnan(result["spindle_zone_occipital"])
|
||||
assert result["spindle_zone_central"] == counts[["C3", "Cz", "C4"]].sum() / 30
|
||||
other_phase, _ = measure(prep, implementation, phase="N3")
|
||||
assert all(np.isnan(value) for value in other_phase.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_sleep_without_spindles_is_nan(sleep_recording, implementation):
|
||||
"""Pin missing outputs on event-free sleep. Fails if any feature reports a value without a detected spindle."""
|
||||
result, events = measure(sleep_recording("empty"), implementation)
|
||||
assert events.empty and events.attrs["searched"]
|
||||
assert all(np.isnan(value) for value in result.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("biomarker", (Spindles, LegacySpindles))
|
||||
def test_spindle_baselines_load_without_new_features(tmp_path, biomarker):
|
||||
"""Pin save/load of a single-feature baseline. Fails if train or predict requires all current feature columns."""
|
||||
table = pd.DataFrame({"age_months": [12, 24, 36], DENSITY: [0.1, 0.2, 0.3]})
|
||||
module = biomarker(baseline_params={"n_min": 1}).train(table)
|
||||
module.save(tmp_path)
|
||||
loaded = biomarker.load(tmp_path)
|
||||
assert list(loaded.baselines) == [DENSITY]
|
||||
assert loaded.predict(table).feature.tolist() == [DENSITY] * len(table)
|
||||
Reference in New Issue
Block a user