TEA: ADOS-2 association job, EEG zone values, spike minutes as exposure and the count baselines' reference range; tea library 0.3.0
This commit is contained in:
+1
-1
Submodule libs/tea updated: 05ee02990c...24e7824fe7
@@ -171,6 +171,21 @@ def _tea_analyze(args: argparse.Namespace) -> int:
|
||||
return 1 if s.failed else 0
|
||||
|
||||
|
||||
def _tea_relate_ados2(args: argparse.Namespace) -> int:
|
||||
"""The ADOS-2 association fitted on the analysed EEGs (`models.ados2_relation`)."""
|
||||
from models.ados2_relation import relate
|
||||
|
||||
s = relate()
|
||||
if s.unchanged:
|
||||
print(f"{s.children} children: the cohort is that of {s.version}, nothing written")
|
||||
elif s.version is None:
|
||||
print(f"{s.children} children: no association could be estimated, nothing written")
|
||||
else:
|
||||
print(f"{s.version}: {s.children} children, level {s.level}, {s.associations} associations, "
|
||||
f"{s.scored} patient probabilities")
|
||||
return 0
|
||||
|
||||
|
||||
def _tea_export_baselines(args: argparse.Namespace) -> int:
|
||||
"""The trained age baselines as one bundle (`models.tea.eeg.bundle`)."""
|
||||
from models.tea.eeg.bundle import BundleError, export
|
||||
@@ -521,6 +536,9 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
|
||||
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
|
||||
analyze.set_defaults(run=_tea_analyze)
|
||||
relate_ados2 = tea_actions.add_parser(
|
||||
"relate-ados2", help="fit the ADOS-2 association on the analysed EEGs and store it as a new version")
|
||||
relate_ados2.set_defaults(run=_tea_relate_ados2)
|
||||
export_baselines = tea_actions.add_parser(
|
||||
"export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child")
|
||||
export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)")
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""The ADOS-2 association against the TEA database: the cohort from bronze, the `tea` library's fit, and its rows in
|
||||
`relacion_ados2` and `relacion_ados2_paciente`.
|
||||
|
||||
The cohort is one row per child with a valid analysed EEG and an ADOS-2: the child's first valid EEG with some
|
||||
predictor (its zone z and metric z, its age) and first ADOS-2 (module, item scores, CSS). Every valid EEG of those
|
||||
children is then scored, so the study's EEG has its probabilities whichever EEG it is.
|
||||
|
||||
A fit is a version `tea-<UTC time>-<fingerprint>`: the time keeps versions in order (the gold view shows the
|
||||
greatest), the fingerprint is that of the scored EEGs, which of them the fit used, and the module and level. Inputs
|
||||
equal to the latest version's write nothing. Versions are
|
||||
written unvalidated (`rel_validado` 0) until the domain expert validates them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
from sqlmodel import Session, col, select
|
||||
|
||||
from core.tea.enums import NivelRelacionAdos2
|
||||
from core.tea.models import (
|
||||
ADOS2_ITEMS,
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaZona,
|
||||
RelacionAdos2,
|
||||
RelacionAdos2Paciente,
|
||||
)
|
||||
from models.tea.ados2.settings import Settings, settings
|
||||
|
||||
VERSION_PREFIX = "tea-"
|
||||
LEVELS = {"item": NivelRelacionAdos2.ITEM.value, "domain": NivelRelacionAdos2.DOMINIO.value}
|
||||
ZONED = ("spikes", "spindles")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Summary:
|
||||
version: str | None = None
|
||||
level: str | None = None
|
||||
children: int = 0
|
||||
associations: int = 0
|
||||
scored: int = 0
|
||||
unchanged: bool = False
|
||||
|
||||
|
||||
def _predictors(session: Session, eeg_ids: list[str], s: Settings) -> pd.DataFrame:
|
||||
"""One row per EEG with a column per predictor: `z_<biomarker>_<zone>` and `z_<biomarker>`."""
|
||||
codes = {code: b for b, code in s.biomarkers.items()}
|
||||
metrics = session.exec(select(EegMetrica.met_id, EegMetrica.met_eeg_id, EegMetrica.met_codigo, EegMetrica.met_z)
|
||||
.where(col(EegMetrica.met_eeg_id).in_(eeg_ids))
|
||||
.where(col(EegMetrica.met_codigo).in_(list(codes)))).all()
|
||||
values: dict[str, dict[str, float]] = {e: {} for e in eeg_ids}
|
||||
zoned = {}
|
||||
for met_id, eeg_id, code, z in metrics:
|
||||
biomarker = codes[code]
|
||||
if biomarker in ZONED:
|
||||
zoned[met_id] = (eeg_id, biomarker)
|
||||
elif z is not None:
|
||||
values[eeg_id][f"z_{biomarker}"] = z
|
||||
if zoned:
|
||||
for met_id, zone, z in session.exec(select(EegMetricaZona.mez_met_id, EegMetricaZona.mez_zona,
|
||||
EegMetricaZona.mez_z)
|
||||
.where(col(EegMetricaZona.mez_met_id).in_(list(zoned)))).all():
|
||||
if z is not None:
|
||||
eeg_id, biomarker = zoned[met_id]
|
||||
values[eeg_id][f"z_{biomarker}_{zone}"] = z
|
||||
return pd.DataFrame.from_dict(values, orient="index")
|
||||
|
||||
|
||||
def cohort(session: Session, s: Settings) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""The fit's cohort (the first valid EEG of each child with an ADOS-2) and the table to score (every valid EEG
|
||||
of those children), both keyed by EEG id, in the library's columns."""
|
||||
eegs = session.exec(select(Eeg.eeg_id, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio, Eeg.eeg_edad_meses)
|
||||
.where(Eeg.eeg_valido == 1).where(col(Eeg.eeg_edad_meses).is_not(None))).all()
|
||||
ados = session.exec(select(Ados2).where(col(Ados2.ado_pac_id).is_not(None))).all()
|
||||
first: dict[int, Ados2] = {}
|
||||
for a in sorted(ados, key=lambda a: (a.ado_fecha is None, a.ado_fecha, a.ado_id)):
|
||||
first.setdefault(a.ado_pac_id, a)
|
||||
rows = []
|
||||
for eeg_id, pac_id, fecha, edad in eegs:
|
||||
a = first.get(pac_id)
|
||||
if a is None:
|
||||
continue
|
||||
rows.append({"key": eeg_id, "pac_id": pac_id, "fecha": fecha, "age_months": float(edad),
|
||||
"ados_module": a.ado_modulo, "css": a.ado_css,
|
||||
**{code: getattr(a, f"ado_{code}") for code in ADOS2_ITEMS}})
|
||||
columns = ["key", "pac_id", "fecha", "age_months", "ados_module", "css", *ADOS2_ITEMS]
|
||||
scored = pd.DataFrame(rows, columns=columns)
|
||||
if len(scored):
|
||||
z = _predictors(session, scored["key"].tolist(), s)
|
||||
scored = scored.join(z, on="key")
|
||||
scored = scored.sort_values(["pac_id", "fecha", "key"], na_position="last").reset_index(drop=True)
|
||||
predictors = [c for c in scored.columns if c.startswith("z_")]
|
||||
with_predictors = scored[predictors].notna().any(axis=1) if predictors else pd.Series(False, index=scored.index)
|
||||
fit = scored[with_predictors].drop_duplicates("pac_id").reset_index(drop=True)
|
||||
return fit.drop(columns=["pac_id", "fecha"]), scored.drop(columns=["pac_id", "fecha"])
|
||||
|
||||
|
||||
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
|
||||
"""Eight hex digits of the scored EEGs, which of them the fit used, and `module` (name, version, level);
|
||||
independent of row and column order."""
|
||||
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
|
||||
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
|
||||
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
|
||||
return hashlib.sha256(text.encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
def _latest(session: Session) -> str | None:
|
||||
versions = session.exec(select(RelacionAdos2.rel_version)
|
||||
.where(col(RelacionAdos2.rel_version).startswith(VERSION_PREFIX))).all()
|
||||
return max(versions, default=None)
|
||||
|
||||
|
||||
def _finite(value) -> float | None:
|
||||
"""The value as a float, or none when missing or infinite (an open interval): not every engine stores inf."""
|
||||
if value is None or pd.isna(value):
|
||||
return None
|
||||
value = float(value)
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
def _row_id(*parts) -> str:
|
||||
from models.eeg_analysis import row_id
|
||||
|
||||
return row_id("relacion-ados2", *parts)
|
||||
|
||||
|
||||
def rows(module, version: str, associations: pd.DataFrame, scores: pd.DataFrame,
|
||||
s: Settings) -> tuple[list[RelacionAdos2], list[RelacionAdos2Paciente]]:
|
||||
"""The estimated associations as `relacion_ados2` rows and their scores as `relacion_ados2_paciente` rows."""
|
||||
level = LEVELS[module.fitted["level"]]
|
||||
# An odds ratio rounded to 0 or never estimated is no association to show (`rel_or` is above 0).
|
||||
estimated = associations[associations["odds_ratio"].astype(float) > 0]
|
||||
models, ids = [], {}
|
||||
for a in estimated.itertuples():
|
||||
rel_id = _row_id(version, a.biomarker, a.zone, a.outcome_code)
|
||||
ids[a.biomarker, a.zone, a.outcome_code] = rel_id
|
||||
models.append(RelacionAdos2(
|
||||
rel_id=rel_id, rel_version=version, rel_nivel=level, rel_validado=0,
|
||||
rel_n_cohorte=int(module.fitted["n"]), rel_biomarcador=s.biomarkers[a.biomarker], rel_zona=a.zone,
|
||||
rel_tipo=LEVELS[a.kind], rel_resultado=a.outcome_code, rel_evento=a.event, rel_or=_finite(a.odds_ratio),
|
||||
rel_ic_inf=_finite(a.ci_low), rel_ic_sup=_finite(a.ci_high), rel_q=_finite(a.q)))
|
||||
patients = []
|
||||
for r in scores.itertuples():
|
||||
rel_id = ids.get((r.biomarker, r.zone, r.outcome_code))
|
||||
if rel_id is None:
|
||||
continue
|
||||
patients.append(RelacionAdos2Paciente(
|
||||
rap_id=_row_id(rel_id, r.key), rap_rel_id=rel_id, rap_eeg_id=r.key, rap_valor_z=float(r.z),
|
||||
rap_probabilidad=float(r.probability), rap_probabilidad_referencia=float(r.reference_probability)))
|
||||
return models, patients
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def relate(*, settings_: Settings | None = None, at: datetime | None = None) -> Summary:
|
||||
"""Fits the association on the current cohort and writes it as a new version, unless the cohort is the latest
|
||||
version's. Nothing is written when no association could be estimated."""
|
||||
from tea.pipeline import registry
|
||||
|
||||
from persistance.tea import relacion_ados2_repository
|
||||
|
||||
s = settings_ or settings()
|
||||
with relacion_ados2_repository.open_session() as session:
|
||||
fit, scored = cohort(session, s)
|
||||
summary = Summary(children=len(fit))
|
||||
if not len(fit):
|
||||
return summary
|
||||
module = type(registry.association(s.association, s.impl))(level=s.level)
|
||||
mark = fingerprint(fit, scored, f"{module.name}/{module.version}/{module.impl}/{s.level}")
|
||||
latest = _latest(session)
|
||||
if latest is not None and latest.endswith(f"-{mark}"):
|
||||
return Summary(version=latest, children=len(fit), unchanged=True)
|
||||
module.fit(fit)
|
||||
version = f"{VERSION_PREFIX}{(at or _now()):%Y%m%dT%H%M%S}-{mark}"
|
||||
models, patients = rows(module, version, module.associations(), module.score(scored), s)
|
||||
summary.level = module.fitted["level"]
|
||||
if not models:
|
||||
return summary
|
||||
session.add_all([*models, *patients])
|
||||
session.commit()
|
||||
summary.version, summary.associations, summary.scored = version, len(models), len(patients)
|
||||
return summary
|
||||
+23
-10
@@ -4,8 +4,8 @@ An EEG is pending when it has an EDF and was never analysed, or was analysed wit
|
||||
versions, or, being valid, against baselines other than those now in production. One that failed with the current
|
||||
plan and versions waits for a new one instead of failing again on every run.
|
||||
|
||||
Each result replaces the EEG's previous checks, metrics and electrode values in `eeg`, `eeg_criterio`,
|
||||
`eeg_metrica` and `eeg_metrica_electrodo`. Row ids derive from the EEG and what each row is, so a row keeps its id
|
||||
Each result replaces the EEG's previous checks, metrics, electrode and zone values in `eeg`, `eeg_criterio`,
|
||||
`eeg_metrica`, `eeg_metrica_electrodo` and `eeg_metrica_zona`. Row ids derive from the EEG and what each row is, so a row keeps its id
|
||||
from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with
|
||||
its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished.
|
||||
|
||||
@@ -20,11 +20,11 @@ from datetime import datetime, timedelta, timezone
|
||||
from sqlmodel import Session, col, delete, select
|
||||
|
||||
from core.tea.enums import MetricaEeg
|
||||
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
|
||||
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, EegMetricaZona, Pacientes
|
||||
|
||||
from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
from models.tea.eeg.settings import Settings, settings as model_settings
|
||||
from models.tea.eeg.settings import Settings, scenario_of, settings as model_settings
|
||||
|
||||
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
|
||||
|
||||
@@ -83,6 +83,7 @@ class Rows:
|
||||
criteria: list[EegCriterio]
|
||||
metrics: list[EegMetrica]
|
||||
electrodes: list[EegMetricaElectrodo]
|
||||
zones: list[EegMetricaZona]
|
||||
|
||||
|
||||
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
|
||||
@@ -108,23 +109,34 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None
|
||||
))
|
||||
|
||||
by_code = {metric.code: metric for metric in s.metrics}
|
||||
metrics, electrodes = [], []
|
||||
metrics, electrodes, zones = [], [], []
|
||||
for value in m.metrics:
|
||||
metric = by_code[value.code]
|
||||
met_id = row_id(m.key, "metrica", value.code)
|
||||
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months)
|
||||
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months, value.exposure)
|
||||
used = [metric.scenario] if deviation is not None else []
|
||||
for electrode, raw in sorted(value.electrodes.items()):
|
||||
at_electrode = None
|
||||
if metric.electrode_scenario:
|
||||
at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode,
|
||||
raw, m.age_months)
|
||||
raw, m.age_months, value.exposure)
|
||||
if at_electrode is not None and metric.electrode_scenario not in used:
|
||||
used.append(metric.electrode_scenario)
|
||||
electrodes.append(EegMetricaElectrodo(
|
||||
mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode,
|
||||
mel_valor=raw, mel_z=at_electrode.z if at_electrode else None,
|
||||
))
|
||||
for zone, raw in sorted(value.zones.items()):
|
||||
at_zone = None
|
||||
if metric.zone_scenario:
|
||||
at_zone = baselines.deviation(metric.zone_scenario, metric.zone_prefix + zone, raw, m.age_months,
|
||||
value.exposure)
|
||||
if at_zone is not None and metric.zone_scenario not in used:
|
||||
used.append(metric.zone_scenario)
|
||||
zones.append(EegMetricaZona(
|
||||
mez_id=row_id(m.key, "metrica", value.code, "zona", zone), mez_met_id=met_id, mez_zona=zone,
|
||||
mez_valor=raw, mez_z=at_zone.z if at_zone else None,
|
||||
))
|
||||
metrics.append(EegMetrica(
|
||||
met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value,
|
||||
met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None,
|
||||
@@ -132,7 +144,7 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None
|
||||
met_p95=deviation.p95 if deviation else None,
|
||||
met_modelo=";".join(baselines.label(scenario) for scenario in used) or None,
|
||||
))
|
||||
return Rows(eeg, criteria, metrics, electrodes)
|
||||
return Rows(eeg, criteria, metrics, electrodes, zones)
|
||||
|
||||
|
||||
def save(session: Session, eeg_id: str, new: Rows) -> None:
|
||||
@@ -145,10 +157,11 @@ def save(session: Session, eeg_id: str, new: Rows) -> None:
|
||||
session.add(eeg)
|
||||
metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id)
|
||||
session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids)))
|
||||
session.exec(delete(EegMetricaZona).where(col(EegMetricaZona.mez_met_id).in_(metric_ids)))
|
||||
session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id))
|
||||
session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id))
|
||||
session.flush()
|
||||
session.add_all([*new.criteria, *new.metrics, *new.electrodes])
|
||||
session.add_all([*new.criteria, *new.metrics, *new.electrodes, *new.zones])
|
||||
|
||||
|
||||
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
|
||||
@@ -181,7 +194,7 @@ class Summary:
|
||||
def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]:
|
||||
out = {}
|
||||
for m in s.metrics:
|
||||
scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario]
|
||||
scenarios = [scenario_of(n, m.phase) for n in m.readers]
|
||||
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
|
||||
return out
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
"""TEA's models: the EEG analysis (`eeg`)."""
|
||||
"""TEA's models: the EEG analysis (`eeg`) and the ADOS-2 association (`ados2`)."""
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
"""TEA's ADOS-2 association: the `tea` library module and the metrics it reads (`model.toml`); fitted on the
|
||||
database by `models.ados2_relation`."""
|
||||
@@ -0,0 +1,13 @@
|
||||
# The ADOS-2 association: the `tea` library's cohort-level module, and the stored EEG metric each of its biomarkers
|
||||
# reads. Spike and spindle predictors are the metric's zone z (`eeg_metrica_zona`); the posterior rhythm and the
|
||||
# gradient are the metric's own z (`eeg_metrica.met_z`).
|
||||
association = "ados2_association"
|
||||
impl = "modern"
|
||||
# "auto": by item when the cohort has ADOS-2 item scores, by the CSS otherwise; or "item", "domain".
|
||||
level = "auto"
|
||||
|
||||
[biomarkers]
|
||||
spikes = "PICOS_PAROXISTICOS"
|
||||
spindles = "HUSOS_SUENO_N2"
|
||||
posterior_rhythm = "RITMO_POSTERIOR"
|
||||
gradient = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
@@ -0,0 +1,20 @@
|
||||
"""The ADOS-2 association's settings (`model.toml`): the library module, its implementation and level, and the
|
||||
stored EEG metric each of its biomarkers reads."""
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
association: str
|
||||
impl: str
|
||||
level: str
|
||||
biomarkers: dict[str, str] # library biomarker -> `MetricaEeg` code
|
||||
|
||||
|
||||
@cache
|
||||
def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings:
|
||||
raw = tomllib.loads(path.read_text())
|
||||
return Settings(raw["association"], raw["impl"], raw["level"], dict(raw["biomarkers"]))
|
||||
+17
-11
@@ -46,6 +46,8 @@ class MetricValue:
|
||||
code: str
|
||||
value: float | None
|
||||
electrodes: dict[str, float | None] = field(default_factory=dict)
|
||||
zones: dict[str, float | None] = field(default_factory=dict)
|
||||
exposure: float | None = None # what a count baseline divides the value, electrodes and zones by
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -90,7 +92,7 @@ def processes(pipe, settings: Settings) -> list[str]:
|
||||
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]
|
||||
needs = [n for m in settings.metrics if not m.phase for n in m.readers]
|
||||
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)
|
||||
@@ -158,22 +160,26 @@ def features(pipe, study, settings: Settings) -> Features:
|
||||
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:
|
||||
for biomarker in m.readers:
|
||||
if (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 _prefixed(measured: Features, biomarker: str | None, phase: str | None, prefix: str) -> dict[str, float | None]:
|
||||
"""The features of `biomarker` whose name starts with `prefix`, by the rest of the name."""
|
||||
if not biomarker:
|
||||
return {}
|
||||
return {name.removeprefix(prefix): v for name, v in measured[biomarker, phase].items() if name.startswith(prefix)}
|
||||
|
||||
|
||||
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)
|
||||
return tuple(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature),
|
||||
_prefixed(measured, m.electrodes, m.phase, m.electrode_prefix),
|
||||
_prefixed(measured, m.zones, m.phase, m.zone_prefix),
|
||||
measured[m.biomarker, m.phase].get(m.exposure) if m.exposure else None)
|
||||
for m in settings.metrics)
|
||||
|
||||
|
||||
def _error(exc: Exception) -> str:
|
||||
|
||||
@@ -47,9 +47,15 @@ def _load(model_uri: str):
|
||||
sys.path[:] = path
|
||||
|
||||
|
||||
def _takes_exposure(baseline) -> bool:
|
||||
import inspect
|
||||
|
||||
return "exposure" in inspect.signature(baseline.deviation).parameters
|
||||
|
||||
|
||||
def _feature_baseline(module, feature: str):
|
||||
baselines = getattr(module, "baselines", None)
|
||||
return baselines[feature] if baselines is not None else module.baseline
|
||||
return baselines.get(feature) if baselines is not None else module.baseline
|
||||
|
||||
|
||||
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
|
||||
@@ -103,16 +109,30 @@ class Baselines:
|
||||
self._loaded[scenario] = _load(resolved.model_uri)
|
||||
return self._loaded[scenario]
|
||||
|
||||
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None:
|
||||
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None,
|
||||
exposure: float | None = None) -> Deviation | None:
|
||||
"""None without a baseline in production; with one, a deviation whose fields are null where the value or
|
||||
the age is missing or the curve doesn't cover the age."""
|
||||
the age is missing or the curve doesn't cover the age. `exposure` reaches a baseline that takes one (a count
|
||||
against its minutes), whose p5, median and p95 are then the rates expected in those minutes; the others
|
||||
ignore it."""
|
||||
module = self.module(scenario)
|
||||
if module is None:
|
||||
return None
|
||||
baseline = _feature_baseline(module, feature)
|
||||
if baseline is None:
|
||||
return None
|
||||
if value is None or age_months is None:
|
||||
return Deviation(None, None, None, None, None)
|
||||
outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float))
|
||||
args = (np.array([value], float), np.array([age_months], float))
|
||||
minutes = np.array([np.nan if exposure is None else exposure], float)
|
||||
if _takes_exposure(baseline):
|
||||
outside, z = baseline.deviation(*args, exposure=minutes)
|
||||
else:
|
||||
outside, z = baseline.deviation(*args)
|
||||
z_value = _number(z[0])
|
||||
p5, median, p95 = centiles(baseline, age_months)
|
||||
return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95)
|
||||
if hasattr(baseline, "percentiles"):
|
||||
p5, median, p95 = (_number(v) for v in baseline.percentiles(args[1], minutes)[0])
|
||||
else:
|
||||
p5, median, p95 = centiles(baseline, age_months)
|
||||
outside_value = _number(outside[0])
|
||||
return Deviation(z_value, int(outside_value) if outside_value is not None else None, p5, median, p95)
|
||||
|
||||
@@ -18,7 +18,10 @@ line_hz = 50.0
|
||||
ages = [16.0, 36.0]
|
||||
|
||||
# One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the
|
||||
# biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode.
|
||||
# biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode, and `zones` the
|
||||
# one whose `<zone_prefix><zone>` features are its value per scalp zone (`tea.contracts.ZONES`), which the ADOS-2
|
||||
# association reads. `exposure` names the feature a count baseline divides by: spikes are counted against the
|
||||
# minutes they were looked for in, since most children of the reference have none.
|
||||
# The feature each metric maps to is provisional until the domain expert confirms it.
|
||||
[[metrics]]
|
||||
code = "RITMO_POSTERIOR"
|
||||
@@ -32,6 +35,8 @@ phase = "N2"
|
||||
feature = "spindle_density_per_min_channel"
|
||||
electrodes = "spindle_topography"
|
||||
electrode_prefix = "topo_enh_"
|
||||
zones = "spindles"
|
||||
zone_prefix = "spindle_zone_"
|
||||
|
||||
[[metrics]]
|
||||
code = "HUSOS_SUENO_N3"
|
||||
@@ -40,11 +45,18 @@ phase = "N3"
|
||||
feature = "spindle_density_per_min_channel"
|
||||
electrodes = "spindle_topography"
|
||||
electrode_prefix = "topo_enh_"
|
||||
zones = "spindles"
|
||||
zone_prefix = "spindle_zone_"
|
||||
|
||||
[[metrics]]
|
||||
code = "PICOS_PAROXISTICOS"
|
||||
biomarker = "spikes"
|
||||
feature = "spike_rate_nrem"
|
||||
electrodes = "spikes"
|
||||
electrode_prefix = "spike_density_nrem_"
|
||||
zones = "spikes"
|
||||
zone_prefix = "spike_zone_rate_nrem_"
|
||||
exposure = "spike_minutes_nrem"
|
||||
|
||||
[[metrics]]
|
||||
code = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
|
||||
@@ -17,6 +17,9 @@ class Metric:
|
||||
phase: str | None = None
|
||||
electrodes: str | None = None
|
||||
electrode_prefix: str = ""
|
||||
zones: str | None = None
|
||||
zone_prefix: str = ""
|
||||
exposure: str | None = None # the biomarker's feature a count baseline divides by (its minutes)
|
||||
|
||||
@property
|
||||
def scenario(self) -> str:
|
||||
@@ -26,6 +29,15 @@ class Metric:
|
||||
def electrode_scenario(self) -> str | None:
|
||||
return scenario_of(self.electrodes, self.phase) if self.electrodes else None
|
||||
|
||||
@property
|
||||
def zone_scenario(self) -> str | None:
|
||||
return scenario_of(self.zones, self.phase) if self.zones else None
|
||||
|
||||
@property
|
||||
def readers(self) -> tuple[str, ...]:
|
||||
"""The biomarkers the metric reads: its own, its electrodes' and its zones'."""
|
||||
return tuple(dict.fromkeys(n for n in (self.biomarker, self.electrodes, self.zones) if n))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reference:
|
||||
@@ -55,13 +67,13 @@ class Settings:
|
||||
@property
|
||||
def scenarios(self) -> dict[str, tuple[str, str | None]]:
|
||||
"""Each baseline to train, by scenario: (biomarker, sleep stage)."""
|
||||
pairs = [(n, m.phase) for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
|
||||
pairs = [(n, m.phase) for m in self.metrics for n in m.readers]
|
||||
return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)}
|
||||
|
||||
@property
|
||||
def biomarkers(self) -> tuple[str, ...]:
|
||||
"""Every biomarker a metric reads, its own or its electrodes'."""
|
||||
names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
|
||||
"""Every biomarker a metric reads, its own, its electrodes' or its zones'."""
|
||||
names = [n for m in self.metrics for n in m.readers]
|
||||
return tuple(dict.fromkeys(names))
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""An invented ADOS-2 association cohort: one row per child in the `tea` library's cohort columns, with two planted
|
||||
effects (spikes in temporal_izq raise item 18, spindles in central lower the CSS) and everything else null."""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from tea.associations.ados2 import _items as items
|
||||
from tea.contracts import ZONES
|
||||
|
||||
ITEM_CODES = sorted({c for _, _, codes in items.ITEMS.values() for c in codes.values()})
|
||||
|
||||
|
||||
def cohort(n: int = 60, seed: int = 4, with_items: bool = True) -> pd.DataFrame:
|
||||
rng = np.random.default_rng(seed)
|
||||
age = rng.uniform(16, 37, n).round(1)
|
||||
module = np.where(age < 31, "TODDLER", np.where(rng.random(n) < .7, "MODULO_1", "MODULO_2"))
|
||||
t = pd.DataFrame({"key": [f"e-{i:03d}" for i in range(n)], "age_months": age, "ados_module": module})
|
||||
shared = rng.normal(0, 1, n)
|
||||
for zone in ZONES:
|
||||
t[f"z_spikes_{zone}"] = (.5 * shared + .85 * rng.normal(0, 1, n)).round(3)
|
||||
t[f"z_spindles_{zone}"] = rng.normal(0, 1, n).round(3)
|
||||
t["z_posterior_rhythm"] = rng.normal(0, 1, n).round(3)
|
||||
t["z_gradient"] = rng.normal(0, 1, n).round(3)
|
||||
for number, (_, _, codes) in items.ITEMS.items():
|
||||
latent = rng.logistic(0, 1, n) + (1.6 * t["z_spikes_temporal_izq"].to_numpy() if number == 18 else 0)
|
||||
level = np.digitize(latent, [-.3, 1.4, 3.2])
|
||||
for m, code in codes.items():
|
||||
if code not in t:
|
||||
t[code] = np.nan
|
||||
t.loc[t.ados_module == m, code] = level[t.ados_module.to_numpy() == m]
|
||||
severity = rng.normal(0, 1, n) - .9 * t["z_spindles_central"].to_numpy()
|
||||
t["css"] = np.clip(np.round(6 + 1.8 * severity), 1, 10).astype(int)
|
||||
for code in ITEM_CODES:
|
||||
if code not in t:
|
||||
t[code] = np.nan
|
||||
return t if with_items else t.drop(columns=ITEM_CODES)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""What this module covers: the `tea` library's ADOS-2 association (`tea.associations.ados2`, modern, and
|
||||
`tea.legacy.associations.ados2`, the research code vendored): the pairs it tests, the module-independent outcome
|
||||
codes, recovery of planted effects, legacy and modern agreeing, the per-child scores and the saved state.
|
||||
|
||||
Fixtures: `cohort_items`, 60 invented children of 16 to 37 months (Toddler module under 31 months, Module 1 or 2
|
||||
above) with item scores and a CSS, whose spike z in temporal_izq raises item 18 (intonation) and whose spindle z in
|
||||
central lowers the CSS, everything else null; `cohort_css`, the same children without item scores; `fits`, both
|
||||
implementations fitted once on each cohort.
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from ados2_cohort import ITEM_CODES, cohort
|
||||
|
||||
from tea.associations.ados2 import Ados2Association
|
||||
from tea.associations.ados2 import _items as items
|
||||
from tea.contracts import ASSOCIATION_COLUMNS, SCORE_COLUMNS, ZONES
|
||||
from tea.legacy.associations.ados2 import LegacyAdos2Association
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cohort_items():
|
||||
"""60 children with item scores: spikes in temporal_izq raise item 18, spindles in central lower the CSS."""
|
||||
return cohort()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cohort_css(cohort_items):
|
||||
"""The same children with the CSS only, as when the psychologist reports no items."""
|
||||
return cohort_items.drop(columns=[c for c in ITEM_CODES if c in cohort_items])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fits(cohort_items, cohort_css):
|
||||
"""Modern and legacy, each fitted once on both cohorts, by (impl, level)."""
|
||||
return {(impl, level): cls().fit(c) for impl, cls in (("modern", Ados2Association),
|
||||
("legacy", LegacyAdos2Association))
|
||||
for level, c in (("item", cohort_items), ("domain", cohort_css))}
|
||||
|
||||
|
||||
def test_level_follows_the_cohort_and_codes_are_module_independent(fits):
|
||||
"""Pins down: a cohort with items is fitted by item and one without by the CSS; item outcomes carry
|
||||
`ados2_item_NN` and domain outcomes `CSS`, with events `>=1` and `>=8`; zones are the library's, `posterior`
|
||||
or `global`. Fails if the level stops following the data, an outcome goes back to a per-module column code (one
|
||||
code is another item in another module), or a zone code leaves the shared list."""
|
||||
for impl in ("modern", "legacy"):
|
||||
assert fits[impl, "item"].fitted["level"] == "item"
|
||||
assert fits[impl, "domain"].fitted["level"] == "domain"
|
||||
a = fits[impl, "item"].associations()
|
||||
assert list(a.columns) == list(ASSOCIATION_COLUMNS)
|
||||
assert set(a.outcome_code) <= {items.item_code(n) for n in items.ITEMS} | {"CSS"}
|
||||
assert set(a.loc[a.kind == "item", "event"]) == {">=1"}
|
||||
assert set(a.loc[a.kind == "domain", "event"]) == {">=8"}
|
||||
assert set(a.zone) <= set(ZONES) | {"posterior", "global"}
|
||||
assert set(fits[impl, "domain"].associations().outcome_code) == {"CSS"}
|
||||
|
||||
|
||||
def test_the_planted_effects_are_found(fits):
|
||||
"""Pins down: the item fit finds spikes in temporal_izq raising item 18 (odds ratio above 1, q < 0.05) and the CSS
|
||||
fit finds spindles in central lowering the CSS (odds ratio below 1, q < 0.05). Fails if the Firth or ordinal fit,
|
||||
the item read per module, or the q values break."""
|
||||
a = fits["modern", "item"].associations().set_index(["biomarker", "zone", "outcome_code"])
|
||||
item = a.loc[("spikes", "temporal_izq", "ados2_item_18")]
|
||||
assert item.odds_ratio > 1 and item.q < .05
|
||||
d = fits["modern", "domain"].associations().set_index(["biomarker", "zone", "outcome_code"])
|
||||
css = d.loc[("spindles", "central", "CSS")]
|
||||
assert css.odds_ratio < 1 and css.q < .05
|
||||
|
||||
|
||||
@pytest.mark.parametrize("level", ["item", "domain"])
|
||||
def test_legacy_and_modern_agree(fits, cohort_items, cohort_css, level):
|
||||
"""Pins down: the modern port gives the vendored research code's odds ratios, intervals, p, q and per-child
|
||||
probabilities exactly, at both levels. Fails if either side's design matrix, fit, interval search, FLIC
|
||||
intercept or pair list drifts from the other."""
|
||||
cohort = cohort_items if level == "item" else cohort_css
|
||||
m, legacy = fits["modern", level], fits["legacy", level]
|
||||
keys = ["biomarker", "zone", "outcome_code"]
|
||||
joined = m.associations().merge(legacy.associations(), on=keys, suffixes=("_m", "_l"), validate="1:1")
|
||||
assert len(joined) == len(m.associations()) == len(legacy.associations())
|
||||
for c in ("odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio"):
|
||||
np.testing.assert_allclose(joined[f"{c}_m"].astype(float), joined[f"{c}_l"].astype(float), rtol=1e-9)
|
||||
scores = m.score(cohort).merge(legacy.score(cohort), on=["key", *keys], suffixes=("_m", "_l"), validate="1:1")
|
||||
assert len(scores) == len(legacy.score(cohort)) > 0
|
||||
np.testing.assert_allclose(scores.probability_m, scores.probability_l, atol=1e-9)
|
||||
np.testing.assert_allclose(scores.reference_probability_m, scores.reference_probability_l, atol=1e-9)
|
||||
|
||||
|
||||
def test_an_item_is_read_from_the_column_of_the_childs_module(cohort_items):
|
||||
"""Pins down: item 11 (showing) is `sa_b12` in the Toddler module, `sa_b9` in Module 1 and `sa_b5` in Module 2,
|
||||
and each child's score comes from its own module's column, with 3 as 2 and 7 as 0. Fails if items are read by
|
||||
one column code for every module."""
|
||||
t = pd.DataFrame({"ados_module": ["TODDLER", "MODULO_1", "MODULO_2", "MODULO_2"],
|
||||
"sa_b12": [1, 2, 0, 0], "sa_b9": [0, 3, 0, 0], "sa_b5": [2, 0, 7, np.nan]})
|
||||
assert items.item_scores(t, 11).tolist()[:3] == [1.0, 2.0, 0.0]
|
||||
assert np.isnan(items.item_scores(t, 11).iloc[3])
|
||||
|
||||
|
||||
def test_scores_cover_only_the_modules_with_the_item_and_survive_save_and_load(fits, cohort_items, tmp_path):
|
||||
"""Pins down: a child is scored on an item only when its module has that item, every score row has a z and a
|
||||
probability in [0, 1], and a saved and reloaded fit scores the same. Fails if scoring ignores the module, the
|
||||
saved state misses what scoring needs, or the columns drift from `SCORE_COLUMNS`."""
|
||||
m = fits["modern", "item"]
|
||||
scores = m.score(cohort_items)
|
||||
assert list(scores.columns) == list(SCORE_COLUMNS)
|
||||
modules = cohort_items.set_index("key").ados_module
|
||||
item_16 = scores[scores.outcome_code == "ados2_item_16"] # Module 2 only
|
||||
assert set(modules[item_16.key]) <= {"MODULO_2"}
|
||||
assert scores.probability.between(0, 1).all() and scores.z.notna().all()
|
||||
m.save(tmp_path)
|
||||
again = Ados2Association.load(tmp_path).score(cohort_items)
|
||||
pd.testing.assert_frame_equal(scores, again)
|
||||
|
||||
|
||||
def test_registered_under_the_association_groups():
|
||||
"""Pins down: both implementations resolve through the entry points and pass the association protocol, and
|
||||
the per-study pipeline does not load them. Fails if a registration is dropped or the association lands in the
|
||||
pipeline's module groups."""
|
||||
from tea.pipeline import registry
|
||||
|
||||
assert registry.association("ados2_association").impl == "modern"
|
||||
assert registry.association("ados2_association", "legacy").impl == "legacy"
|
||||
assert "ados2_association" not in registry.available("modern")
|
||||
|
||||
|
||||
def test_a_module_the_fit_never_saw_is_not_scored_as_the_reference(fits, cohort_items):
|
||||
"""Pins down: a child whose module was not in the pair's fit (here an unknown `MODULO_3`) gets no probability
|
||||
instead of the reference module's. Fails if unseen levels fall back to all-zero indicators."""
|
||||
m = fits["modern", "domain"]
|
||||
other = cohort_items.head(3).assign(ados_module="MODULO_3", key=["x-1", "x-2", "x-3"])
|
||||
assert m.score(other).empty
|
||||
|
||||
|
||||
def test_a_singular_pair_or_an_infinite_z_does_not_stop_the_fit(cohort_css):
|
||||
"""Pins down: a predictor equal to the module indicator (a rank-deficient design) leaves that pair with a reason
|
||||
and no estimate while every other pair is fitted, and an infinite z is dropped rather than fitted. Fails if a
|
||||
singular information matrix aborts the whole fit, or `inf` reaches the design."""
|
||||
t = cohort_css.copy()
|
||||
t["z_gradient"] = (t["ados_module"] == "TODDLER").astype(float)
|
||||
t.loc[0, "z_posterior_rhythm"] = np.inf
|
||||
a = Ados2Association().fit(t).associations().set_index(["biomarker", "zone"])
|
||||
assert a["odds_ratio"].notna().sum() >= len(a) - 2
|
||||
assert a.loc[("posterior_rhythm", "posterior"), "n"] == len(t) - 1
|
||||
@@ -0,0 +1,140 @@
|
||||
"""What this module covers: the ADOS-2 association against the TEA database (`models.ados2_relation`): the cohort
|
||||
it builds from bronze (first valid EEG and first ADOS-2 per child), the rows it writes to `relacion_ados2` and
|
||||
`relacion_ados2_paciente`, and versions (a new cohort is a later version, the same cohort writes nothing).
|
||||
|
||||
Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, the invented cohort of `ados2_cohort` without item
|
||||
scores (60 children, spindles in central lowering the CSS) written to bronze: each child with an ADOS-2 and a valid
|
||||
analysed EEG `e-NNN` whose metric z and zone z are the cohort's, plus a later valid EEG `e-000-b` of child 1, an
|
||||
invalid EEG of child 2 and a child 99 with an EEG and no ADOS-2.
|
||||
"""
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from ados2_cohort import ITEM_CODES, cohort
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from core.tea.models import Ados2, Eeg, EegMetrica, EegMetricaZona, Pacientes, RelacionAdos2, RelacionAdos2Paciente
|
||||
from models import ados2_relation as rel
|
||||
from tea.contracts import ZONES
|
||||
|
||||
CODES = {"spikes": "PICOS_PAROXISTICOS", "spindles": "HUSOS_SUENO_N2", "posterior_rhythm": "RITMO_POSTERIOR",
|
||||
"gradient": "GRADIENTE_ANTEROPOSTERIOR"}
|
||||
|
||||
|
||||
def _eeg(session, eeg_id, pac_id, row, *, studied=date(2025, 6, 1), valid=1):
|
||||
session.add(Eeg(eeg_id=eeg_id, eeg_pac_id=pac_id, eeg_fecha_estudio=studied, eeg_valido=valid,
|
||||
eeg_edad_meses=float(row.age_months)))
|
||||
for biomarker, code in CODES.items():
|
||||
met_id = f"{eeg_id}/{code}"
|
||||
zoned = biomarker in rel.ZONED
|
||||
session.add(EegMetrica(met_id=met_id, met_eeg_id=eeg_id, met_codigo=code,
|
||||
met_z=None if zoned else float(row[f"z_{biomarker}"])))
|
||||
if zoned:
|
||||
session.add_all([EegMetricaZona(mez_id=f"{met_id}/{z}", mez_met_id=met_id, mez_zona=z,
|
||||
mez_z=float(row[f"z_{biomarker}_{z}"])) for z in ZONES])
|
||||
|
||||
|
||||
def _engine():
|
||||
from persistance.db import get_tea_engine
|
||||
|
||||
return get_tea_engine()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stored(tea_db):
|
||||
"""The CSS-only invented cohort in bronze, with the extra EEGs and child the module docstring lists."""
|
||||
t = cohort().drop(columns=ITEM_CODES)
|
||||
with Session(_engine()) as s:
|
||||
for i, row in t.iterrows():
|
||||
pac_id = i + 1
|
||||
s.add(Pacientes(pac_id=pac_id, pac_id_hospital=f"H-{pac_id}"))
|
||||
s.add(Ados2(ado_id=f"a-{pac_id}", ado_pac_id=pac_id, ado_fecha=date(2025, 5, 1),
|
||||
ado_modulo=row.ados_module, ado_css=int(row.css)))
|
||||
_eeg(s, row.key, pac_id, row)
|
||||
_eeg(s, "e-000-b", 1, t.iloc[0], studied=date(2025, 9, 1))
|
||||
_eeg(s, "e-001-x", 2, t.iloc[1], studied=date(2025, 3, 1), valid=0)
|
||||
s.add(Pacientes(pac_id=99, pac_id_hospital="H-99"))
|
||||
_eeg(s, "e-099", 99, t.iloc[2])
|
||||
s.commit()
|
||||
return t
|
||||
|
||||
|
||||
def _read():
|
||||
with Session(_engine()) as s:
|
||||
return s.exec(select(RelacionAdos2)).all(), s.exec(select(RelacionAdos2Paciente)).all()
|
||||
|
||||
|
||||
def test_a_fit_writes_one_version_of_estimated_rows_on_the_platform_codes(stored):
|
||||
"""Pins down: one fit writes a `tea-<time>-<fingerprint>` version, unvalidated, over the 60 children with a
|
||||
valid EEG and an ADOS-2, with the metric codes, `CSS` outcomes and an `>=8` event, and finds the planted
|
||||
spindle effect in central. Fails if the cohort takes the child without ADOS-2 or the invalid EEG, the
|
||||
biomarker codes stop following `model.toml`, or the written estimates stop being the library's."""
|
||||
summary = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
models, patients = _read()
|
||||
assert summary.children == 60 and summary.level == "domain"
|
||||
assert summary.version.startswith("tea-20261121T120000-") and len(summary.version) <= 32
|
||||
assert {m.rel_version for m in models} == {summary.version} and len(models) == summary.associations
|
||||
assert {m.rel_validado for m in models} == {0} and {m.rel_n_cohorte for m in models} == {60}
|
||||
assert {m.rel_resultado for m in models} == {"CSS"} and {m.rel_evento for m in models} == {">=8"}
|
||||
assert {m.rel_biomarcador for m in models} <= set(CODES.values())
|
||||
central = next(m for m in models if m.rel_biomarcador == "HUSOS_SUENO_N2" and m.rel_zona == "central")
|
||||
assert central.rel_or < 1 and central.rel_q < .05
|
||||
assert len(patients) == summary.scored
|
||||
|
||||
|
||||
def test_every_valid_eeg_of_the_cohort_is_scored_and_no_other(stored):
|
||||
"""Pins down: child 1's later valid EEG gets probabilities too (the gold view shows the study's EEG, whichever
|
||||
it is), while the invalid EEG and the EEG of the child without ADOS-2 get none. Fails if scoring stops at the
|
||||
fit's EEGs or starts scoring outside the cohort."""
|
||||
rel.relate()
|
||||
_, patients = _read()
|
||||
eegs = {p.rap_eeg_id for p in patients}
|
||||
assert {"e-000", "e-000-b"} <= eegs
|
||||
assert not {"e-001-x", "e-099"} & eegs
|
||||
assert all(0 <= p.rap_probabilidad <= 1 and 0 <= p.rap_probabilidad_referencia <= 1 for p in patients)
|
||||
|
||||
|
||||
def test_the_same_cohort_writes_nothing_and_a_new_one_is_a_later_version(stored):
|
||||
"""Pins down: fitting the same cohort again writes nothing and names the latest version; a changed z is a new
|
||||
version that sorts after the first, so the gold view's greatest version is the newest fit. Fails if reruns
|
||||
duplicate versions, or the version stops sorting by time."""
|
||||
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
again = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
||||
assert again.unchanged and again.version == first.version
|
||||
assert len({m.rel_version for m in _read()[0]}) == 1
|
||||
with Session(_engine()) as s:
|
||||
zone = s.get(EegMetricaZona, "e-000/HUSOS_SUENO_N2/central")
|
||||
zone.mez_z = 3.0
|
||||
s.add(zone)
|
||||
s.commit()
|
||||
later = rel.relate(at=datetime(2026, 11, 23, 12, 0, 0))
|
||||
assert not later.unchanged and later.version > first.version
|
||||
assert {m.rel_version for m in _read()[0]} == {first.version, later.version}
|
||||
|
||||
|
||||
def test_an_open_interval_is_stored_as_null():
|
||||
"""Pins down: an infinite interval limit (the profile never crossed the threshold) is stored as NULL, which every
|
||||
engine accepts. Fails if `inf` reaches the database (MySQL and SQL Server reject it)."""
|
||||
assert rel._finite(float("inf")) is None and rel._finite(None) is None and rel._finite(2.5) == 2.5
|
||||
|
||||
|
||||
def test_the_fit_uses_the_first_eeg_with_predictors_and_a_new_eeg_is_a_new_version(stored):
|
||||
"""Pins down: a child whose earliest valid EEG has no metric rows is fitted on its next EEG, and a valid EEG
|
||||
added for a child already in the fit (so the fit table is the same) is still a new version that scores it.
|
||||
Fails if the fit takes an EEG without predictors (the child would drop out of every model), or the fingerprint
|
||||
covers only the fit table (the new EEG would stay unscored)."""
|
||||
with Session(_engine()) as s:
|
||||
s.add(Eeg(eeg_id="e-000-a", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 1, 1), eeg_valido=1,
|
||||
eeg_edad_meses=20.0))
|
||||
s.commit()
|
||||
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
||||
assert first.children == 60
|
||||
assert "e-000-a" not in {p.rap_eeg_id for p in _read()[1]}
|
||||
with Session(_engine()) as s:
|
||||
_eeg(s, "e-000-c", 1, stored.iloc[0], studied=date(2025, 12, 1))
|
||||
s.commit()
|
||||
later = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
||||
assert not later.unchanged and later.version > first.version
|
||||
models, patients = _read()
|
||||
latest = {m.rel_id for m in models if m.rel_version == later.version}
|
||||
assert "e-000-c" in {p.rap_eeg_id for p in patients if p.rap_rel_id in latest}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Outside markers for centile and age-block references in modern and legacy tea.
|
||||
|
||||
Fixtures: parameterized baseline modules and in-memory synthetic control values.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from tea.biomarkers.spindles import _baseline as modern
|
||||
from tea.legacy.biomarkers.spindles import _baseline as legacy
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", (modern, legacy))
|
||||
def test_centile_outside_requires_a_reference(baseline):
|
||||
"""Pin float -1/0/+1 and missing values. Fails if missing data, uncovered ages or sparse controls give zero."""
|
||||
curve = baseline.CentileCurves().fit(np.tile([1, 2, 3], 50), np.repeat([12, 24, 36], 50))
|
||||
outside, _ = curve.deviation([0, 2, 4, np.nan, 2, 2], [24, 24, 24, 24, 60, np.nan])
|
||||
assert outside.dtype.kind == "f"
|
||||
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan, np.nan])
|
||||
sparse = baseline.CentileCurves().fit([1, 2], [12, 36])
|
||||
assert np.isnan(sparse.deviation([2], [24])[0][0])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", (modern, legacy))
|
||||
def test_age_block_outside_requires_a_z_score(baseline):
|
||||
"""Pin float markers with a valid score. Fails if a missing score or degenerate MAD is classified in range."""
|
||||
fitted = baseline.AgeBlockZ().fit(np.arange(30), np.full(30, 24))
|
||||
outside, _ = fitted.deviation([-2, 15, 40, np.nan, 15], [24, 24, 24, 24, np.nan])
|
||||
assert outside.dtype.kind == "f"
|
||||
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan])
|
||||
flat = baseline.AgeBlockZ().fit(np.ones(30), np.full(30, 24))
|
||||
assert np.isnan(flat.deviation([1], [24])[0][0])
|
||||
@@ -144,7 +144,34 @@ def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves)
|
||||
(1, "tea-eeg-posterior-rhythm/3")
|
||||
assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None
|
||||
electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo))
|
||||
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"))
|
||||
mapped = [m.code for m in settings().metrics if m.electrodes]
|
||||
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in mapped)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ("uncovered_age", "missing_cutoffs"))
|
||||
def test_missing_reference_stores_null_outside(bronze, curves, case):
|
||||
"""Pin SQL NULL when a reference interval is absent. Fails if a missing marker is cast to int or stored as zero."""
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
age = 60.0
|
||||
if case == "missing_cutoffs":
|
||||
from tea.biomarkers.posterior_rhythm._baseline import AgeBlockZ
|
||||
|
||||
age = 26.0
|
||||
reference = AgeBlockZ().fit([5.0, 6.0, 7.0], [age] * 3)
|
||||
reference.state["cortes"] = [float("nan")] * 2
|
||||
curves.module("eeg-posterior-rhythm").baseline = reference
|
||||
|
||||
measurement = fake_measure("e-1", b"edf", age, settings())
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, "e-1", rows(measurement, settings(), curves))
|
||||
session.commit()
|
||||
metric = next(row for row in _all(EegMetrica) if row.met_codigo == "RITMO_POSTERIOR")
|
||||
assert metric.met_valor == 9.0
|
||||
assert metric.met_modelo == "tea-eeg-posterior-rhythm/3"
|
||||
assert metric.met_fuera is None
|
||||
if case == "missing_cutoffs":
|
||||
assert metric.met_z == pytest.approx(3.0 / 1.4826)
|
||||
|
||||
|
||||
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""What this module covers: the zone values of the EEG analysis (`models.tea.eeg.settings` zones,
|
||||
`analyze._metrics`, `models.eeg_analysis.rows` and `save`): which metrics read zones, how a biomarker's
|
||||
`<zone_prefix><zone>` features become a metric's zones, and the `eeg_metrica_zona` rows with the z of the zone's
|
||||
baseline, replaced on the next analysis.
|
||||
|
||||
Fixtures: `tea_db` (an empty SQLite TEA database); `spike_zones`, `Baselines` whose only production version is
|
||||
`tea-eeg-spikes/2`, a spikes module with one centile curve, 0.5/1/2 spikes per minute at p5/median/p95 at every age,
|
||||
for `spike_zone_rate_nrem_temporal_izq` alone.
|
||||
"""
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from core.tea.models import Eeg, EegMetrica, EegMetricaZona, Pacientes
|
||||
from models.eeg_analysis import rows, save
|
||||
from models.tea.eeg.analyze import Measurement, MetricValue, _metrics
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
from models.tea.eeg.settings import settings
|
||||
from tea.contracts import ZONES
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def spike_zones():
|
||||
"""Spikes in production with a curve for the temporal_izq zone feature only."""
|
||||
from tea.biomarkers.spikes._baseline import CentileCurves
|
||||
|
||||
curve = pd.DataFrame({"edad_meses": [12.0, 36.0], "n_efectivo": [50.0] * 2, "p5": [0.5] * 2, "p25": [0.8] * 2,
|
||||
"mediana": [1.0] * 2, "p75": [1.4] * 2, "p95": [2.0] * 2})
|
||||
module = SimpleNamespace(baselines={"spike_zone_rate_nrem_temporal_izq": CentileCurves(curva=curve)})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="2", model_uri="models:/tea-eeg-spikes/2")
|
||||
|
||||
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
|
||||
|
||||
|
||||
def test_spikes_and_spindles_read_zones_and_their_scenarios_are_trained():
|
||||
"""Pins down: the spike metric reads `spike_zone_rate_nrem_<zone>` and the per-electrode `spike_density_nrem_<E>`
|
||||
from spikes with `spike_minutes_nrem` as exposure, both spindle metrics read `spindle_zone_<zone>` from spindles
|
||||
at their stage, and no scenario is added for them (the zone features train with the metric's own biomarker).
|
||||
Fails if `model.toml` loses the zones the ADOS-2 association reads, or zones start a scenario of their own."""
|
||||
s = settings()
|
||||
by_code = {m.code: m for m in s.metrics}
|
||||
spikes = by_code["PICOS_PAROXISTICOS"]
|
||||
assert (spikes.zones, spikes.zone_prefix, spikes.electrodes, spikes.electrode_prefix) == (
|
||||
"spikes", "spike_zone_rate_nrem_", "spikes", "spike_density_nrem_")
|
||||
assert spikes.exposure == "spike_minutes_nrem"
|
||||
assert spikes.zone_scenario == spikes.scenario == "eeg-spikes"
|
||||
for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"):
|
||||
assert (by_code[code].zones, by_code[code].zone_prefix) == ("spindles", "spindle_zone_")
|
||||
assert set(s.scenarios) == {"eeg-posterior-rhythm", "eeg-spindles-n2", "eeg-spindles-n3",
|
||||
"eeg-spindle-topography-n2", "eeg-spindle-topography-n3", "eeg-spikes",
|
||||
"eeg-gradient"}
|
||||
|
||||
|
||||
def test_a_biomarkers_zone_features_become_the_metrics_zones():
|
||||
"""Pins down: the features named `<zone_prefix><zone>` are the metric's zones by zone code, the electrode map
|
||||
keeps its own prefix, and a feature whose name only starts like the prefix's biomarker is left out. Fails if
|
||||
the prefix is not stripped or zone and electrode features mix."""
|
||||
s = settings()
|
||||
spikes = {"spike_rate_nrem": 0.7, "spike_density_nrem_T3": 1.2,
|
||||
**{f"spike_zone_rate_nrem_{z}": float(i) for i, z in enumerate(ZONES)},
|
||||
"spike_zone_rate_awake_central": 9.0, "spike_minutes_nrem": 12.5}
|
||||
measured = {("posterior_rhythm", None): {}, ("spindles", "N2"): {}, ("spindles", "N3"): {},
|
||||
("spindle_topography", "N2"): {}, ("spindle_topography", "N3"): {}, ("spikes", None): spikes,
|
||||
("gradient", None): {}}
|
||||
value = {v.code: v for v in _metrics(measured, s)}["PICOS_PAROXISTICOS"]
|
||||
assert value.value == 0.7
|
||||
assert value.electrodes == {"T3": 1.2}
|
||||
assert value.zones == {z: float(i) for i, z in enumerate(ZONES)}
|
||||
assert value.exposure == 12.5
|
||||
|
||||
|
||||
def test_zone_rows_carry_the_zone_baselines_z_and_are_replaced(tea_db, spike_zones):
|
||||
"""Pins down: each zone of a metric is an `eeg_metrica_zona` row of that metric, with the z of the zone's own
|
||||
curve where one is in production and null elsewhere, and a new analysis replaces them. Fails if zone rows are
|
||||
not written, read another feature's baseline, or pile up across analyses."""
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
s = settings()
|
||||
with eeg_repository.open_session() as session:
|
||||
session.add_all([Pacientes(pac_id=1), Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1))])
|
||||
session.commit()
|
||||
zones = {"temporal_izq": 2.0, "central": 1.0}
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {}, zones if x.code == "PICOS_PAROXISTICOS" else {})
|
||||
for x in s.metrics))
|
||||
for _ in range(2):
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, "e-1", rows(m, s, spike_zones))
|
||||
session.commit()
|
||||
with eeg_repository.open_session() as session:
|
||||
found = {z.mez_zona: z for z in session.exec(select(EegMetricaZona)).all()}
|
||||
met_id = session.exec(select(EegMetrica.met_id).where(EegMetrica.met_codigo == "PICOS_PAROXISTICOS")).one()
|
||||
assert set(found) == {"temporal_izq", "central"}
|
||||
assert {z.mez_met_id for z in found.values()} == {met_id}
|
||||
assert found["temporal_izq"].mez_z == pytest.approx(1.645) and found["temporal_izq"].mez_valor == 2.0
|
||||
assert found["central"].mez_z is None
|
||||
|
||||
|
||||
def test_a_count_baseline_gets_the_metrics_minutes(tea_db):
|
||||
"""Pins down: a baseline whose `deviation` takes `exposure` gets the metric's minutes for the value, every
|
||||
electrode and every zone, and one without that parameter is called as before. Fails if the minutes stop reaching
|
||||
count baselines (spike z would be computed against no exposure) or curves start receiving them."""
|
||||
import numpy as np
|
||||
|
||||
seen = []
|
||||
|
||||
class Count:
|
||||
def deviation(self, values, ages_months, exposure=None):
|
||||
seen.append(float(exposure[0]))
|
||||
return np.array([0.0]), np.array([1.0])
|
||||
|
||||
module = SimpleNamespace(baselines={"spike_rate_nrem": Count(), "spike_density_nrem_T3": Count(),
|
||||
"spike_zone_rate_nrem_central": Count()})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
|
||||
|
||||
s = settings()
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {"T3": 0.5}, {"central": 0.2}, 12.5)
|
||||
if x.code == "PICOS_PAROXISTICOS" else MetricValue(x.code, 1.0)
|
||||
for x in s.metrics))
|
||||
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
|
||||
assert seen == [12.5, 12.5, 12.5]
|
||||
assert [z.mez_z for z in out.zones] == [1.0] and [e.mel_z for e in out.electrodes] == [1.0]
|
||||
|
||||
|
||||
def test_a_count_baselines_range_is_its_own_for_the_minutes(tea_db):
|
||||
"""Pins down: a baseline with `percentiles` gives the metric's p5, median and p95 from the metric's minutes, and
|
||||
the metric row stores them, so a spike metric with a z has a reference range. Fails if count baselines lose their
|
||||
range (the patient summary then refuses the EEG: a metric with a z and no reference)."""
|
||||
import numpy as np
|
||||
|
||||
class Count:
|
||||
def deviation(self, values, ages_months, exposure=None):
|
||||
return np.array([0.0]), np.array([0.5])
|
||||
|
||||
def percentiles(self, ages_months, exposure):
|
||||
return np.array([[0.0, 0.1, 0.4]]) * 10 / exposure[0]
|
||||
|
||||
module = SimpleNamespace(baselines={"spike_rate_nrem": Count()})
|
||||
|
||||
class Registry:
|
||||
def resolve(self, domain, scenario):
|
||||
if scenario != "eeg-spikes":
|
||||
raise LookupError(scenario)
|
||||
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
|
||||
|
||||
s = settings()
|
||||
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
|
||||
metrics=tuple(MetricValue(x.code, 1.0, {}, {}, 20.0) if x.code == "PICOS_PAROXISTICOS"
|
||||
else MetricValue(x.code, 1.0) for x in s.metrics))
|
||||
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
|
||||
spikes = next(r for r in out.metrics if r.met_codigo == "PICOS_PAROXISTICOS")
|
||||
assert (spikes.met_p5, spikes.met_mediana, spikes.met_p95) == (0.0, 0.05, 0.2)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""What this module covers: the spikes biomarker's baselines around the per-electrode and
|
||||
per-zone features: training from a feature table that predates them, and loading a baseline
|
||||
saved before they existed. Both implementations, modern and legacy.
|
||||
|
||||
Fixtures: `old_table`, a DataFrame with only the original seven study-wide spikes features and
|
||||
an age column, as a reference cohort measured before the density features existed; `full_table`,
|
||||
the same rows plus every current feature.
|
||||
"""
|
||||
import importlib
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
ORIGINAL = ("spike_rate_awake", "spike_rate_nrem", "spike_nrem_activation", "spike_focus_frac",
|
||||
"spike_laterality", "spike_frac_generalized", "spike_index_nrem")
|
||||
MODULES = (("tea.biomarkers.spikes.api", "Spikes"),
|
||||
("tea.legacy.biomarkers.spikes.api", "LegacySpikes"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def old_table():
|
||||
"""Twelve synthetic children with only the study-wide spikes features and their ages."""
|
||||
rng = np.random.default_rng(0)
|
||||
t = pd.DataFrame({f: rng.uniform(0.0, 2.0, size=12) for f in ORIGINAL})
|
||||
t["age_months"] = np.linspace(16.0, 36.0, 12)
|
||||
return t
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def full_table(old_table):
|
||||
"""`old_table` plus every per-electrode, per-zone and inherited feature the module has now."""
|
||||
rng = np.random.default_rng(1)
|
||||
t = old_table.copy()
|
||||
cls = getattr(importlib.import_module(MODULES[0][0]), MODULES[0][1])
|
||||
for f in cls.features:
|
||||
if f not in t.columns:
|
||||
t[f] = rng.uniform(0.0, 2.0, size=len(t))
|
||||
return t
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_training_skips_features_the_table_lacks(path, name, old_table, tmp_path):
|
||||
"""Pins down: training from a table without the new columns works, fits only the columns
|
||||
it has, and saving then loading that baseline keeps predicting those features only.
|
||||
|
||||
Fails if `train` starts requiring the new columns, or if save/load stops round-tripping
|
||||
a baseline that knows nothing about them.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
module = cls().train(old_table)
|
||||
out = module.predict(old_table)
|
||||
assert set(out.feature) == set(ORIGINAL)
|
||||
module.save(tmp_path)
|
||||
loaded = cls.load(tmp_path)
|
||||
assert set(loaded.predict(old_table).feature) == set(ORIGINAL)
|
||||
assert len(cls.features) > len(ORIGINAL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_a_baseline_saved_before_the_new_features_loads_and_predicts(path, name, old_table,
|
||||
full_table, tmp_path):
|
||||
"""Pins down: a baseline bundle written before the new features existed (no new
|
||||
parameters in params.json, none of the new features in baseline.json) loads into the
|
||||
current module and predicts; the new features simply have no baseline and are not
|
||||
evaluated.
|
||||
|
||||
Fails if load starts requiring the new parameters, if a saved baseline stops being
|
||||
readable after the feature list grows, or if predict evaluates a feature that has no
|
||||
fitted baseline.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
cls().train(old_table).save(tmp_path)
|
||||
params = json.loads((tmp_path / "params.json").read_text())
|
||||
for k in ("vent_s", "rechazar_transitorio", "herencia_s"):
|
||||
params.pop(k, None)
|
||||
(tmp_path / "params.json").write_text(json.dumps(params))
|
||||
loaded = cls.load(tmp_path)
|
||||
out = loaded.predict(full_table)
|
||||
assert set(out.feature) == set(ORIGINAL)
|
||||
assert len(out) == len(full_table) * len(ORIGINAL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,name", MODULES)
|
||||
def test_a_full_baseline_round_trips(path, name, full_table, tmp_path):
|
||||
"""Pins down: with every column present, train fits all features and save/load predicts
|
||||
the same deviations.
|
||||
|
||||
Fails if the per-electrode and per-zone features stop getting their own baselines when
|
||||
the training table has them.
|
||||
"""
|
||||
cls = getattr(importlib.import_module(path), name)
|
||||
module = cls().train(full_table)
|
||||
before = module.predict(full_table)
|
||||
assert set(before.feature) == set(cls.features)
|
||||
module.save(tmp_path)
|
||||
after = cls.load(tmp_path).predict(full_table)
|
||||
pd.testing.assert_frame_equal(before, after)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""What this module covers: the count reference of spike candidates (`_baseline.CountRate` of both spikes modules)
|
||||
and how `Spikes` / `LegacySpikes` use it: the aggregate rate and its dispersion, a child's z from the tail of its
|
||||
own count in its own minutes, NaN without exposure, the per-electrode zone scale, and which features it serves.
|
||||
|
||||
Fixtures: `count_rate`, parametrized over the modern and legacy `CountRate` classes; `reference`, 200 invented
|
||||
children of 16 to 36 months with 5 to 15 clean NREM minutes and Poisson candidates at 0.02 per minute (most have
|
||||
none), as rates.
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from scipy import stats
|
||||
|
||||
from tea.biomarkers.spikes import _baseline as modern_baseline
|
||||
from tea.biomarkers.spikes import api as modern
|
||||
from tea.legacy.biomarkers.spikes import _baseline as legacy_baseline
|
||||
from tea.legacy.biomarkers.spikes import api as legacy
|
||||
|
||||
|
||||
@pytest.fixture(params=["modern", "legacy"])
|
||||
def count_rate(request):
|
||||
"""The implementation's `CountRate` class."""
|
||||
return {"modern": modern_baseline, "legacy": legacy_baseline}[request.param].CountRate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reference():
|
||||
"""(rates, ages, minutes) of 200 children with Poisson candidates at 0.02 per minute."""
|
||||
rng = np.random.default_rng(3)
|
||||
minutes = rng.uniform(5, 15, 200).round(2)
|
||||
counts = rng.poisson(0.02 * minutes)
|
||||
return counts / minutes, rng.uniform(16, 36, 200), minutes
|
||||
|
||||
|
||||
def test_the_reference_is_the_aggregate_rate_with_its_dispersion(count_rate):
|
||||
"""Pins down: the rate is all candidates over all minutes of the children within the ages (one child of 50
|
||||
months left out) and the dispersion is the research code's moments estimate, Poisson (inf) without excess.
|
||||
Fails if the rate becomes a mean of per-child rates, the age range stops filtering, or the moments change."""
|
||||
rates = np.array([0, 0.1, 0.2, 0])
|
||||
b = count_rate().fit(rates, np.array([20, 20, 30, 50.0]), exposure=np.array([10, 10, 20, 30.0]))
|
||||
assert b.state["rate"] == pytest.approx(5 / 40) and b.state["reference"] == 3 and b.state["events"] == 5
|
||||
n, mu = np.array([0, 1, 4]), 5 / 40 * np.array([10, 10, 20])
|
||||
excess = ((n - mu) ** 2 - n).sum()
|
||||
assert b.state["k"] == (pytest.approx((mu ** 2).sum() / excess) if excess > 0 else np.inf)
|
||||
flat = count_rate().fit(np.array([0.1, 0.1]), np.array([20, 20.0]), exposure=np.array([10, 10.0]))
|
||||
assert flat.state["k"] == np.inf
|
||||
|
||||
|
||||
def test_a_count_is_judged_in_its_own_minutes(count_rate, reference):
|
||||
"""Pins down: no candidates is a mildly negative z (never -inf), the same one candidate is rarer in fewer
|
||||
minutes, many candidates in few minutes are outside +1 with a large z, and z is the normal quantile of the mid-p
|
||||
tail. Fails if z stops using the child's minutes, the mid-p correction, or the 0.05 cut for `outside`."""
|
||||
b = count_rate().fit(*reference[:2], exposure=reference[2])
|
||||
outside, z = b.deviation(np.array([0.0, 1 / 5, 1 / 40, 8 / 5]), np.full(4, 24.0),
|
||||
exposure=np.array([10.0, 5.0, 40.0, 5.0]))
|
||||
assert -1 < z[0] < 0
|
||||
assert z[1] > z[2]
|
||||
assert outside.tolist() == [0.0, 0.0, 0.0, 1.0] and z[3] > 3
|
||||
mu = b.state["rate"] * 5.0
|
||||
tail = stats.poisson.sf(0, mu) if np.isinf(b.state["k"]) else stats.nbinom.sf(0, b.state["k"],
|
||||
b.state["k"] / (b.state["k"] + mu))
|
||||
at = (stats.poisson.pmf(1, mu) if np.isinf(b.state["k"])
|
||||
else stats.nbinom.pmf(1, b.state["k"], b.state["k"] / (b.state["k"] + mu)))
|
||||
assert z[1] == pytest.approx(stats.norm.ppf(1 - (tail - at / 2)))
|
||||
|
||||
|
||||
def test_no_exposure_value_age_or_reference_is_nan(count_rate, reference):
|
||||
"""Pins down: without minutes, with zero minutes, without a value, at an age outside the range, or against a
|
||||
reference with no minutes, z and outside are NaN, and a reference with no candidates at all clips z instead of
|
||||
reaching infinity. Fails if any of them reads as within the reference, or `inf` leaves the baseline."""
|
||||
b = count_rate().fit(*reference[:2], exposure=reference[2])
|
||||
outside, z = b.deviation(np.array([0.1, 0.1, np.nan, 0.1]), np.array([24, 24, 24, 60.0]),
|
||||
exposure=np.array([np.nan, 0.0, 10.0, 10.0]))
|
||||
assert np.isnan(z).all() and np.isnan(outside).all()
|
||||
assert np.isnan(b.deviation(np.array([0.1]), np.array([24.0]))[1]).all()
|
||||
empty = count_rate().fit(np.array([0.1]), np.array([24.0]), exposure=np.array([np.nan]))
|
||||
assert np.isnan(empty.deviation(np.array([0.1]), np.array([24.0]), exposure=np.array([10.0]))[1]).all()
|
||||
none = count_rate().fit(np.zeros(5), np.full(5, 24.0), exposure=np.full(5, 10.0))
|
||||
assert none.deviation(np.array([0.5]), np.array([24.0]), exposure=np.array([10.0]))[1][0] == count_rate.Z_MAX
|
||||
|
||||
|
||||
def test_the_reference_range_is_the_rates_expected_in_the_childs_minutes(count_rate, reference):
|
||||
"""Pins down: the p5, median and p95 of a count reference are the reference count's quantiles in the child's own
|
||||
minutes (times the zone scale) as rates, ordered, narrower in rate with more minutes, and NaN where z is NaN.
|
||||
Fails if the range stops using the child's minutes or the scale, or a child without minutes gets one (the
|
||||
patient summary shows it as the metric's reference)."""
|
||||
b = count_rate(scale=2.0).fit(*reference[:2], exposure=reference[2])
|
||||
out = b.percentiles(np.array([24.0, 24.0, 24.0, 60.0]), np.array([5.0, 400.0, np.nan, 10.0]))
|
||||
mu, k = b.state["rate"] * 400.0 * 2.0, b.state["k"]
|
||||
p95 = stats.poisson.ppf(0.95, mu) if np.isinf(k) else stats.nbinom.ppf(0.95, k, k / (k + mu))
|
||||
assert out[1, 2] == pytest.approx(p95 / 800.0)
|
||||
assert (np.diff(out[:2], axis=1) >= 0).all()
|
||||
assert out[1, 2] - out[1, 0] < out[0, 2] - out[0, 0] or out[0, 2] == 0
|
||||
assert np.isnan(out[2:]).all()
|
||||
|
||||
|
||||
def test_round_trip_and_scale(count_rate, reference):
|
||||
"""Pins down: `to_dict` / `from_dict` keep the state and the scale, and a per-electrode zone value is counted
|
||||
back through its electrodes (0.1 per minute per electrode over 3 electrodes in 10 minutes is 3 candidates).
|
||||
Fails if the scale is lost on save or not applied."""
|
||||
b = count_rate(scale=3.0).fit(*reference[:2], exposure=reference[2])
|
||||
again = count_rate.from_dict(b.to_dict())
|
||||
args = (np.array([0.1]), np.array([24.0]))
|
||||
assert again.deviation(*args, exposure=np.array([10.0]))[1] == pytest.approx(
|
||||
b.deviation(*args, exposure=np.array([10.0]))[1])
|
||||
assert again.scale == 3.0
|
||||
counts, exposure = b._counts(np.array([0.1]), np.array([10.0]))
|
||||
assert counts.tolist() == [3.0] and exposure.tolist() == [30.0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", [modern, legacy], ids=["modern", "legacy"])
|
||||
def test_the_rates_are_counted_against_their_minutes(module, reference):
|
||||
"""Pins down: every rate and density feature (overall, per electrode, per zone, unnormalised zone, inherited)
|
||||
has a count baseline whose exposure is the minutes of its own state and variant, the minutes themselves have no
|
||||
baseline, and the other spike features keep the configured one; a table without the minutes gives NaN for the
|
||||
counted features. Fails if a rate falls back to centile curves (collapsed at 0 in the reference) or reads
|
||||
another state's minutes."""
|
||||
spikes = (module.Spikes if module is modern else module.LegacySpikes)()
|
||||
assert set(module.EXPOSURE) == {f for f in module.FEATURES if f.startswith(
|
||||
("spike_rate_", "spike_density_", "spike_zone_", "spike_inherited_rate_", "spike_inherited_zone_"))}
|
||||
assert all(module.EXPOSURE[f].endswith(("_nrem" if "nrem" in f else "_awake")) for f in module.EXPOSURE)
|
||||
assert not set(module.MINUTES) & set(module.FEATURES)
|
||||
assert {spikes.baselines[f].name for f in module.EXPOSURE} == {"count_rate"}
|
||||
assert spikes.baselines["spike_laterality"].name == "curves"
|
||||
rates, ages, minutes = reference
|
||||
table = pd.DataFrame({"spike_rate_nrem": rates, "spike_minutes_nrem": minutes, "age_months": ages})
|
||||
spikes.train(table)
|
||||
out = spikes.predict(table.iloc[:3]).set_index("feature")
|
||||
assert out.loc["spike_rate_nrem", "z"].notna().all()
|
||||
blind = spikes.predict(table.iloc[:3].drop(columns="spike_minutes_nrem")).set_index("feature")
|
||||
assert blind.loc["spike_rate_nrem", "z"].isna().all()
|
||||
|
||||
|
||||
def test_legacy_and_modern_count_alike(reference):
|
||||
"""Pins down: both implementations' count baselines give the same reference and the same z. Fails if one copy
|
||||
of `CountRate` drifts from the other."""
|
||||
rates, ages, minutes = reference
|
||||
a = modern_baseline.CountRate().fit(rates, ages, exposure=minutes)
|
||||
b = legacy_baseline.CountRate().fit(rates, ages, exposure=minutes)
|
||||
assert a.state == b.state
|
||||
np.testing.assert_array_equal(a.deviation(rates, ages, exposure=minutes)[1],
|
||||
b.deviation(rates, ages, exposure=minutes)[1])
|
||||
@@ -0,0 +1,424 @@
|
||||
"""What this module covers: the spikes biomarker's density features: only useful candidates
|
||||
count (a field and no vertex/POSTS/ocular mark), the per-electrode and per-zone density per
|
||||
state, the 0-vs-NaN convention, and the inherited-state variant where a stretch without a
|
||||
clean-window state takes the nearest labeled window's state (30 s, conservative on
|
||||
transitions, never before the stable start). Both implementations, modern and legacy, are
|
||||
exercised and must agree.
|
||||
|
||||
Fixtures: synthetic in-memory studies built around 1/f noise with spike waveforms injected
|
||||
(`density_study`: 40 field spikes at C3 in sleep and 20 isolated artifacts on O2 in wake;
|
||||
`rejected_study`: all sleep, a 20 s stretch the QC left without a state, and 20 s annotated
|
||||
as crying; `edge_study`: a single clean sleep window at 10-14 s with one field spike at 13 s;
|
||||
`montage_study`: sleep windows at 2-6 s and 30-34 s with field spikes at 10 s, 24 s and 31 s)
|
||||
and a quiet all-wake study. Nothing comes from a patient.
|
||||
"""
|
||||
import contextlib
|
||||
import importlib
|
||||
import io
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
FS = 250.0
|
||||
DUR = 600.0
|
||||
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
C3_NEIGHBORS = ("F3", "T3", "Cz", "P3")
|
||||
DENSITY_MODULES = ("tea.biomarkers.spikes._density", "tea.legacy.biomarkers.spikes._density")
|
||||
|
||||
|
||||
def _fondo(n, n_ch, rng):
|
||||
"""1/f noise at ~20 µV per channel, as the director's spike-detector validation uses."""
|
||||
f = np.fft.rfftfreq(n, 1 / FS)
|
||||
f[0] = f[1]
|
||||
out = np.empty((n, n_ch))
|
||||
for j in range(n_ch):
|
||||
esp = (1.0 / f) * np.exp(1j * rng.uniform(0, 2 * np.pi, len(f)))
|
||||
y = np.fft.irfft(esp, n)
|
||||
out[:, j] = y / np.std(y) * 20.0
|
||||
return out
|
||||
|
||||
|
||||
def _punta(dur_ms=50.0, amp=120.0, post=60.0):
|
||||
"""A spike with its slow posterior wave, as the director's criterion 3 describes."""
|
||||
n = int(dur_ms * FS / 1000)
|
||||
t = np.linspace(-1, 1, max(n, 3))
|
||||
p = amp * (1 - t ** 2) ** 2
|
||||
m = int(0.30 * FS)
|
||||
s = -post * np.sin(np.pi * np.linspace(0, 1, m))
|
||||
return np.concatenate([p, s])
|
||||
|
||||
|
||||
def _add_spikes(x, rng, canal, spans, field):
|
||||
"""`spikes` per (start_s, end_s) span on `canal`, with the field on its 10-20 neighbors
|
||||
when `field`, as one simultaneous discharge."""
|
||||
idx = {c: i for i, c in enumerate(SCALP)}
|
||||
pun = _punta()
|
||||
for a, b, k in spans:
|
||||
for t in np.sort(rng.uniform(a, b, k)):
|
||||
i = int(t * FS)
|
||||
x[i:i + len(pun), idx[canal]] += pun
|
||||
if field:
|
||||
for v in C3_NEIGHBORS:
|
||||
x[i:i + len(pun), idx[v]] += 0.6 * pun
|
||||
return x
|
||||
|
||||
|
||||
def _study(x, labels, annotations=()):
|
||||
"""The contracts' Study around an in-memory (samples, channels) µV array: one variant,
|
||||
4 s windows at a 2 s step labeled by sleep_state, and the annotated states as
|
||||
annotation_mask events (the same annotations ride the variant for the legacy adapter,
|
||||
whose director code translates them itself)."""
|
||||
import mne
|
||||
|
||||
from tea.contracts import Labels, Preprocessed, Study
|
||||
from tea.processes.annotation_mask.api import state_of
|
||||
|
||||
n = x.shape[0]
|
||||
raw = mne.io.RawArray(x.T * 1e-6, mne.create_info(SCALP[: x.shape[1]], FS, ch_types="eeg"),
|
||||
verbose="error")
|
||||
anns = [(float(t0), float(d), e) for t0, d, e in annotations]
|
||||
if anns:
|
||||
onsets, durs, descs = zip(*anns)
|
||||
raw.set_annotations(mne.Annotations(list(onsets), list(durs), list(descs)))
|
||||
starts = np.arange(0.0, n / FS - 4.0 + 1e-9, 2.0)
|
||||
windows = pd.DataFrame({"start_s": starts, "end_s": starts + 4.0, "clean": True, "gap": False})
|
||||
prep = Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
|
||||
plan={"name": "synthetic"}, plan_hash="synthetic")
|
||||
sleep_state = Labels("sleep_state",
|
||||
per_window=pd.Series(labels, index=windows.index, name="vigilancia"))
|
||||
events = pd.DataFrame([{"onset_s": t0, "duration_s": d, "estado": state_of(e)}
|
||||
for t0, d, e in anns if state_of(e)],
|
||||
columns=["onset_s", "duration_s", "estado"])
|
||||
annotation_mask = Labels("annotation_mask", events=events)
|
||||
return Study(prep, {"sleep_state": sleep_state, "annotation_mask": annotation_mask})
|
||||
|
||||
|
||||
def _labels_for(edits):
|
||||
"""A 600 s window at 2 s step labeled 'sueno' everywhere, with `edits` {start_s: label}."""
|
||||
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sueno", dtype=object)
|
||||
for t0, e in edits.items():
|
||||
labels[starts == float(t0)] = e
|
||||
return list(labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def density_study():
|
||||
"""Half sleep, half wake: 40 spikes with field at C3 in the sleep half, 20 isolated
|
||||
artifacts on O2 in the wake half (no field: they must not count as useful)."""
|
||||
rng = np.random.default_rng(5)
|
||||
x = _fondo(int(DUR * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(200.0, 290.0, 40)], field=True)
|
||||
solo = _punta(dur_ms=50.0, amp=150.0, post=0.0)
|
||||
idx = {c: i for i, c in enumerate(SCALP)}
|
||||
for t in np.sort(rng.uniform(310.0, 590.0, 20)):
|
||||
i = int(t * FS)
|
||||
x[i:i + len(solo), idx["O2"]] += 1.4 * solo
|
||||
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
|
||||
labels = np.where(starts < 300.0, "sueno", "vigilia")
|
||||
return _study(x, labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rejected_study():
|
||||
"""All sleep: 6 spikes in a 20 s stretch the QC left without a state (150-170 s), 6 in
|
||||
clean sleep, 6 in a stretch annotated as crying (400-420 s)."""
|
||||
rng = np.random.default_rng(8)
|
||||
x = _fondo(int(DUR * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(152.0, 168.0, 6), (200.0, 216.0, 6), (402.0, 418.0, 6)],
|
||||
field=True)
|
||||
labels = _labels_for({t0: "sin_estado" for t0 in range(148, 170, 2)})
|
||||
return _study(x, labels, annotations=((400.0, 20.0, "Llanto"),))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wake_study():
|
||||
"""Two quiet minutes of wake: no spike, no sleep."""
|
||||
rng = np.random.default_rng(2)
|
||||
labels = ["vigilia"] * len(np.arange(0.0, 120.0 - 4.0 + 1e-9, 2.0))
|
||||
return _study(_fondo(int(120 * FS), len(SCALP), rng), labels)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edge_study():
|
||||
"""One minute with a single clean sleep window at 10-14 s and one field spike at 13 s:
|
||||
inside the 4 s window the state was classified on, beyond the 2 s grid step."""
|
||||
rng = np.random.default_rng(11)
|
||||
x = _fondo(int(60 * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(12.9, 13.1, 1)], field=True)
|
||||
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sin_estado", dtype=object)
|
||||
labels[starts == 10.0] = "sueno"
|
||||
return _study(x, list(labels))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def montage_study():
|
||||
"""One minute with clean sleep windows at 2-6 s and 30-34 s and field spikes at 10 s
|
||||
(unlabeled gap before the stable start), 24 s (unlabeled gap after it) and 31 s
|
||||
(inside the second window)."""
|
||||
rng = np.random.default_rng(13)
|
||||
x = _fondo(int(60 * FS), len(SCALP), rng)
|
||||
x = _add_spikes(x, rng, "C3", [(9.9, 10.1, 1), (23.9, 24.1, 1), (30.9, 31.1, 1)],
|
||||
field=True)
|
||||
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
|
||||
labels = np.full(len(starts), "sin_estado", dtype=object)
|
||||
labels[starts == 2.0] = "sueno"
|
||||
labels[starts == 30.0] = "sueno"
|
||||
return _study(x, list(labels))
|
||||
|
||||
|
||||
def _measure(impl, study, **kwargs):
|
||||
path = "tea.legacy.biomarkers.spikes.api" if impl == "legacy" else "tea.biomarkers.spikes.api"
|
||||
cls = getattr(importlib.import_module(path), "LegacySpikes" if impl == "legacy" else "Spikes")
|
||||
return cls(**kwargs).measure(study)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_density(density_study):
|
||||
"""The density study measured by both implementations, {'modern': {...}, 'legacy': {...}}."""
|
||||
return {impl: _measure(impl, density_study) for impl in ("modern", "legacy")}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_rejected(rejected_study):
|
||||
"""The rejected-stretch study measured by both implementations."""
|
||||
return {impl: _measure(impl, rejected_study) for impl in ("modern", "legacy")}
|
||||
|
||||
|
||||
def test_useful_candidates_map_to_c3_and_the_central_zone(measured_density):
|
||||
"""Pins down: with field spikes at C3 in sleep, the NREM density lands on C3 and the
|
||||
central zone (per electrode, so it divides by the zone's 3 electrodes), every other
|
||||
electrode is exactly 0, and the isolated wake artifacts on O2 count nowhere.
|
||||
|
||||
Fails if candidates without a field start counting, if canal_max stops being the
|
||||
electrode a discharge is attributed to, or if the zone density stops being normalised
|
||||
per electrode.
|
||||
"""
|
||||
m = measured_density["modern"]
|
||||
assert m["spike_rate_nrem"] > 0
|
||||
# the density divides by the unrounded minutes (the por_canal convention) and the
|
||||
# rate by the two-decimal minutes (the indicadores convention), so they can differ
|
||||
# by that rounding
|
||||
assert m["spike_density_nrem_C3"] == pytest.approx(m["spike_rate_nrem"], rel=0.01)
|
||||
assert m["spike_density_nrem_C3"] > 10 * max(m["spike_rate_awake"], 0.01)
|
||||
for e in SCALP:
|
||||
esperado = m["spike_rate_nrem"] if e == "C3" else 0.0
|
||||
assert m[f"spike_density_nrem_{e}"] == pytest.approx(esperado, rel=0.01), e
|
||||
assert m["spike_zone_nrem_central"] == pytest.approx(m["spike_rate_nrem"] / 3, rel=0.01)
|
||||
assert m["spike_zone_nrem_frontal_izq"] == 0.0
|
||||
assert m["spike_zone_nrem_occipital"] == 0.0
|
||||
assert m["spike_density_awake_O2"] == 0.0
|
||||
|
||||
|
||||
def test_a_quiet_present_electrode_is_zero_and_a_state_without_minutes_is_nan(wake_study):
|
||||
"""Pins down: an electrode present with no candidates reads 0, never NaN, while a state
|
||||
with no clean minutes (no sleep in an all-wake study) makes every feature of that state
|
||||
NaN, inherited ones included.
|
||||
|
||||
Fails if the densities stop distinguishing 'no candidates' (0) from 'no denominator'
|
||||
(NaN), or if the inherited variant stops honouring the same convention.
|
||||
"""
|
||||
m = _measure("modern", wake_study)
|
||||
for e in SCALP:
|
||||
assert m[f"spike_density_nrem_{e}"] != m[f"spike_density_nrem_{e}"] # NaN
|
||||
assert m[f"spike_density_awake_{e}"] == 0.0
|
||||
for z in ("central", "occipital", "temporal_der"):
|
||||
assert m[f"spike_zone_nrem_{z}"] != m[f"spike_zone_nrem_{z}"]
|
||||
assert m[f"spike_zone_awake_{z}"] == 0.0
|
||||
assert m[f"spike_inherited_zone_nrem_{z}"] != m[f"spike_inherited_zone_nrem_{z}"]
|
||||
assert m["spike_inherited_rate_nrem"] != m["spike_inherited_rate_nrem"]
|
||||
assert m["spike_inherited_rate_awake"] == pytest.approx(0.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_absent_electrode_and_zone_are_nan(module):
|
||||
"""Pins down: an electrode missing from the montage has a NaN density (it cannot be
|
||||
measured), and a zone with no present electrode is NaN too.
|
||||
|
||||
Fails if absent electrodes start reading as a measured 0.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
ev = pd.DataFrame({"canal_max": ["C3", "C3"], "fase": ["sueno", "sueno"],
|
||||
"vertice": [False, False], "posts": [False, False],
|
||||
"ocular": [False, False], "vecinos": [2, 2]})
|
||||
out = mod.electrode_densities(ev, {"sueno": 2.0}, electrodes=("C3", "T6"), present=("C3",))
|
||||
assert out["spike_density_nrem_C3"] == pytest.approx(1.0)
|
||||
assert out["spike_density_nrem_T6"] != out["spike_density_nrem_T6"]
|
||||
zonas = mod.zone_densities(ev, {"sueno": 2.0}, present=("C3",))
|
||||
assert zonas["spike_zone_nrem_central"] == pytest.approx(1.0)
|
||||
assert zonas["spike_zone_nrem_temporal_der"] != zonas["spike_zone_nrem_temporal_der"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_states_inherit_from_the_nearest_labeled_window(module):
|
||||
"""Pins down (port of the research repo's inheritance test): a stretch the QC left
|
||||
unlabeled takes the nearest clean window's state up to 30 s away; farther, or before
|
||||
the first labeled window (or `t_min`), it stays without a state; intervals never
|
||||
overlap.
|
||||
|
||||
Fails if the 30 s reach, the nearest-window rule or the `t_min` floor stop being
|
||||
applied.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
t0 = np.r_[np.arange(20, 40, 2.0), np.arange(60, 98, 2.0), np.arange(200, 240, 2.0)]
|
||||
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": "sueno"})
|
||||
v = mod.inherit_states(labeled, 300.0, inherit_s=30.0, t_min=15.0)
|
||||
|
||||
def etq(t):
|
||||
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
|
||||
return (v.etiqueta[m].iloc[0], bool(v.heredado[m].iloc[0])) if m.any() else (None, None)
|
||||
|
||||
assert etq(30) == ("sueno", False) # clean window
|
||||
assert etq(50) == ("sueno", True) # 20 s gap between clean windows
|
||||
assert etq(120) == ("sueno", True) # 20 s after the last clean window
|
||||
assert etq(150) == (None, None) # more than 30 s away from both
|
||||
assert etq(18) == (None, None) # before the first clean window (t_min 15)
|
||||
assert not (v.t_ini_s.to_numpy()[1:] < v.t_fin_s.to_numpy()[:-1]).any()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_inheritance_is_conservative_across_state_transitions(module):
|
||||
"""Pins down (port of the research repo's conservative-transition test): an unlabeled
|
||||
stretch between two different states stays 'transicion' and counts in neither; between
|
||||
two windows of the same state it inherits that state.
|
||||
|
||||
Fails if the transition rule starts assigning one of the two states.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
t0 = np.r_[np.arange(0, 40, 2.0), np.arange(60, 100, 2.0), np.arange(110, 150, 2.0)]
|
||||
e = np.r_[["somnolencia"] * 20, ["sueno"] * 20, ["sueno"] * 20]
|
||||
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": e})
|
||||
v = mod.inherit_states(labeled, 160.0)
|
||||
|
||||
def etq(t):
|
||||
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
|
||||
return v.etiqueta[m].iloc[0] if m.any() else None
|
||||
|
||||
assert etq(45) == "transicion" and etq(58) == "transicion"
|
||||
assert etq(105) == "sueno"
|
||||
assert etq(30) == "somnolencia" and etq(70) == "sueno"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", DENSITY_MODULES)
|
||||
def test_candidate_category_marks_isolated_and_marked(module):
|
||||
"""Pins down: a candidate is 'util' only with a field and no mark; the director's mark
|
||||
order (posts, vertice, ocular) wins over 'aislado'.
|
||||
|
||||
Fails if the category rule starts counting marked or fieldless candidates as useful.
|
||||
"""
|
||||
mod = importlib.import_module(module)
|
||||
ev = pd.DataFrame({"vecinos": [2, 0, 3, 1, 0],
|
||||
"posts": [False, False, True, False, False],
|
||||
"vertice": [False, False, False, True, False],
|
||||
"ocular": [False, False, False, False, True]})
|
||||
assert list(mod.candidate_category(ev)) == ["util", "aislado", "posts", "vertice", "ocular"]
|
||||
|
||||
|
||||
def test_rejected_stretch_counts_only_when_inherited(measured_rejected):
|
||||
"""Pins down (port of the research repo's rejected-window test): spikes in a stretch
|
||||
the QC left without a state count in NREM only through inheritance — the direct rate
|
||||
sees only the clean-stretch spikes — and spikes in a stretch annotated as crying count
|
||||
nowhere, because the detector's own gate rejects those windows.
|
||||
|
||||
Fails if the inherited variant starts using the direct states, or if annotated states
|
||||
stop gating the detector.
|
||||
"""
|
||||
for m in measured_rejected.values():
|
||||
assert 0 < m["spike_rate_nrem"] < m["spike_inherited_rate_nrem"]
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(2 * m["spike_rate_nrem"], rel=0.2)
|
||||
assert m["spike_inherited_zone_nrem_central"] > m["spike_zone_nrem_central"]
|
||||
assert m["spike_inherited_rate_awake"] != m["spike_inherited_rate_awake"] # no wake
|
||||
|
||||
|
||||
def test_without_inheritance_the_inherited_variant_matches_the_direct(rejected_study):
|
||||
"""Pins down: with the inheritance reach at 0 the inherited variant reduces to the
|
||||
direct one (same candidates, same minutes).
|
||||
|
||||
Fails if the inherited run stops deriving its states from the inheritance intervals.
|
||||
"""
|
||||
m = _measure("modern", rejected_study, herencia_s=0.0)
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(m["spike_rate_nrem"], rel=1e-9)
|
||||
assert m["spike_inherited_zone_nrem_central"] == pytest.approx(m["spike_zone_nrem_central"],
|
||||
rel=1e-9)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_candidate_inside_the_classified_window_counts_as_direct(impl, edge_study):
|
||||
"""Pins down (the reviewer's 13 s scenario): a candidate at 13 s with a single clean
|
||||
4 s sleep window starting at 10 s lies inside the window's own state, so the direct
|
||||
NREM rate counts it (1 spike over the 4 clean gate minutes of [10, 14)); the inherited
|
||||
run labels 13 s as direct too and only stretches [14, 44) inherit.
|
||||
|
||||
Fails if `_vig` shortens the state windows to the 2 s grid step again: the spike would
|
||||
fall outside every window, the direct rate would read 0 and only the inherited run
|
||||
would count it.
|
||||
"""
|
||||
m = _measure(impl, edge_study)
|
||||
assert m["spike_rate_nrem"] == pytest.approx(14.286, abs=0.001) # 1 / 0.07 rounded minutes
|
||||
assert m["spike_density_nrem_C3"] == pytest.approx(15.0, abs=0.01) # 1 over 4/60 unrounded
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(1.754, abs=0.001)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_no_inherited_state_before_the_stable_start(impl, montage_study):
|
||||
"""Pins down (the reviewer's stable-start scenario): with the stable start at 20 s,
|
||||
the spike at 10 s — in the gap after an early labeled window but before the stable
|
||||
start — gets no state anywhere, while the spike at 24 s inherits and the spike at
|
||||
31 s is direct. The direct run sees only 31 s (0.13 clean sleep minutes, rate 7.692);
|
||||
the inherited run counts 24 s and 31 s but not 10 s (0.73 minutes, rate 2.74). With
|
||||
the default stable start of 0 the 10 s spike inherits as well (0.97 minutes, 3.093).
|
||||
|
||||
Fails if `measure` stops passing the stable start to the inheritance (the 10 s spike
|
||||
would count in the inherited rate) or if the early window's reach is clamped wrongly.
|
||||
"""
|
||||
m = _measure(impl, montage_study, stable_start_s=20.0)
|
||||
assert m["spike_rate_nrem"] == pytest.approx(7.692, abs=0.001)
|
||||
assert m["spike_inherited_rate_nrem"] == pytest.approx(2.74, abs=0.001)
|
||||
sin_montaje = _measure(impl, montage_study)
|
||||
assert sin_montaje["spike_inherited_rate_nrem"] == pytest.approx(3.093, abs=0.001)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ("modern", "legacy"))
|
||||
def test_crying_annotation_rejects_gate_windows(impl, rejected_study):
|
||||
"""Pins down (port of the research repo's annotated-window test): the detector's 2 s
|
||||
gate rejects the windows of the crying stretch and nothing else.
|
||||
|
||||
Fails if annotated states stop reaching the quality gate (the crying spikes would then
|
||||
count as sleep).
|
||||
"""
|
||||
if impl == "modern":
|
||||
from tea.biomarkers.spikes import _density
|
||||
from tea.biomarkers.spikes.api import Spikes
|
||||
|
||||
module = Spikes()
|
||||
est, canales = module._prepare(rejected_study)
|
||||
gate = _density.gate_windows(est, canales, module.vent_s, module.rechazar_transitorio)
|
||||
else:
|
||||
from tea.legacy.biomarkers.spikes import _adapter, _density
|
||||
from tea.legacy.biomarkers.spikes._director import eeg_io
|
||||
|
||||
module = _density
|
||||
with _adapter.estudio(rejected_study.prep, "hp05_prom", eeg_io) as est, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
gate = _density.gate_windows(est, eeg_io, 2.0, False)
|
||||
lloro = gate.motivo.str.contains("estado llanto", regex=False)
|
||||
assert lloro.sum() >= 8 and not gate[lloro].apta.any()
|
||||
assert gate[~lloro].apta.all()
|
||||
|
||||
|
||||
def test_legacy_and_modern_agree_on_every_feature(measured_density, measured_rejected):
|
||||
"""Pins down: both implementations expose the same 79 features with the same values on
|
||||
the same study, old and new alike.
|
||||
|
||||
Fails if one implementation's port of the detector, the densities or the inheritance
|
||||
drifts from the other's.
|
||||
"""
|
||||
for nombre, medido in (("density", measured_density), ("rejected", measured_rejected)):
|
||||
moderno, legado = medido["modern"], medido["legacy"]
|
||||
assert set(moderno) == set(legado)
|
||||
for f, v in moderno.items():
|
||||
otro = legado[f]
|
||||
iguales = v == otro or (np.isnan(v) and np.isnan(otro))
|
||||
assert iguales or v == pytest.approx(otro, rel=1e-6, abs=1e-12), (nombre, f, v, otro)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Spindle detection and summaries, plus loading partial spindle baselines.
|
||||
|
||||
Fixtures: `sleep_recording` supplies synthetic EEG with short, long or sustained
|
||||
sigma bursts. `tmp_path` holds a saved spindle baseline.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tea.biomarkers.spindles.api import Spindles
|
||||
from tea.legacy.biomarkers.spindles.api import LegacySpindles
|
||||
from tea.legacy.processes.spindle_detection.api import LegacySpindleDetection
|
||||
from tea.processes.spindle_detection.api import SpindleDetection
|
||||
|
||||
CHANNELS = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
FS = 250
|
||||
DENSITY = "spindle_density_per_min_channel"
|
||||
NO_LONG = "spindle_density_per_min_channel_no_long"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sleep_recording():
|
||||
"""Make 600 s of sleep on the 10-20 montage with selectable sigma bursts."""
|
||||
|
||||
def make(mode):
|
||||
rng = np.random.default_rng(1)
|
||||
duration = 600
|
||||
freq = np.fft.rfftfreq(duration * FS, 1 / FS)
|
||||
freq[0] = freq[1]
|
||||
voltages = np.empty((duration * FS, len(CHANNELS)))
|
||||
for i in range(len(CHANNELS)):
|
||||
spectrum = np.exp(1j * rng.uniform(0, 2 * np.pi, len(freq))) / freq
|
||||
background = np.fft.irfft(spectrum)
|
||||
voltages[:, i] = background * (20 / background.std())
|
||||
|
||||
def inject(start, length, hz, amplitude, gains):
|
||||
t = np.arange(int(length * FS)) / FS
|
||||
envelope = np.hanning(len(t)) if length < 2 else np.clip(np.minimum(t, length - t) / 0.5, 0, 1)
|
||||
wave = amplitude * envelope * np.sin(2 * np.pi * hz * t)
|
||||
for channel, gain in gains.items():
|
||||
a = int(start * FS)
|
||||
voltages[a:a + len(t), CHANNELS.index(channel)] += gain * wave
|
||||
|
||||
short = dict.fromkeys(("F3", "F4", "C3", "C4", "Cz"), 1.0) | {"Fz": 0.8, "P3": 0.7, "P4": 0.7}
|
||||
starts = np.arange(5, duration - 10, 9.0)
|
||||
if mode != "empty":
|
||||
for start in starts + rng.uniform(-1, 1, len(starts)):
|
||||
if mode == "long" and (200 < start < 240 or 400 < start < 410):
|
||||
continue
|
||||
inject(start, 1, 12.5, 50, short)
|
||||
if mode == "long":
|
||||
inject(205, 25, 13, 60, {"C3": 1, "C4": 1, "Cz": 1, "F3": 0.8, "F4": 0.8})
|
||||
inject(402, 5, 12, 60, {"Fz": 1, "F3": 0.6, "F4": 0.6})
|
||||
if mode == "continuous":
|
||||
inject(0, duration * 0.6, 13, 60, short)
|
||||
if mode == "empty":
|
||||
voltages.fill(0)
|
||||
|
||||
class Raw:
|
||||
n_times = len(voltages)
|
||||
ch_names = CHANNELS
|
||||
info = {"sfreq": FS}
|
||||
annotations = ()
|
||||
|
||||
def get_channel_types(self):
|
||||
return ["eeg"] * len(self.ch_names)
|
||||
|
||||
def get_data(self, picks):
|
||||
return voltages[:, [self.ch_names.index(name) for name in picks]].T / 1e6
|
||||
|
||||
windows = pd.DataFrame({"start_s": np.arange(0, duration, 4.0)})
|
||||
return SimpleNamespace(variant=lambda _: Raw(), windows=windows)
|
||||
|
||||
return make
|
||||
|
||||
|
||||
IMPLEMENTATIONS = ((SpindleDetection, Spindles), (LegacySpindleDetection, LegacySpindles))
|
||||
|
||||
|
||||
def measure(prep, implementation, phase="N2"):
|
||||
detector, biomarker = implementation
|
||||
labels = {"sleep_state": SimpleNamespace(per_window=["sueno"] * len(prep.windows)),
|
||||
"slow_wave_staging": SimpleNamespace(per_window=["N2"] * len(prep.windows))}
|
||||
study = SimpleNamespace(prep=prep, label=labels.__getitem__)
|
||||
labels["spindle_detection"] = detector(phase=phase).predict(study)
|
||||
return biomarker().measure(study), labels["spindle_detection"].events
|
||||
|
||||
|
||||
def test_long_runs_split_events_and_density(sleep_recording):
|
||||
"""Pin long/extreme counts and the existing density. Fails if split events disappear from the old density."""
|
||||
prep = sleep_recording("long")
|
||||
outputs = []
|
||||
for implementation in IMPLEMENTATIONS:
|
||||
result, events = measure(prep, implementation)
|
||||
assert ((events.channel == "C3") & events.onset_s.between(204, 231)).sum() >= 6
|
||||
assert result["spindle_n_long_runs"] == 6
|
||||
assert result["spindle_n_extreme"] == 5
|
||||
assert 24 <= result["spindle_max_run_s"] <= 27
|
||||
assert result[DENSITY] == round(len(events) / 10 / 13, 3)
|
||||
assert result[NO_LONG] < result[DENSITY]
|
||||
outputs.append(result)
|
||||
for feature in ("spindle_n_long_runs", "spindle_n_extreme", "spindle_max_run_s",
|
||||
"spindle_sigma_occupancy_median", "spindle_sigma_occupancy_max", NO_LONG):
|
||||
assert outputs[0][feature] == pytest.approx(outputs[1][feature], abs=0.01)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_short_bursts_and_sustained_sigma(sleep_recording, implementation):
|
||||
"""Pin zero long runs with short spindles and occupancy with sustained sigma. Fails if occupancy uses event thresholds."""
|
||||
short, _ = measure(sleep_recording("short"), implementation)
|
||||
sustained, _ = measure(sleep_recording("continuous"), implementation)
|
||||
assert short["spindle_n_long_runs"] == short["spindle_n_extreme"] == 0
|
||||
assert short[NO_LONG] == short[DENSITY]
|
||||
assert short["spindle_sigma_occupancy_max"] < 0.45
|
||||
assert sustained["spindle_sigma_occupancy_max"] >= 0.55
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_spindle_density_by_electrode_and_zone(sleep_recording, implementation):
|
||||
"""Pin event counts per sleep minute and per searched electrode, NaN on a channel the detector never searches
|
||||
(O1, and so the occipital zone). Fails if empty searched channels are omitted, an unsearched channel reports a
|
||||
density, or a phase leaks."""
|
||||
prep = sleep_recording("short")
|
||||
result, events = measure(prep, implementation)
|
||||
counts = events.channel.value_counts()
|
||||
assert counts["C3"] > 0 and counts["Fz"] > 0
|
||||
assert result["spindle_electrode_C3"] == counts["C3"] / 10
|
||||
assert np.isnan(result["spindle_electrode_O1"])
|
||||
assert np.isnan(result["spindle_zone_occipital"])
|
||||
assert result["spindle_zone_central"] == counts[["C3", "Cz", "C4"]].sum() / 30
|
||||
other_phase, _ = measure(prep, implementation, phase="N3")
|
||||
assert all(np.isnan(value) for value in other_phase.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
|
||||
def test_sleep_without_spindles_is_nan(sleep_recording, implementation):
|
||||
"""Pin missing outputs on event-free sleep. Fails if any feature reports a value without a detected spindle."""
|
||||
result, events = measure(sleep_recording("empty"), implementation)
|
||||
assert events.empty and events.attrs["searched"]
|
||||
assert all(np.isnan(value) for value in result.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("biomarker", (Spindles, LegacySpindles))
|
||||
def test_spindle_baselines_load_without_new_features(tmp_path, biomarker):
|
||||
"""Pin save/load of a single-feature baseline. Fails if train or predict requires all current feature columns."""
|
||||
table = pd.DataFrame({"age_months": [12, 24, 36], DENSITY: [0.1, 0.2, 0.3]})
|
||||
module = biomarker(baseline_params={"n_min": 1}).train(table)
|
||||
module.save(tmp_path)
|
||||
loaded = biomarker.load(tmp_path)
|
||||
assert list(loaded.baselines) == [DENSITY]
|
||||
assert loaded.predict(table).feature.tolist() == [DENSITY] * len(table)
|
||||
Reference in New Issue
Block a user