Files
models/models/tea/eeg/analysis.py
T

129 lines
4.6 KiB
Python

"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
analysis = analyze(edf_bytes, birth_date)
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
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
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
`error` set, keeping the verdict and checks when validation finished before it. Missing values
are None.
"""
import re
from dataclasses import dataclass, field
from datetime import date
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
from models.tea.eeg.curves import _number
DAYS_PER_MONTH = 30.4375
MAINS_HZ = 60.0
@dataclass(frozen=True)
class Metric:
code: str
value: float | None
electrodes: dict[str, float] = field(default_factory=dict) # None where not measured
zones: dict[str, float] = field(default_factory=dict)
@dataclass(frozen=True)
class Analysis:
valid: bool | None
level: str
age_months: float | None
clean_fraction: float | None
bad_channels: int | None
channels: int | None
duration_min: float | None
line_noise_db: float | None
sleep: bool | None
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes,
# anteroposterior_gradient
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
error: str | None
def _error(exc: Exception) -> str:
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}"
def analyze(
edf: bytes,
birth_date: date | None = None,
*,
age_months: float | None = None,
mains_hz: float = MAINS_HZ,
) -> Analysis:
"""`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`)."""
out = dict(
valid=None,
level=checks.NOT_ANALYZABLE,
age_months=age_months,
clean_fraction=None,
bad_channels=None,
channels=None,
duration_min=None,
line_noise_db=None,
sleep=None,
checks=[],
metrics=[],
features={},
error=None,
)
try:
try:
rec = read.read(edf)
except read.FileNotValid as exc:
verdict = checks.file_not_valid(str(exc))
return Analysis(
**out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks)
)
if age_months is None:
header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH)
given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH)
out["age_months"] = age = header if header is not None else given
else:
age = age_months
verdict = checks.validate(rec, mains_hz)
out.update(
valid=verdict.valid,
level=verdict.level,
clean_fraction=verdict.clean_pct / 100,
bad_channels=len(verdict.bad),
channels=len(rec.names) or None,
duration_min=round(rec.duration_s / 60, 2),
line_noise_db=_number(verdict.line_db),
checks=verdict.checks,
)
if not verdict.valid:
return Analysis(**out)
prep = preprocess.prepare(rec, verdict.bad)
notes = sleep.note_intervals(prep.annotations, prep.duration_s)
states = sleep.states(prep, notes, age)
staged = sleep.stages(prep, states)
metrics, features = biomarkers.measure(prep, states, staged, notes)
out.update(
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
return Analysis(**out | dict(error=_error(exc)))