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