Files
models/tests/tea/test_spikes_density.py

425 lines
20 KiB
Python

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