274 lines
11 KiB
Python
274 lines
11 KiB
Python
"""One EEG through the `tea` library: validation, then preprocessing, the processes and the metrics' biomarkers.
|
|
|
|
`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age the
|
|
patient's rows give, touches no database and returns a `Measurement` with the verdict, every quality check and each
|
|
metric's raw value. The deviation from the age baselines is added afterwards (`baselines.py`), where the registered
|
|
models are.
|
|
|
|
The age is the EDF header's (recording start minus birth date) when the header has both, and the rows' otherwise:
|
|
the file is written when the study is recorded, the rows' birth date may be missing or mistyped.
|
|
|
|
The library reads EDFs from paths only, so the bytes go to a temporary file for the duration of the call.
|
|
"""
|
|
import logging
|
|
import re
|
|
import tempfile
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
from models.tea.eeg.settings import Settings
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
# Channel codes the library builds from the reason's first words, and the fixed code each is stored as.
|
|
CHANNEL_CODES = {"intermittent-contact-by": "intermittent-bursts"}
|
|
# Header and rows further apart than this, in months, are logged.
|
|
AGE_DISAGREEMENT_MONTHS = 1.0
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Check:
|
|
code: str
|
|
electrode: str | None
|
|
value: float | None
|
|
text: str | None
|
|
unit: str | None
|
|
low: float | None
|
|
high: float | None
|
|
decisive: bool
|
|
abnormal: bool
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class MetricValue:
|
|
code: str
|
|
value: float | None
|
|
electrodes: dict[str, float | None] = field(default_factory=dict)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Measurement:
|
|
key: str
|
|
age_months: float | None # the age the study was analysed at
|
|
plan_hash: str
|
|
versions: str
|
|
valid: int | None = None
|
|
level: str | None = None
|
|
clean_fraction: float | None = None
|
|
bad_channels: int | None = None
|
|
line_db: float | None = None
|
|
channels: int | None = None
|
|
duration_min: float | None = None
|
|
asleep: int | None = None
|
|
checks: tuple[Check, ...] = ()
|
|
metrics: tuple[MetricValue, ...] = ()
|
|
error: str | None = None
|
|
seconds: float = 0.0
|
|
|
|
|
|
def pipeline(settings: Settings):
|
|
from tea.pipeline import Pipeline
|
|
|
|
return Pipeline.default(impl=settings.impl)
|
|
|
|
|
|
def plan(settings: Settings) -> dict:
|
|
from tea.preprocessing import PLANS
|
|
|
|
return PLANS[settings.plan].to_dict()
|
|
|
|
|
|
def phase_detector(pipe, phase: str):
|
|
base = pipe.module("spindle_detection")
|
|
return type(base)(variant=base.variant, phase=phase)
|
|
|
|
|
|
def processes(pipe, settings: Settings) -> list[str]:
|
|
"""The processes the metrics need, in dependency order. Spindle detection itself runs once per sleep stage, so
|
|
the phased biomarkers contribute only what their stage's detector requires."""
|
|
from tea.pipeline.run_study import order_for
|
|
|
|
needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n]
|
|
requires = {r for n in needs for r in pipe.module(n).requires}
|
|
for phase in settings.phases:
|
|
requires.update(phase_detector(pipe, phase).requires)
|
|
return order_for(["metrics"], {**pipe.modules, "metrics": SimpleNamespace(requires=tuple(sorted(requires)))})
|
|
|
|
|
|
def versions(pipe, settings: Settings) -> str:
|
|
"""What produced an analysis, as `name=version;...`: a new version of any module analyses every EEG again."""
|
|
names = ["validation", "preprocessing", *processes(pipe, settings)]
|
|
if settings.phases:
|
|
names.append("spindle_detection")
|
|
names += settings.biomarkers
|
|
return ";".join(f"{n}={getattr(pipe.module(n), 'version', '?')}" for n in dict.fromkeys(names))
|
|
|
|
|
|
def criterion_code(code: str, text: str, electrode: str | None) -> str:
|
|
"""The library's channel codes are the first words of the reason, numbers included (`amplitude-4.5-x`)."""
|
|
if electrode is None:
|
|
return code
|
|
if code.startswith("amplitude"):
|
|
return "aux-amplitude" if "out of range" in text else "amplitude"
|
|
return CHANNEL_CODES.get(code, code)
|
|
|
|
|
|
def _number(value) -> float | None:
|
|
try:
|
|
number = float(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
return number if number == number else None
|
|
|
|
|
|
def checks(validation, run: dict) -> tuple[Check, ...]:
|
|
out = []
|
|
for c in validation.checks_of(run):
|
|
text = c.value if isinstance(c.value, str) else None
|
|
out.append(Check(
|
|
code=criterion_code(c.code, c.display, c.electrode), electrode=c.electrode,
|
|
value=None if text is not None else _number(c.value), text=text, unit=c.unit or None,
|
|
low=_number(c.low), high=_number(c.high), decisive=bool(c.decisive), abnormal=bool(c.abnormal),
|
|
))
|
|
return tuple(out)
|
|
|
|
|
|
def gate_reasons(summary, plan: dict) -> list[str]:
|
|
"""The plan's gates on top of the validator's verdict, as the library's own batch applies them."""
|
|
reasons = list(summary.extra.get("reasons", []))
|
|
gates = plan.get("gates", {})
|
|
if gates.get("skip_no_analizable", True) and summary.level == "no_analizable" and not reasons:
|
|
reasons.append("triage level no_analizable")
|
|
least = gates.get("min_clean")
|
|
if least is not None and summary.clean_fraction == summary.clean_fraction and summary.clean_fraction < least:
|
|
reasons.append(f"plan gate: {100 * summary.clean_fraction:.0f}% clean < {100 * least:.0f}%")
|
|
return reasons
|
|
|
|
|
|
Features = dict[tuple[str, str | None], dict[str, float | None]]
|
|
|
|
|
|
def features(pipe, study, settings: Settings) -> Features:
|
|
"""Every feature of each biomarker the metrics read, by biomarker and sleep stage (`None`: no stage), with
|
|
spindle detection run once per stage."""
|
|
by_phase = {None: study}
|
|
for phase in settings.phases:
|
|
by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study))
|
|
out: Features = {}
|
|
for m in settings.metrics:
|
|
for biomarker in (m.biomarker, m.electrodes):
|
|
if biomarker and (biomarker, m.phase) not in out:
|
|
out[biomarker, m.phase] = {k: _number(v) for k, v in
|
|
pipe.module(biomarker).measure(by_phase[m.phase]).items()}
|
|
return out
|
|
|
|
|
|
def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]:
|
|
out = []
|
|
for m in settings.metrics:
|
|
electrodes = {}
|
|
if m.electrodes:
|
|
electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items()
|
|
if name.startswith(m.electrode_prefix)}
|
|
out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes))
|
|
return tuple(out)
|
|
|
|
|
|
def _error(exc: Exception) -> str:
|
|
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
|
return f"{type(exc).__name__}: {message}"
|
|
|
|
|
|
def _study(pipe, path, settings: Settings, the_plan: dict, age_months: float | None, line_hz: float):
|
|
"""Validation, then, for a valid study, preprocessing and the processes: (validation run, summary, verdict,
|
|
study or None)."""
|
|
from tea.contracts import Study
|
|
|
|
validation = pipe.module("validation")
|
|
run = validation.run(path, line_hz=line_hz)
|
|
summary = validation.summary_of(run)
|
|
valid = int(bool(summary.valid) and not gate_reasons(summary, the_plan))
|
|
if not valid:
|
|
return run, summary, valid, None
|
|
preprocessing = pipe.module("preprocessing")
|
|
study = Study(preprocessing.run(path, preprocessing.plan_for(summary, the_plan), age_months=age_months))
|
|
for name in processes(pipe, settings):
|
|
study = study.with_labels(pipe.module(name).predict(study))
|
|
return run, summary, valid, study
|
|
|
|
|
|
def study_age(key: str, path: Path, row_age: float | None, days_per_month: float) -> float | None:
|
|
"""The header's age if it has one, else `row_age`. An unreadable header counts as none: validation reports the
|
|
file."""
|
|
from tea.contracts import header_age_months
|
|
|
|
try:
|
|
header = header_age_months(path, days_per_month=days_per_month)
|
|
except Exception: # noqa: BLE001
|
|
header = None
|
|
if header is None:
|
|
return row_age
|
|
if row_age is not None and abs(header - row_age) > AGE_DISAGREEMENT_MONTHS:
|
|
log.warning("EEG %s: the EDF header gives %.1f months and the patient's rows %.1f; using the header",
|
|
key, header, row_age)
|
|
return header
|
|
|
|
|
|
def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) -> Measurement:
|
|
"""`age_months` is the rows' age, used when the EDF header has none (`study_age`). Never raises: a failure is a
|
|
`Measurement` with `error` set, keeping the verdict and checks if validation finished before it."""
|
|
started = time.time()
|
|
pipe = pipeline(settings)
|
|
the_plan = plan(settings)
|
|
result = dict(key=key, age_months=age_months, plan_hash=the_plan.get("hash", ""), versions=versions(pipe, settings))
|
|
try:
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
path = Path(folder) / "study.edf"
|
|
path.write_bytes(edf)
|
|
result["age_months"] = age = study_age(key, path, age_months, settings.days_per_month)
|
|
validation = pipe.module("validation")
|
|
run, summary, valid, study = _study(pipe, path, settings, the_plan, age, settings.line_hz)
|
|
result.update(
|
|
valid=valid, level=summary.level, clean_fraction=_number(summary.clean_fraction),
|
|
bad_channels=len(summary.bad_channels), line_db=_number(summary.line_db),
|
|
channels=len(run.get("channels", [])) or None,
|
|
duration_min=round(run["duration_s"] / 60, 2) if run.get("duration_s") else None,
|
|
checks=checks(validation, run),
|
|
)
|
|
if study is None:
|
|
return Measurement(**result, seconds=round(time.time() - started, 1))
|
|
asleep = int((study.label("sleep_state").per_window == "sueno").any())
|
|
return Measurement(**result, asleep=asleep, metrics=_metrics(features(pipe, study, settings), settings),
|
|
seconds=round(time.time() - started, 1))
|
|
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop the batch
|
|
return Measurement(**result, error=_error(exc), seconds=round(time.time() - started, 1))
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ReferenceStudy:
|
|
"""One study of a reference cohort, measured for training: its age, verdict, and every feature of each
|
|
biomarker the metrics read, by biomarker and sleep stage. No path, file name or date."""
|
|
|
|
key: str
|
|
age_months: float
|
|
valid: int | None = None
|
|
features: Features = field(default_factory=dict)
|
|
error: str | None = None
|
|
|
|
|
|
def reference(key: str, path: str, age_months: float, settings: Settings, line_hz: float) -> ReferenceStudy:
|
|
"""A reference study read from a local or `s3://` path, at the mains frequency of the cohort's country. Never
|
|
raises: a failure is a `ReferenceStudy` with `error` set."""
|
|
from tea.pipeline.storage import local_copy
|
|
|
|
pipe = pipeline(settings)
|
|
try:
|
|
with local_copy(path) as local:
|
|
_, _, valid, study = _study(pipe, local, settings, plan(settings), age_months, line_hz)
|
|
measured = features(pipe, study, settings) if study is not None else {}
|
|
return ReferenceStudy(key, age_months, valid, measured)
|
|
except Exception as exc: # noqa: BLE001 -- one unreadable study must not stop the batch
|
|
return ReferenceStudy(key, age_months, error=_error(exc))
|