EEG: one NREM spindle metric, nearest-window spike states and awake rate, gate and metric reasons, zone rates over present electrodes, stable start and mains notch, Spanish checks, EDF header

This commit is contained in:
Roberto Treviño
2026-12-06 03:42:11 -06:00
parent 20a92a01e6
commit e2487062ae
12 changed files with 490 additions and 336 deletions
+31 -28
View File
@@ -1,10 +1,13 @@
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics. """One EEG, from its EDF bytes: whether it can be analysed (and why not) and its four metrics.
analysis = analyze(edf_bytes, birth_date) analysis = analyze(edf_bytes, birth_date)
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are (`preprocess.py`), its windows get a state (`sleep.py`), and the metrics are measured
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`). (`biomarkers.py`) along with the features the age baselines score (`curves.py`), why a metric
was not measured (`core.tea.reasons.METRIC_REASONS`) and the minutes the spike gate left out
(`REJECTED_MINUTES`, with the stable start as `start_s`); an EEG not valid has every metric,
none measured, for `invalid-eeg`.
The age is the EDF header's (recording start minus birth date) when it has both dates, else the The age is the EDF header's (recording start minus birth date) when it has both dates, else the
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
@@ -17,6 +20,7 @@ import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date
from core.tea.reasons import METRIC_REASONS, REJECTED_MINUTES
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
DAYS_PER_MONTH = 30.4375 DAYS_PER_MONTH = 30.4375
@@ -35,6 +39,7 @@ class Metric:
class Analysis: class Analysis:
valid: bool | None valid: bool | None
level: str level: str
reasons: list[str] # why it is not valid (checks.Validation.reasons)
age_months: float | None age_months: float | None
clean_fraction: float | None clean_fraction: float | None
bad_channels: int | None bad_channels: int | None
@@ -43,9 +48,8 @@ class Analysis:
line_noise_db: float | None line_noise_db: float | None
sleep: bool | None sleep: bool | None
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes, metrics: list[Metric] # biomarkers.CODES
# anteroposterior_gradient features: dict[str, dict] # by scenario (`curves.SCENARIOS`), None missing; and the reasons
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
error: str | None error: str | None
@@ -53,6 +57,16 @@ def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None return float(v) if v is not None and math.isfinite(v) else None
def _result(out: dict, measured: biomarkers.Measured, **fields) -> Analysis:
metrics = [Metric(code, _number(value), {k: _number(v) for k, v in electrodes.items()},
{k: _number(v) for k, v in zones.items()})
for code, (value, electrodes, zones) in measured.metrics.items()] # fmt: skip
features = {s: {k: _number(v) for k, v in f.items()} for s, f in measured.features.items()}
features[METRIC_REASONS] = measured.reasons
features[REJECTED_MINUTES] = {k: _number(v) for k, v in measured.rejected.items()}
return Analysis(**out | dict(metrics=metrics, features=features) | fields)
def _error(exc: Exception) -> str: def _error(exc: Exception) -> str:
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300] message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}" return f"{type(exc).__name__}: {message}"
@@ -64,12 +78,14 @@ def analyze(
*, *,
age_months: float | None = None, age_months: float | None = None,
mains_hz: float = MAINS_HZ, mains_hz: float = MAINS_HZ,
keep_flat: bool = False,
) -> Analysis: ) -> Analysis:
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency """`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`).""" of the recording's mains; `keep_flat` keeps a reference study's one flat electrode."""
out = dict( out = dict(
valid=None, valid=None,
level=checks.NOT_ANALYZABLE, level=checks.NOT_ANALYZABLE,
reasons=[],
age_months=age_months, age_months=age_months,
clean_fraction=None, clean_fraction=None,
bad_channels=None, bad_channels=None,
@@ -87,9 +103,8 @@ def analyze(
rec = read.read(edf) rec = read.read(edf)
except read.FileNotValid as exc: except read.FileNotValid as exc:
verdict = checks.file_not_valid(str(exc)) verdict = checks.file_not_valid(str(exc))
return Analysis( return _result(out, biomarkers.invalid(), valid=False, reasons=verdict.reasons,
**out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks) clean_fraction=0.0, bad_channels=0, checks=verdict.checks) # fmt: skip
)
if age_months is None: if age_months is None:
header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH) header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH)
given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH) given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH)
@@ -100,6 +115,7 @@ def analyze(
out.update( out.update(
valid=verdict.valid, valid=verdict.valid,
level=verdict.level, level=verdict.level,
reasons=verdict.reasons,
clean_fraction=verdict.clean_pct / 100, clean_fraction=verdict.clean_pct / 100,
bad_channels=len(verdict.bad), bad_channels=len(verdict.bad),
channels=len(rec.names) or None, channels=len(rec.names) or None,
@@ -108,25 +124,12 @@ def analyze(
checks=verdict.checks, checks=verdict.checks,
) )
if not verdict.valid: if not verdict.valid:
return Analysis(**out) return _result(out, biomarkers.invalid())
prep = preprocess.prepare(rec, verdict.bad) prep = preprocess.prepare(rec, verdict.bad, mains_hz, keep_flat=keep_flat)
notes = sleep.note_intervals(prep.annotations, prep.duration_s) notes = sleep.note_intervals(prep.annotations, prep.duration_s)
states = sleep.states(prep, notes, age) states = sleep.states(prep, notes, age)
staged = sleep.stages(prep, states) measured = biomarkers.measure(prep, states, notes)
metrics, features = biomarkers.measure(prep, states, staged, notes) measured.rejected["start_s"] = preprocess.stable_start(rec)
out.update( return _result(out, measured, sleep=bool((states == "sleep").any()))
sleep=bool((states == "sleep").any()),
metrics=[
Metric(
code,
_number(value),
{k: _number(v) for k, v in electrodes.items()},
{k: _number(v) for k, v in zones.items()},
)
for code, (value, electrodes, zones) in metrics.items()
],
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
)
return Analysis(**out)
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch
return Analysis(**out | dict(error=_error(exc))) return Analysis(**out | dict(error=_error(exc)))
+78 -55
View File
@@ -1,5 +1,7 @@
"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features """The four metrics of an EEG, their per-electrode and per-zone values, the features each age
each age baseline scores (by scenario, `curves.SCENARIOS`). baseline scores (by scenario, `curves.SCENARIOS`) and why a metric was not measured (its reason:
few-wake-windows, no-dominant-peak, no-sleep, few-electrodes, no-spindles; invalid-eeg for every
metric of an EEG not valid).
Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior
electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more. electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more.
@@ -8,10 +10,13 @@ Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-
each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the
electrode's front-back position (6 electrodes at least). electrode's front-back position (6 electrodes at least).
Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode. Spindles in NREM sleep (`spindles.py`): density, per zone, and enhancement per electrode, noting
Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes. a posterior rhythm near sigma. Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode
and per zone, against the minutes; awake, and the minutes the gate left out by reason.
""" """
from dataclasses import dataclass, replace
import numpy as np import numpy as np
from scipy.fft import rfft, rfftfreq from scipy.fft import rfft, rfftfreq
from scipy.signal.windows import hann from scipy.signal.windows import hann
@@ -22,49 +27,58 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
from models.tea.eeg.sleep import POSTERIOR from models.tea.eeg.sleep import POSTERIOR
MIN_WINDOWS = 15 MIN_WINDOWS = 15
MIN_GRADIENT_ELECTRODES = 6
INVALID = "invalid-eeg"
FRONT_BACK = { FRONT_BACK = {
"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59, "Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53, "T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
"Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95, "Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
} # fmt: skip } # fmt: skip
CODES = ( CODES = ("posterior_rhythm", "spindles", "paroxysmal_spikes", "anteroposterior_gradient")
"posterior_rhythm",
"spindles_n2",
"spindles_n3",
"paroxysmal_spikes",
"anteroposterior_gradient",
)
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None: @dataclass(frozen=True)
"""The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15.""" class Measured:
metrics: dict[str, tuple[float, dict, dict]] # code -> (value, electrodes, zones)
features: dict[str, dict[str, float]] # by scenario
reasons: dict[str, str] # code -> why it was not measured
rejected: dict[str, float] # minutes the spike gate left out, by reason
def _segments(prep: Prepared, names, states, state) -> tuple[list[np.ndarray], int]:
"""The gap-free 4 s windows labelled `state`, (channels, samples) each, and how many
windows bear the label."""
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state] starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
if len(starts) < MIN_WINDOWS or not names:
return None
x, n = prep.data(names), int(round(WINDOW_S * prep.fs)) x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
found = [] found = []
for a in (int(round(float(s) * prep.fs)) for s in starts): for a in (int(round(float(s) * prep.fs)) for s in starts if names):
if a + n <= len(x) and np.isfinite(x[a : a + n]).all(): if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
found.append(x[a : a + n].T) found.append(x[a : a + n].T)
return found or None return found, len(starts)
def posterior_rhythm(prep: Prepared, states) -> float: def posterior_rhythm(prep: Prepared, states) -> tuple[float, str | None]:
names = prep.columns(POSTERIOR) names = prep.columns(POSTERIOR)
segments = _segments(prep, names, states, "wake") segments, windows = _segments(prep, names, states, "wake")
if segments is None: if windows < MIN_WINDOWS:
return np.nan return np.nan, "few-wake-windows"
if not segments:
return np.nan, "no-dominant-peak"
f, power = signals.periodograms(np.stack(segments), prep.fs) f, power = signals.periodograms(np.stack(segments), prep.fs)
peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))] peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))]
found = [hz for hz, _, ok in peaks if ok] found = [hz for hz, _, ok in peaks if ok]
return float(np.median(found)) if len(found) >= 2 else np.nan return (float(np.median(found)), None) if len(found) >= 2 else (np.nan, "no-dominant-peak")
def delta_gradient(prep: Prepared, states) -> float: def delta_gradient(prep: Prepared, states) -> tuple[float, str | None]:
names = [c for c in prep.names if c in FRONT_BACK] names = [c for c in prep.names if c in FRONT_BACK]
segments = _segments(prep, names, states, "sleep") segments, windows = _segments(prep, names, states, "sleep")
if segments is None: if windows < MIN_WINDOWS:
return np.nan return np.nan, "no-sleep"
if len(names) < MIN_GRADIENT_ELECTRODES:
return np.nan, "few-electrodes"
if not segments:
return np.nan, "no-sleep"
stack = np.stack(segments) stack = np.stack(segments)
n = stack.shape[-1] n = stack.shape[-1]
f = rfftfreq(n, 1 / prep.fs) f = rfftfreq(n, 1 / prep.fs)
@@ -73,41 +87,50 @@ def delta_gradient(prep: Prepared, states) -> float:
log_power = np.log10(np.maximum(delta, 1e-30)) log_power = np.log10(np.maximum(delta, 1e-30))
y = np.array([FRONT_BACK[c] for c in names]) y = np.array([FRONT_BACK[c] for c in names])
finite = np.isfinite(log_power) finite = np.isfinite(log_power)
return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan if finite.sum() < MIN_GRADIENT_ELECTRODES:
return np.nan, "few-electrodes"
return float(theilslopes(log_power[finite], y[finite])[0]), None
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]: def invalid() -> Measured:
"""(metrics: code -> (value, electrodes, zones), features by scenario).""" """An EEG not valid: no metric, each for that reason."""
metrics, features = {}, {} return Measured({c: (np.nan, {}, {}) for c in CODES}, {}, dict.fromkeys(CODES, INVALID), {})
rhythm = posterior_rhythm(prep, states)
def measure(prep: Prepared, states, intervals) -> Measured:
metrics, features, reasons = {}, {}, {}
rhythm, reasons["posterior_rhythm"] = posterior_rhythm(prep, states)
metrics["posterior_rhythm"] = (rhythm, {}, {}) metrics["posterior_rhythm"] = (rhythm, {}, {})
features["eeg-posterior-rhythm"] = {"value": rhythm} features["eeg-posterior-rhythm"] = {"value": rhythm}
for stage in ("N2", "N3"): found = replace(spindles.detect(prep, states), rhythm_near_sigma=spindles.near_sigma(rhythm))
found = spindles.detect(prep, staged, stage)
value, zones = spindles.density(found) value, zones = spindles.density(found)
electrodes = spindles.enhancement(prep, found, states) electrodes = spindles.enhancement(prep, found, states)
metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones) metrics["spindles"] = (value, electrodes, zones)
features[f"eeg-spindles-{stage.lower()}"] = { features["eeg-spindles"] = {"value": value, **{f"zone_{z}": v for z, v in zones.items()},
"value": value, "rhythm_near_sigma": float(found.rhythm_near_sigma)} # fmt: skip
**{f"zone_{z}": v for z, v in zones.items()}, features["eeg-spindle-topography"] = {f"electrode_{e}": v for e, v in electrodes.items()}
} if np.isnan(value):
features[f"eeg-spindle-topography-{stage.lower()}"] = { reasons["spindles"] = "no-sleep" if found.minutes < spindles.MIN_MINUTES else "no-spindles"
f"electrode_{e}": v for e, v in electrodes.items() spiked = spikes.detect(prep, states, intervals)
} if spiked is None:
found = spikes.detect(prep, states, intervals) reasons["paroxysmal_spikes"] = "few-electrodes"
if found is None: recorded = {z: sum(e in prep.names for e in m) for z, m in spindles.ZONES.items()}
nan = dict.fromkeys spiked = spikes.Spikes(np.nan, dict.fromkeys(spikes.ELECTRODES, np.nan),
found = spikes.Spikes( dict.fromkeys(spindles.ZONES, np.nan), 0.0, {}, np.nan, 0.0,
np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0 recorded) # fmt: skip
) elif np.isnan(spiked.rate):
metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones) reasons["paroxysmal_spikes"] = "no-sleep"
metrics["paroxysmal_spikes"] = (spiked.rate, spiked.electrodes, spiked.zones)
features["eeg-spikes"] = { features["eeg-spikes"] = {
"value": found.rate, "value": spiked.rate,
**{f"electrode_{e}": v for e, v in found.electrodes.items()}, **{f"electrode_{e}": v for e, v in spiked.electrodes.items()},
**{f"zone_{z}": v for z, v in found.zones.items()}, **{f"zone_{z}": v for z, v in spiked.zones.items()},
"minutes": found.minutes, "minutes": spiked.minutes, "awake_rate": spiked.awake_rate,
} "awake_minutes": spiked.awake_minutes,
gradient = delta_gradient(prep, states) **{f"zone_electrodes_{z}": n for z, n in spiked.zone_electrodes.items()},
} # fmt: skip
gradient, reasons["anteroposterior_gradient"] = delta_gradient(prep, states)
metrics["anteroposterior_gradient"] = (gradient, {}, {}) metrics["anteroposterior_gradient"] = (gradient, {}, {})
features["eeg-gradient"] = {"value": gradient} features["eeg-gradient"] = {"value": gradient}
return {code: metrics[code] for code in CODES}, features reasons = {code: why for code, why in reasons.items() if why}
return Measured({code: metrics[code] for code in CODES}, features, reasons, spiked.rejected)
+36 -31
View File
@@ -37,6 +37,8 @@ MAX_BAD_SCALP = 2
MIN_SCALP = 12 MIN_SCALP = 12
MAX_LINE_DB = 45.0 MAX_LINE_DB = 45.0
NOT_ANALYZABLE = "not_analyzable" NOT_ANALYZABLE = "not_analyzable"
LEVELS = {NOT_ANALYZABLE: "No analizable", "partial": "Parcial",
"no_ear_reference": "Sin referencia auricular", "complete": "Completo"} # fmt: skip
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -47,10 +49,7 @@ class Validation:
clean_pct: float clean_pct: float
line_db: float line_db: float
checks: list[dict] = field(default_factory=list) checks: list[dict] = field(default_factory=list)
reasons: list[str] = field(default_factory=list) # why it is not valid
@property
def ears_usable(self) -> bool:
return all(ear not in self.bad for ear in ("A1", "A2"))
def check( def check(
@@ -80,7 +79,7 @@ def check(
def file_not_valid(reason: str) -> Validation: def file_not_valid(reason: str) -> Validation:
rows = [check("file", text=reason, decisive=True, abnormal=True)] rows = [check("file", text=reason, decisive=True, abnormal=True)]
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows) return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows, ["invalid-file"])
def _filtered(x, fs, mains_hz, lo, hi): def _filtered(x, fs, mains_hz, lo, hi):
@@ -91,14 +90,14 @@ def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
"""Rules on a channel's raw samples: (code, reason).""" """Rules on a channel's raw samples: (code, reason)."""
finite = v[np.isfinite(v)] finite = v[np.isfinite(v)]
if len(finite) < 10 or np.std(finite) < 0.5: if len(finite) < 10 or np.std(finite) < 0.5:
return [("dead-channel", "dead channel")] return [("dead-channel", "Canal muerto")]
out = [] out = []
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5: if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
out.append(("frozen", "frozen")) out.append(("frozen", "Señal congelada"))
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001: if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
out.append(("saturated", "saturated")) out.append(("saturated", "Señal saturada"))
if np.isinf(v).any(): if np.isinf(v).any():
out.append(("inf-values", "Inf values")) out.append(("inf-values", "Valores infinitos"))
return out return out
@@ -166,9 +165,7 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
"""Channel -> [(code, reason)] of every channel some rule flags.""" """Channel -> [(code, reason)] of every channel some rule flags."""
x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds() x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)} reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
dead = { dead = {name for name, found in reasons.items() if found and found[0][0] == "dead-channel"}
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
}
notched = signals.notch(x, fs, mains_hz) notched = signals.notch(x, fs, mains_hz)
y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9)) y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9))
y40 = signals.bandpass(notched, fs, 1.0, 40.0) y40 = signals.bandpass(notched, fs, 1.0, 40.0)
@@ -184,34 +181,38 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
found, k = reasons[name], kinds[name] found, k = reasons[name], kinds[name]
if missing[i] > missing.min() + 0.02: if missing[i] > missing.min() + 0.02:
excess = 100 * (missing[i] - missing.min()) excess = 100 * (missing[i] - missing.min())
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)")) found.append(
("own-gaps", f"Interrupciones del canal ({excess:.1f} % más que el resto)")
)
if name in dead: if name in dead:
continue continue
if k == "eeg" and name in bridges: if k == "eeg" and name in bridges:
found.append(("bridge", f"bridge with {bridges[name]}")) found.append(("bridge", f"Puente con {bridges[name]}"))
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0: if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median")) found.append(
("amplitude", f"Amplitud {ratio[i]:.1f} veces la mediana del cuero cabelludo")
)
if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]: if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
c, e = ears[name] c, e = ears[name]
found.append( found.append(
( (
"does-not-correlate", "does-not-correlate",
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})", f"Sin correlación con los vecinos ({c:.2f} frente a {e:.2f})",
) )
) )
if np.isfinite(low[i]) and low[i] > 0.10: if np.isfinite(low[i]) and low[i] > 0.10:
found.append( found.append(
( (
"intermittent-contact", "intermittent-contact",
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)", f"Contacto intermitente ({100 * low[i]:.0f} % de bloques sin señal)",
) )
) )
if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05: if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
found.append( found.append(
( (
"intermittent-bursts", "intermittent-bursts",
f"intermittent contact by bursts " f"Contacto intermitente por ráfagas "
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)", f"({100 * burst[i]:.0f} % de bloques por encima de 4 veces el montaje)",
) )
) )
if k in ("eog", "ecg"): if k in ("eog", "ecg"):
@@ -220,18 +221,19 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
found.append( found.append(
( (
"aux-amplitude", "aux-amplitude",
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, " f"Amplitud {np.sqrt(np.mean(v**2)):.0f} µV, "
f"out of range even for {k.upper()}", f"fuera de rango incluso para {k.upper()}",
) )
) )
return {name: found for name, found in reasons.items() if found} return {name: found for name, found in reasons.items() if found}
def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]: def window_qc(y: np.ndarray, fs: float, start_s: float = 0.0) -> list[tuple[float, float, str]]:
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the """Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
verdict `gap`, `suspect` or `clean`.""" verdict `gap`, `suspect` or `clean`; its fixed lines are sought after `start_s` (when 30 s
n = int(4 * fs) or more remain)."""
lines = signals.fixed_lines(y, fs, f_max=44.0) n, start = int(4 * fs), int(start_s * fs)
lines = signals.fixed_lines(y[start:] if len(y) - start > 30 * fs else y, fs, f_max=44.0)
starts = list(range(0, len(y) - n + 1, n)) starts = list(range(0, len(y) - n + 1, n))
segments = [y[a : a + n] for a in starts] segments = [y[a : a + n] for a in starts]
whole = [bool(np.isfinite(s).all()) for s in segments] whole = [bool(np.isfinite(s).all()) for s in segments]
@@ -315,7 +317,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
check( check(
"internal-coverage", "internal-coverage",
value=coverage, value=coverage,
unit="fraction", unit="fracción",
low=MIN_COVERAGE, low=MIN_COVERAGE,
abnormal=coverage < MIN_COVERAGE, abnormal=coverage < MIN_COVERAGE,
decisive=True, decisive=True,
@@ -323,7 +325,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
check( check(
"bad-scalp-triage", "bad-scalp-triage",
value=float(len(triaged)), value=float(len(triaged)),
unit="electrodes", unit="electrodos",
high=float(MAX_BAD_SCALP), high=float(MAX_BAD_SCALP),
abnormal=len(triaged) > MAX_BAD_SCALP, abnormal=len(triaged) > MAX_BAD_SCALP,
decisive=True, decisive=True,
@@ -331,12 +333,12 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
check( check(
"usable-scalp", "usable-scalp",
value=float(len(usable)), value=float(len(usable)),
unit="electrodes", unit="electrodos",
low=float(MIN_SCALP), low=float(MIN_SCALP),
abnormal=len(usable) < MIN_SCALP, abnormal=len(usable) < MIN_SCALP,
decisive=True, decisive=True,
), ),
check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True), check("triage-level", text=LEVELS[level], abnormal=level == NOT_ANALYZABLE, decisive=True),
] ]
if np.isfinite(line): if np.isfinite(line):
rows.append( rows.append(
@@ -344,6 +346,9 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB "line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
) )
) )
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP failed = {"triage-not-analyzable": level == NOT_ANALYZABLE,
"few-clean-minutes": clean_pct < MIN_CLEAN_PCT,
"few-electrodes": len(usable) < MIN_SCALP} # fmt: skip
reasons = [reason for reason, fails in failed.items() if fails]
bad = {name: [reason for _, reason in found] for name, found in flagged.items()} bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
return Validation(valid, level, bad, clean_pct, line, rows) return Validation(not reasons, level, bad, clean_pct, line, rows, reasons)
+69 -44
View File
@@ -1,7 +1,7 @@
"""Age baselines: each metric's value (and per electrode and zone) against children of the same """Age baselines: each metric's value (and per electrode and zone) against children of the same
age in a reference cohort. age in a reference cohort.
Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference Five scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets
its own baseline, plain JSON-able data (`train`), scored by `score`: its own baseline, plain JSON-able data (`train`), scored by `score`:
@@ -14,7 +14,9 @@ its own baseline, plain JSON-able data (`train`), scored by `score`:
minute (16 to 37 months) and its dispersion between children (negative binomial by moments, minute (16 to 37 months) and its dispersion between children (negative binomial by moments,
Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from
the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5, the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5,
median and p95 are the rates at those quantiles of the count in those minutes. median and p95 are the rates at those quantiles of the count in those minutes. A zone's rate
is per minute and electrode: its exposure is its minutes times its electrodes recorded.
A value without a score says why (`reason`): no-age, age-out-of-range or no-exposure.
""" """
import math import math
@@ -31,22 +33,21 @@ MIN_EFFECTIVE = 30
COUNT_AGES = (16.0, 37.0) COUNT_AGES = (16.0, 37.0)
Z_MAX = 8.0 Z_MAX = 8.0
EXPOSURE = "minutes" EXPOSURE = "minutes"
NOT_MEASURES = ("age_months", EXPOSURE, "rhythm_near_sigma") # in a table, not baselines
SCORE_FIELDS = ("z", "outside", "p5", "median", "p95")
@dataclass(frozen=True) @dataclass(frozen=True)
class Scenario: class Scenario:
metric: str # the metric code it scores metric: str # the metric code it scores
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones" parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones"
stage: str | None = None
counts: bool = False # a count against the `minutes` feature, not centile curves counts: bool = False # a count against the `minutes` feature, not centile curves
SCENARIOS = { SCENARIOS = {
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)), "eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
"eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"), "eeg-spindles": Scenario("spindles", ("value", "zones")),
"eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"), "eeg-spindle-topography": Scenario("spindles", ("electrodes",)),
"eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"),
"eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"),
"eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True), "eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True),
"eeg-gradient": Scenario("anteroposterior_gradient", ("value",)), "eeg-gradient": Scenario("anteroposterior_gradient", ("value",)),
} }
@@ -81,7 +82,10 @@ def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
} }
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict: def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray,
electrodes: np.ndarray) -> dict: # fmt: skip
"""A zone's rate per minute and electrode: its count over its minutes x electrodes."""
exposure = exposure * electrodes
n = np.round(values * exposure) n = np.round(values * exposure)
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0) keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1]) keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
@@ -101,15 +105,21 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
def train(features: pd.DataFrame, scenario: str) -> dict: def train(features: pd.DataFrame, scenario: str) -> dict:
"""Feature -> baseline, for every feature of the scenario's table (`age_months` and the """Feature -> baseline, for every measure of the scenario's table (NOT_MEASURES, a zone's
count's `minutes` excepted).""" electrodes and the awake spikes excepted)."""
counts = SCENARIOS[scenario].counts counts = SCENARIOS[scenario].counts
ages = features["age_months"].to_numpy(float) ages = features["age_months"].to_numpy(float)
out = {} out = {}
for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"): for name in features.columns.drop(list(NOT_MEASURES), errors="ignore"):
if name.startswith(("zone_electrodes_", "awake_")):
continue
values = pd.to_numeric(features[name]).to_numpy(float) values = pd.to_numeric(features[name]).to_numpy(float)
if counts: if counts:
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float)) column = f"zone_electrodes_{name.removeprefix('zone_')}"
electrodes = np.ones(len(features))
if name.startswith("zone_") and column in features:
electrodes = pd.to_numeric(features[column]).fillna(1).to_numpy(float)
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes)
else: else:
out[name] = _curve(values, ages) out[name] = _curve(values, ages)
return out return out
@@ -119,51 +129,64 @@ def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None return float(v) if v is not None and math.isfinite(v) else None
def _score_curve(baseline: dict, value: float, age: float) -> dict: def _unscored(reason: str | None = None) -> dict:
"""No score, and why: no-age, age-out-of-range, no-exposure (None: no value)."""
return {**dict.fromkeys(SCORE_FIELDS), "reason": reason}
def centiles(baseline: dict, age_months: float) -> dict:
"""A curve's centiles at an age (None outside the curve)."""
curve = pd.DataFrame(baseline["curve"]).astype(float).dropna() curve = pd.DataFrame(baseline["curve"]).astype(float).dropna()
out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) names = [name for name in QUANTILES if name in curve]
if not len(curve) or not age > 0: if curve.empty or not age_months > 0:
return out return dict.fromkeys(QUANTILES)
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0]) log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(age_months))
if not log_ages.min() <= at <= log_ages.max(): if not log_ages.min() <= at <= log_ages.max():
return out return dict.fromkeys(QUANTILES)
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES} return {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in names}
def _score_curve(baseline: dict, value: float, age: float) -> dict:
q = centiles(baseline, age)
if q["median"] is None:
return _unscored("age-out-of-range")
side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"] side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"]
z = (value - q["median"]) / (side / 1.645) if side > 0 else None z = (value - q["median"]) / (side / 1.645) if side > 0 else None
outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0 outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0
return { return {"z": _number(z), "outside": outside, "p5": q["p5"], "median": q["median"],
"z": _number(z), "p95": q["p95"], "reason": None} # fmt: skip
"outside": outside,
"p5": q["p5"],
"median": q["median"],
"p95": q["p95"],
}
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict: def _score_count(baseline: dict, value: float, age: float, exposure: float | None,
out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) electrodes: float) -> dict: # fmt: skip
rate, k = baseline["rate"], baseline["k"] rate, k = baseline["rate"], baseline["k"]
lo, hi = baseline["ages"] lo, hi = baseline["ages"]
if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi): if not lo <= age < hi:
return out return _unscored("age-out-of-range")
n, mu = float(np.round(value * exposure)), rate * exposure if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0:
return _unscored("no-exposure")
n, mu = float(np.round(value * exposure)), rate * exposure * electrodes
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu)) law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
tail, at = law.sf(n - 1), law.pmf(n) tail, at = law.sf(n - 1), law.pmf(n)
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX)) z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95)) p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95} return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95,
"reason": None} # fmt: skip
def score( def score(baseline: dict, value: float | None, age_months: float | None,
baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None exposure: float | None = None, electrodes: float | None = None) -> dict: # fmt: skip
) -> dict: """z, outside (-1/0/+1), p5, median, p95 of a value at an age, and the reason when it has
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the none; a count against its minutes (`exposure`) and, a zone's, its electrodes."""
age or the baseline's coverage is missing."""
value, age_months = _number(value), _number(age_months) value, age_months = _number(value), _number(age_months)
if value is None or age_months is None: if value is None:
return dict.fromkeys(("z", "outside", "p5", "median", "p95")) return _unscored()
if age_months is None:
return _unscored("no-age")
if baseline["kind"] == "count_rate": if baseline["kind"] == "count_rate":
return _score_count(baseline, value, age_months, _number(exposure)) electrodes = _number(electrodes)
return _score_count(baseline, value, age_months, _number(exposure),
1.0 if electrodes is None else electrodes) # fmt: skip
return _score_curve(baseline, value, age_months) return _score_curve(baseline, value, age_months)
@@ -177,15 +200,17 @@ def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
model, metric = models.get(name), metrics.get(scenario.metric) model, metric = models.get(name), metrics.get(scenario.metric)
if model is None or metric is None: if model is None or metric is None:
continue continue
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None features = analysis.features.get(name, {})
exposure = features.get(EXPOSURE) if scenario.counts else None
for part in scenario.parts: for part in scenario.parts:
if part == "value": if part == "value":
out[metric.code]["value"] = score( out[metric.code]["value"] = score(
model["value"], metric.value, analysis.age_months, exposure model["value"], metric.value, analysis.age_months, exposure
) )
else: continue
out[metric.code][part] = { out[metric.code][part] = {
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure) key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure,
features.get(f"zone_electrodes_{key}") if part == "zones" else None)
for key, v in getattr(metric, part).items() for key, v in getattr(metric, part).items()
} } # fmt: skip
return out return out
+67 -16
View File
@@ -1,26 +1,35 @@
"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average """A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean. reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp The mains notch (at the recording's mains) runs when the line stands at least 6 dB over its
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given: neighbourhood on the kept scalp channels. A reference study's one flat electrode can be kept
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so. (`keep_flat`), outside QC. The QC behind the unclean spans is the validation's window rule on the
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp kept scalp channels with every mains harmonic notched (IIR, Q 30) at 0.5-45 Hz; everything
channels at 0.5-45 Hz. before the stable start (`stable_start`) is unclean too.
Stable start: on back-to-back 10 s blocks of the scalp channels, the first block from which at
least 90 % of the rest (6 blocks or more) stay under twice the median spread of the recording's
second half; a later note of the recording's start (start record, inicio...) or the last note
of its set-up (impedances, montage, calibration...) moves it there.
""" """
import unicodedata
import warnings import warnings
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
from scipy import signal
from models.tea.eeg import signals from models.tea.eeg import signals
from models.tea.eeg.checks import window_qc from models.tea.eeg.checks import window_qc
from models.tea.eeg.read import Recording from models.tea.eeg.read import Recording
NOTCH_HZ = 60.0
NOTCH_MIN_DB = 6.0 NOTCH_MIN_DB = 6.0
WINDOW_S = 4.0 WINDOW_S = 4.0
STEP_S = 2.0 STEP_S = 2.0
START_MARKS = ("start record", "inicio", "comienzo", "begin record", "recording on",
"start of record") # fmt: skip
SETUP_MARKS = ("impedanc", "montaje", "montage", "electrod", "calibrac", "colocac", "prueba")
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -44,12 +53,54 @@ class Prepared:
return self.x[:, [self.names.index(name) for name in names]] return self.x[:, [self.names.index(name) for name in names]]
def prepare(rec: Recording, bad) -> Prepared: def _plain(text) -> str:
scalp = [name for name in rec.of("eeg") if name not in bad] return "".join(c for c in unicodedata.normalize("NFD", str(text))
if unicodedata.category(c) != "Mn").lower() # fmt: skip
def stable_start(rec: Recording) -> float:
"""Seconds from which the recording settles (module docstring)."""
x = rec.x[:, [rec.names.index(name) for name in rec.of("eeg")]]
n = int(10 * rec.fs)
blocks = [x[a : a + n] for a in range(0, len(x) - n + 1, n)]
rms = np.array([np.median(np.std(b, axis=0)) if np.isfinite(b).all() else np.nan
for b in blocks]) # fmt: skip
finite = np.isfinite(rms)
if finite.sum() < 12:
return 0.0
limit = 2.0 * np.median(rms[finite][finite.sum() // 2 :])
start = 0.0
for i in np.flatnonzero(finite):
rest = rms[i:][np.isfinite(rms[i:])]
if len(rest) >= 6 and np.mean(rest <= limit) >= 0.9:
start = i * n / rec.fs
break
mark = None
for onset, _, text in sorted(rec.annotations, key=lambda a: a[0]):
if any(m in _plain(text) for m in START_MARKS):
mark = onset
break
if any(m in _plain(text) for m in SETUP_MARKS):
mark = onset
return float(mark) if mark is not None and mark >= start else start
def _harmonics_notched(x: np.ndarray, fs: float, mains_hz: float) -> np.ndarray:
nyquist = fs / 2 * 0.98
sos = np.vstack([np.hstack(signal.iirnotch(k * mains_hz, 30.0, fs))
for k in range(1, 100) if k * mains_hz < nyquist]) # fmt: skip
minimum = max(3 * (len(sos) * 2 + 1), int(fs))
return signals.by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
def prepare(rec: Recording, bad, mains_hz: float, keep_flat: bool = False) -> Prepared:
eeg = rec.of("eeg")
flat = [n for n in eeg if not np.nanstd(rec.x[:, rec.names.index(n)]) > 0.5]
keep = flat if keep_flat and len(flat) == 1 else []
scalp = [name for name in eeg if name not in bad or name in keep]
x = rec.x[:, [rec.names.index(name) for name in scalp]] x = rec.x[:, [rec.names.index(name) for name in scalp]]
if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB: if np.nanmedian(signals.line_db(x, rec.fs, mains_hz)) >= NOTCH_MIN_DB:
x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5) x = signals.notch(x, rec.fs, mains_hz, width=1.5)
gaps = ~np.isfinite(x).all(axis=1)
y = signals.bandpass(x, rec.fs, 0.5, 100.0) y = signals.bandpass(x, rec.fs, 0.5, 100.0)
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row
@@ -57,10 +108,10 @@ def prepare(rec: Recording, bad) -> Prepared:
# Kept as the reference analysis read it from MNE: through volts and back, column-major in # Kept as the reference analysis read it from MNE: through volts and back, column-major in
# memory (the layout decides the order of float sums along time). # memory (the layout decides the order of float sums along time).
referenced = np.asfortranarray(referenced * 1e-6 * 1e6) referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
qc = signals.bandpass(x, rec.fs, 0.5, 45.0) raw = rec.x[:, [rec.names.index(name) for name in scalp if name not in keep]]
qc[gaps] = np.nan qc = signals.bandpass(_harmonics_notched(raw, rec.fs, mains_hz), rec.fs, 0.5, 45.0)
unclean = tuple( start = stable_start(rec)
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean" unclean = tuple((float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs, start)
) if v != "clean" or t0 < start) # fmt: skip
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S) starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations) return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
+47 -3
View File
@@ -75,14 +75,58 @@ class Recording:
return [name for name in self.names if kind(name) in kinds] return [name for name in self.names if kind(name) in kinds]
def _kept(edf: bytes) -> list[tuple[str, str]]: @dataclass(frozen=True)
"""(label, name) of the channels to read: recognised, at the majority rate, first of each.""" class Header:
"""What an EDF's header says of its patient and recording (EDF+ fields; None when not
given)."""
patient_code: str | None
sex: str | None
birthdate: date | None
start_date: date | None
record_code: str | None
duration_s: float | None
channels: int
def _open(edf: bytes) -> edfio.Edf:
if len(edf) < 256: if len(edf) < 256:
raise FileNotValid("file too short to be an EDF (header < 256 bytes)") raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
try: try:
signals = edfio.read_edf(edf, lazy_load_data=True).signals opened = edfio.read_edf(edf, lazy_load_data=True)
except Exception as exc: # noqa: BLE001 -- any parse failure means the same except Exception as exc: # noqa: BLE001 -- any parse failure means the same
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
if int(edf[236:244]) > opened.num_data_records:
raise FileNotValid("the EDF signal data is truncated")
return opened
def _given(read) -> object | None:
"""An EDF+ subfield, None when not given ('X' or not compliant)."""
try:
value = read()
except ValueError:
return None
return None if value in ("", "X") else value
def header(edf: bytes) -> Header:
opened = _open(edf)
start = _given(lambda: opened.recording.startdate)
return Header(
patient_code=_given(lambda: opened.patient.code),
sex=sex if (sex := _given(lambda: opened.patient.sex)) in ("F", "M") else None,
birthdate=_given(lambda: opened.patient.birthdate),
start_date=None if start == UNKNOWN_START else start,
record_code=_given(lambda: opened.recording.hospital_administration_code),
duration_s=opened.duration,
channels=opened.num_signals,
)
def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
signals = _open(edf).signals
if not signals: if not signals:
raise FileNotValid("the EDF declares zero signals") raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals] named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
+16 -17
View File
@@ -1,11 +1,11 @@
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public), """A reference cohort the age baselines can be trained on (a folder of EDFs of children of 16
children of 16 to 36 months, recorded on 50 Hz mains. to 36 months, such as HK1K, the Helsinki EEGs) instead of the site's own.
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the `listing` pairs each EDF under a folder with its age from the cohort's table (`path`, relative
file name, second the age in years; months = years x 12 to one decimal); keys are positions in to the folder, and `age` in months, kept to one decimal); keys are the folder's name and a
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's position in path order, never file names. `measure` analyses each study as a hospital EEG (at
mains, with the table's age) in worker processes; `tables` gives each scenario's training table the cohort's mains, with the table's age, keeping a single flat electrode) in worker
from the valid studies. processes; `tables` gives each scenario's training table from the valid studies.
""" """
from pathlib import Path from pathlib import Path
@@ -16,25 +16,23 @@ from models import cluster
from models.tea.eeg.analysis import analyze from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS from models.tea.eeg.curves import SCENARIOS
NAME = "hk1k"
MAINS_HZ = 50.0
AGES = (16.0, 36.0) AGES = (16.0, 36.0)
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]: def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
"""(key, path, age in months) of each EDF with an age within `ages`.""" """(key, path, age in months) of each EDF with an age within `ages`."""
table = pd.read_csv(ages_table) table = pd.read_csv(ages_table)
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True)) months = dict(zip(table["path"].astype(str), table["age"].astype(float), strict=True))
found = [] found = []
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"): for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
age = round(float(years[path.name] * 12), 1) if path.name in years else None age = months.get(path.relative_to(folder).as_posix())
if age is not None and age == age and ages[0] <= age <= ages[1]: if age is not None and age == age and ages[0] <= age <= ages[1]:
found.append((path, age)) found.append((path, round(age, 1)))
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] return [(f"{Path(folder).name}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(key: str, edf: bytes, age: float) -> dict: def _one(key: str, edf: bytes, age: float, mains_hz: float) -> dict:
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ) a = analyze(edf, age_months=age, mains_hz=mains_hz, keep_flat=True)
return { return {
"key": key, "key": key,
"age_months": age, "age_months": age,
@@ -44,11 +42,12 @@ def _one(key: str, edf: bytes, age: float) -> dict:
} }
def measure(studies) -> list[dict]: def measure(studies, mains_hz: float) -> list[dict]:
"""Each study's verdict and features, in listing order, each a task on the cluster """Each study's verdict and features, in listing order, each a task on the cluster
(models.cluster).""" (models.cluster)."""
# each task carries its recording: workers see no local folder # each task carries its recording: workers see no local folder
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies)) return cluster.run(_one, ((key, Path(path).read_bytes(), age, mains_hz)
for key, path, age in studies)) # fmt: skip
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
+3 -5
View File
@@ -3,13 +3,12 @@
Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A
filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum
stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge
padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains padding) and so are the periodograms (`periodogram`, a symmetric Hann window). The mains
notch, the fixed-line search and the dominant peak are small rules of their own: no library notch, the fixed-line search and the dominant peak are small rules of their own: no library
computes the same thing (MNE's notch filters change the signal by microvolts). computes the same thing (MNE's notch filters change the signal by microvolts).
""" """
import numpy as np import numpy as np
from mne.time_frequency import psd_array_welch
from scipy import signal from scipy import signal
from scipy.ndimage import median_filter from scipy.ndimage import median_filter
@@ -85,9 +84,8 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
"""One Hann periodogram (density, mean removed) of each segment along the last axis: """One Hann periodogram (density, mean removed) of each segment along the last axis:
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`.""" `(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
n = segments.shape[-1] window = np.hanning(segments.shape[-1])
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") return signal.periodogram(segments, fs, window=window, detrend="constant", axis=-1)
return f, power
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]: def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
+37 -82
View File
@@ -1,9 +1,11 @@
"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3). """The state of each grid window: wake, drowsy or sleep.
Notes: a note's state is the first whose words its text contains (lower case, accents removed, Notes: a note's state is the first whose cues its text holds (lower case, accents removed, ñ
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s; read as n): a cue is a word prefix (`hipervent`) or, for short ones, a whole word (`hv`, `n2`);
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement, a note that ends something (off, fin, end, stop) has none. It lasts its duration or, without
disconnection, photic stimulation and hyperventilation are masked. one, until the next note with a state or 60 s; pieces under 1 s are dropped and the stretches
between notes are `unmarked`. Crying, movement, disconnection, photic stimulation and
hyperventilation are masked.
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma, features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
@@ -11,13 +13,10 @@ muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is s
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age), the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
posterior electrode leaves that feature out of the mean. posterior electrode leaves that feature out of the mean.
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
20 % of the 30 s centred on it, else N2.
""" """
import json import json
import re
import unicodedata import unicodedata
from pathlib import Path from pathlib import Path
@@ -27,18 +26,29 @@ from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared from models.tea.eeg.preprocess import WINDOW_S, Prepared
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text()) REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
NOTE_WORDS = { # (state, its word prefixes, its whole words), in the order a note is matched
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"), NOTE_WORDS = [
"hyperventilation": ("hv", "hipervent", "hypervent"), ("photic", ("fotic", "photic", "flash", "estimulacion luminosa"), ()),
"eyes_open": ("ojos abiertos", "eyes open", "oa"), ("hyperventilation", ("hipervent", "hypervent"), ("hv",)),
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"), ("eyes_open", ("ojos abiertos", "eyes open", "open eyes", "opens eyes", "abre ojos",
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii", "abre los ojos", "abrio ojos", "abrio los ojos", "apertura de ojos",
"n1", "n2", "n3"), "apertura ocular"), ("oa", "eo")),
"awake": ("despierta", "despierto", "arousal", "vigilia"), ("eyes_closed", ("ojos cerrados", "eyes closed", "close eyes", "closes eyes", "eyes shut",
"crying": ("llanto", "llora", "cry"), "cierra ojos", "cierra los ojos", "cerro ojos", "cerro los ojos",
"movement": ("movimiento", "movement", "artefacto de movimiento"), "cierre de ojos", "cierre ocular"), ("oc", "ec")),
"feeding": ("come", "alimenta", "biberon", "lactancia"), ("sleep", ("sueno", "dormido", "dormida", "sleep", "asleep", "somnol", "husos", "spindle"),
} # fmt: skip ("fase i", "fase ii", "fase iii", "n1", "n2", "n3")),
("awake", ("despierta", "despierto", "arousal", "vigilia"), ()),
("crying", ("llanto", "llora", "cry"), ()),
("movement", ("movimiento", "movement", "artefacto de movimiento"), ()),
("feeding", ("alimenta", "biberon", "lactancia"), ("come", "comer", "comio", "comiendo")),
] # fmt: skip
END = re.compile(r"\b(off|fin|end|stop)\b")
PATTERNS = [
(state, re.compile("|".join([*(rf"\b{re.escape(p)}" for p in prefixes),
*(rf"\b{re.escape(w)}\b" for w in words)])))
for state, prefixes, words in NOTE_WORDS
] # fmt: skip
EXCLUDED = ("crying", "movement", "disconnection") EXCLUDED = ("crying", "movement", "disconnection")
MASKED = (*EXCLUDED, "photic", "hyperventilation") MASKED = (*EXCLUDED, "photic", "hyperventilation")
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object) STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
@@ -46,18 +56,14 @@ BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16)
"beta": (16, 30), "high": (20, 40)} # fmt: skip "beta": (16, 30), "high": (20, 40)} # fmt: skip
POSTERIOR = ("O1", "O2", "P3", "P4") POSTERIOR = ("O1", "O2", "P3", "P4")
CENTRAL = ("C3", "C4", "Cz") CENTRAL = ("C3", "C4", "Cz")
FRONTAL = ("F3", "F4", "Fz")
def note_state(text: str) -> str | None: def note_state(text: str) -> str | None:
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1") plain = "".join(c for c in unicodedata.normalize("NFD", str(text or ""))
plain = "".join( if unicodedata.category(c) != "Mn").lower().strip() # fmt: skip
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn" if END.search(plain):
) return None
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip() return next((state for state, pattern in PATTERNS if pattern.search(plain)), None)
return next(
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
)
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]: def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
@@ -122,6 +128,7 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
if not starts: if not starts:
return [], {} return [], {}
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs) f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
power *= fs * (np.hanning(n) ** 2).sum() / 2 # the reference's scale (hk1k_state.json)
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()} band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12) total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names)))) central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names))))
@@ -169,55 +176,3 @@ def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True)) by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True))
out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts] out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts]
return out return out
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
"""(onset s, duration s) of the slow waves of one channel."""
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
sign = np.sign(y)
sign[sign == 0] = 1
crossings = np.flatnonzero(np.diff(sign) != 0) + 1
waves = []
for j, c0 in enumerate(crossings):
if not y[c0] < 0:
continue
if j + 2 >= len(crossings):
break
c1, c2 = crossings[j + 1], crossings[j + 2]
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
continue
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
if 75.0 <= p2p <= 300.0:
waves.append((round(c0 / fs, 3), round(total, 3)))
return waves
def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
if not waves:
return np.empty((0, 2))
a = np.array([onset for onset, _ in waves])
b = a + np.array([length for _, length in waves])
order = np.argsort(a)
out = [[a[order[0]], b[order[0]]]]
for i in order[1:]:
if a[i] <= out[-1][1]:
out[-1][1] = max(out[-1][1], b[i])
else:
out.append([a[i], b[i]])
return np.array(out)
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
"""`N3` or `N2` per sleep window (`` elsewhere)."""
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
covered = _merged(waves)
out = np.full(len(prep.starts), "", dtype=object)
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
if label != "sleep":
continue
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
return out
+66 -24
View File
@@ -4,7 +4,10 @@ the clean minutes of sleep.
Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an
excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz
power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is
one. Each kept window adds its 2 s to the state of its midpoint. one. Each kept window adds its 2 s to the state of its midpoint; each left out adds its minutes
to each reason (gap, state, mixed-states, muscle, frozen). A time takes the state of the grid
window holding it or, outside every one, that of the nearest within 30 s (`transition` when
the windows on either side differ).
Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD, Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD,
20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both 20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both
@@ -16,8 +19,9 @@ and width. A useful discharge has field and is not a vertex wave (asleep, max on
slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on
Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair). Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair).
Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode Rate: useful discharges in sleep per sleep minute to 3 decimals, and awake (wake or drowsy) per
(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals. awake minute; per electrode (its own maxima) and per zone (its electrodes' sum, with how many
it has), per minute to 4 decimals.
""" """
from dataclasses import dataclass from dataclasses import dataclass
@@ -33,12 +37,13 @@ from models.tea.eeg.spindles import ZONES
ELECTRODES = tuple(NEIGHBOURS) ELECTRODES = tuple(NEIGHBOURS)
GATE_S = 2.0 GATE_S = 2.0
INHERIT_S = 30.0
VERTEX = ("Cz", "Fz", "Pz") VERTEX = ("Cz", "Fz", "Pz")
POSTS = ("O1", "O2") POSTS = ("O1", "O2")
OCULAR = ("Fp1", "Fp2", "F7", "F8") OCULAR = ("Fp1", "Fp2", "F7", "F8")
POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"} POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"}
LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4")) LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4"))
ASLEEP = ("N2", "N3", "sleep") ASLEEP = ("sleep",)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -47,6 +52,31 @@ class Spikes:
electrodes: dict[str, float] electrodes: dict[str, float]
zones: dict[str, float] zones: dict[str, float]
minutes: float # clean sleep minutes, the rate's exposure minutes: float # clean sleep minutes, the rate's exposure
rejected: dict[str, float] # minutes the gate left out, by reason
awake_rate: float
awake_minutes: float
zone_electrodes: dict[str, int] # per zone, its electrodes recorded
def _states(labelled, duration_s: float) -> np.ndarray:
"""The state every 0.5 s: its window's, or the nearest window's within INHERIT_S."""
t = np.arange(0.0, duration_s, 0.5)
out = np.full(len(t), "unlabelled", dtype=object)
for t0, t1, label in labelled:
out[(out == "unlabelled") & (t0 <= t) & (t < t1)] = label
direct = np.flatnonzero(out != "unlabelled")
if not len(direct):
return out
missing = np.flatnonzero((out == "unlabelled") & (t >= t[direct[0]]))
j = np.searchsorted(direct, missing)
before, after = direct[np.maximum(j - 1, 0)], direct[np.minimum(j, len(direct) - 1)]
to_before = np.where(j > 0, t[missing] - t[before], np.inf)
to_after = np.where(j < len(direct), t[after] - t[missing], np.inf)
labels = np.where(to_before <= to_after, out[before], out[after])
labels[(j > 0) & (j < len(direct)) & (out[before] != out[after])] = "transition"
close = np.minimum(to_before, to_after) <= INHERIT_S
out[missing[close]] = labels[close]
return out
def _mad(v: np.ndarray) -> float: def _mad(v: np.ndarray) -> float:
@@ -56,29 +86,34 @@ def _mad(v: np.ndarray) -> float:
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]: def _gate(x: np.ndarray, fs: float, intervals) -> tuple[list[tuple[float, float]], dict]:
"""(start, end) s of the 2 s windows the detector reads.""" """(start, end) s of the 2 s windows the detector reads, and the minutes left out by
reason."""
n = int(GATE_S * fs) n = int(GATE_S * fs)
top = min(45, fs / 2 * 0.9) top = min(45, fs / 2 * 0.9)
lines = signals.fixed_lines(x, fs, f_max=top) lines = signals.fixed_lines(x, fs, f_max=top)
f = np.fft.rfftfreq(n, 1 / fs) f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None] taper = np.hanning(n)[:, None]
kept = [] kept, rejected = [], {}
for a in range(0, len(x) - n + 1, n): for a in range(0, len(x) - n + 1, n):
t0, t1 = a / fs, a / fs + GATE_S t0, t1 = a / fs, a / fs + GATE_S
state, mixed = window_note(t0, t1, intervals) state, mixed = window_note(t0, t1, intervals)
segment = x[a : a + n] segment = x[a : a + n]
if not np.isfinite(segment).all() or state in EXCLUDED or mixed: reasons = ["gap"]
continue if np.isfinite(segment).all():
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2 power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
power = power.mean(axis=1) power = power.mean(axis=1)
high = signals.band_power(f, power, 20, top, lines, include_hi=True) high = signals.band_power(f, power, 20, top, lines, include_hi=True)
low = signals.band_power(f, power, 4, 13, lines, include_hi=True) low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
muscle = float(high / max(low, 1e-12))
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9)) frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
if not (muscle > 1.5 or frozen > 0.5): failed = {"state": state in EXCLUDED, "mixed-states": mixed,
"muscle": high / max(low, 1e-12) > 1.5, "frozen": frozen > 0.5} # fmt: skip
reasons = [reason for reason, fails in failed.items() if fails]
if not reasons:
kept.append((round(t0, 2), round(t1, 2))) kept.append((round(t0, 2), round(t1, 2)))
return kept for reason in reasons:
rejected[reason] = rejected.get(reason, 0.0) + GATE_S / 60.0
return kept, {reason: round(minutes, 4) for reason, minutes in rejected.items()}
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]: def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
@@ -189,20 +224,23 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
if label in ("wake", "drowsy", "sleep") if label in ("wake", "drowsy", "sleep")
] ]
grid = _states(labelled, prep.duration_s)
def state_at(t: np.ndarray) -> np.ndarray: def state_at(t: np.ndarray) -> np.ndarray:
"""The state of the first labelled window holding each time.""" out = np.full(len(t), "unlabelled", dtype=object)
out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool) index = np.floor(t / 0.5).astype(int)
for t0, t1, label in labelled: inside = (t >= 0) & (index < len(grid))
hit = open_ & (t0 <= t) & (t < t1) out[inside] = grid[index[inside]]
out[hit], open_ = label, open_ & ~hit
return out return out
gate = _gate(x, fs, intervals) gate, rejected = _gate(x, fs, intervals)
minutes = {} minutes = {}
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate])) middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
for (t0, t1), state in zip(gate, middles, strict=True): for (t0, t1), state in zip(gate, middles, strict=True):
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0 minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",))) sleep_minutes = float(minutes.get("sleep", 0.0))
awake_minutes = float(minutes.get("wake", 0.0) + minutes.get("drowsy", 0.0))
awake = 0
counts = dict.fromkeys(channels, 0) counts = dict.fromkeys(channels, 0)
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)] candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
if candidates and gate: if candidates and gate:
@@ -215,18 +253,22 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
if len(c): if len(c):
c = c.assign(field=_field(c), state=state_at(c.t.to_numpy())) c = c.assign(field=_field(c), state=state_at(c.t.to_numpy()))
found = _merge(c) found = _merge(c)
found = found[found.useful & (found.field > 0) & (found.state == "sleep")] found = found[found.useful & (found.field > 0)]
awake = int(found.state.isin(("wake", "drowsy")).sum())
found = found[found.state == "sleep"]
for channel, n in found.channel.value_counts().items(): for channel, n in found.channel.value_counts().items():
counts[channel] = int(n) counts[channel] = int(n)
rounded = round(sleep_minutes, 2) rate = round(sum(counts.values()) / sleep_minutes, 3) if sleep_minutes > 0 else np.nan
rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan awake_rate = round(awake / awake_minutes, 3) if awake_minutes > 0 else np.nan
electrodes = { electrodes = {
e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan
for e in ELECTRODES for e in ELECTRODES
} }
zones = {} zones, zone_electrodes = {}, {}
for zone, members in ZONES.items(): for zone, members in ZONES.items():
present = [e for e in members if e in counts] present = [e for e in members if e in counts]
zone_electrodes[zone] = len(present)
total = sum(counts[e] for e in present) total = sum(counts[e] for e in present)
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4)) return Spikes(rate, electrodes, zones, round(sleep_minutes, 4), rejected, awake_rate,
round(awake_minutes, 4), zone_electrodes) # fmt: skip
+23 -15
View File
@@ -1,10 +1,10 @@
"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the """Sleep spindles (NREM sleep, unstaged): their density, per zone, and the enhancement of the
sigma envelope per electrode. sigma envelope per electrode.
Detection runs on the frontal, central and parietal electrodes over the windows of the stage Detection runs on the frontal, central and parietal electrodes over the sleep windows (only when
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median), per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer from the sleep's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
envelope peaks 3 x over the median. envelope peaks 3 x over the median.
@@ -12,7 +12,8 @@ envelope peaks 3 x over the median.
Density: spindles per minute and searched channel (NaN when none were found); per zone, the Density: spindles per minute and searched channel (NaN when none were found); per zone, the
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
the episode ± 0.25 s, over the median envelope in sleep. the episode ± 0.25 s, over the median envelope in sleep. A posterior rhythm within 1.5 Hz of the
sigma band (`near_sigma`) is noted: its alpha can pass for spindles.
""" """
from dataclasses import dataclass from dataclasses import dataclass
@@ -25,6 +26,8 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz") CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
SIGMA = (11.0, 16.0) SIGMA = (11.0, 16.0)
RHYTHM_MARGIN_HZ = 1.5
MIN_MINUTES = 1
ZONES = { ZONES = {
"frontal_left": ("Fp1", "F3", "F7"), "frontal_left": ("Fp1", "F3", "F7"),
"frontal_right": ("Fp2", "F4", "F8"), "frontal_right": ("Fp2", "F4", "F8"),
@@ -41,7 +44,12 @@ ZONES = {
class Spindles: class Spindles:
events: list[tuple[float, float, str]] # (onset s, duration s, channel) events: list[tuple[float, float, str]] # (onset s, duration s, channel)
minutes: float minutes: float
channels: list[str] # the channels searched (none when under a minute of the stage) channels: list[str] # the channels searched (none when under a minute of sleep)
rhythm_near_sigma: bool = False
def near_sigma(posterior_rhythm: float) -> bool:
return bool(posterior_rhythm > SIGMA[0] - RHYTHM_MARGIN_HZ)
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
@@ -92,31 +100,31 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1] return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles: def detect(prep: Prepared, states: np.ndarray) -> Spindles:
"""The spindles in the grid windows staged `stage`.""" """The spindles in the grid windows in sleep."""
fs, n = prep.fs, int(WINDOW_S * prep.fs) fs, n = prep.fs, int(WINDOW_S * prep.fs)
asleep = np.zeros(len(prep.x), bool) asleep = np.zeros(len(prep.x), bool)
for start, s in zip(prep.starts, staged, strict=True): for start, state in zip(prep.starts, states, strict=True):
if s == stage: if state == "sleep":
a = int(round(float(start) * fs)) a = int(round(float(start) * fs))
asleep[a : a + n] = True asleep[a : a + n] = True
minutes = float(asleep.sum() / fs / 60) minutes = float(asleep.sum() / fs / 60)
names = prep.columns([c for c in prep.names if c in CHANNELS]) names = prep.columns([c for c in prep.names if c in CHANNELS])
if minutes < 1 or not names: if minutes < MIN_MINUTES or not names:
return Spindles([], minutes, []) return Spindles([], minutes, [])
x = prep.data(names) x = prep.data(names)
y, envelope = _envelope(x, fs) y, envelope = _envelope(x, fs)
events = [] events = []
for i, name in enumerate(names): for i, name in enumerate(names):
in_stage = np.where(asleep, envelope[:, i], np.nan) in_sleep = np.where(asleep, envelope[:, i], np.nan)
values = in_stage[np.isfinite(in_stage)] values = in_sleep[np.isfinite(in_sleep)]
if len(values) < fs * 30: if len(values) < fs * 30:
continue continue
median = float(np.median(values)) or 1e-9 median = float(np.median(values)) or 1e-9
core = max(float(np.percentile(values, 95)), 3 * median) core = max(float(np.percentile(values, 95)), 3 * median)
extent = max(float(np.percentile(values, 70)), 1.6 * median) extent = max(float(np.percentile(values, 70)), 1.6 * median)
finite = np.isfinite(in_stage) finite = np.isfinite(in_sleep)
for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs): for a, b in _segments(finite & (in_sleep > core), finite & (in_sleep > extent), fs):
if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3: if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3:
events.append((round(a / fs, 3), round((b - a) / fs, 3), name)) events.append((round(a / fs, 3), round((b - a) / fs, 3), name))
return Spindles(events, minutes, names) return Spindles(events, minutes, names)
+8 -7
View File
@@ -26,8 +26,8 @@ GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_r
class Baseline(mlflow.pyfunc.PythonModel): class Baseline(mlflow.pyfunc.PythonModel):
"""An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z, """An age curve as MLflow serves it: (value, age_months, exposure, electrodes) rows in,
outside, p5, median and p95 out, for one of its features.""" their z, outside, p5, median, p95 and reason out, for one of its features."""
def __init__(self, scenario: str, baseline: dict): def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = scenario, baseline self.scenario, self.baseline = scenario, baseline
@@ -36,7 +36,8 @@ class Baseline(mlflow.pyfunc.PythonModel):
feature = (params or {}).get("feature", "value") feature = (params or {}).get("feature", "value")
rows = model_input.to_dict("records") rows = model_input.to_dict("records")
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"), return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
r.get("age_months"), r.get("exposure")) r.get("age_months"), r.get("exposure"),
r.get("electrodes"))
for r in rows]) # fmt: skip for r in rows]) # fmt: skip
@@ -121,9 +122,8 @@ def _score_curve(name: str) -> int | None:
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None) metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
if metric is None: if metric is None:
continue continue
exposure = ( features = one["features"].get(name) or {}
(one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None exposure = features.get(curves.EXPOSURE) if scenario.counts else None
)
for part in scenario.parts: for part in scenario.parts:
sites = {"": metric["value"]} if part == "value" else metric[part] sites = {"": metric["value"]} if part == "value" else metric[part]
prefix = "" if part == "value" else curves.PREFIX[part] prefix = "" if part == "value" else curves.PREFIX[part]
@@ -131,7 +131,8 @@ def _score_curve(name: str) -> int | None:
feature = "value" if part == "value" else prefix + site feature = "value" if part == "value" else prefix + site
if feature not in baseline: if feature not in baseline:
continue continue
s = curves.score(baseline[feature], value, one["age_months"], exposure) electrodes = features.get(f"zone_electrodes_{site}") if part == "zones" else None
s = curves.score(baseline[feature], value, one["age_months"], exposure, electrodes)
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"], rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
"scenario": name, "model": label, "metric": scenario.metric, "scenario": name, "model": label, "metric": scenario.metric,
"part": part, "site": site or None, **s}) # fmt: skip "part": part, "site": site or None, **s}) # fmt: skip