feat(tea): EEG analysis and age baselines on the tea library, installed from the libs/tea submodule

This commit is contained in:
AlbertoPMDM
2026-11-19 15:43:27 -06:00
parent 7b2eae2782
commit 25c460f80e
20 changed files with 1646 additions and 2 deletions
+3
View File
@@ -0,0 +1,3 @@
[submodule "tea"]
path = libs/tea
url = ssh://git@10.0.10.41:2222/alberto/tea.git
+3
View File
@@ -31,6 +31,9 @@ WebApi.
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Training records its five routines (`sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`). Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
| `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-<biomarker>[-<stage>]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. |
| `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-<biomarker>[-<stage>]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. |
| `eeg_analysis.py` | The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (`cluster`: this process, a LocalCluster or `DASK_SCHEDULER_ADDRESS`), each result written to `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo` with ids that survive a re-analysis, and one governance `ExtractionRun` per EEG. `python -m models tea analyze [--all] [--limit N] [--cluster auto\|local\|remote\|sync]`. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
Submodule
+1
Submodule libs/tea added at 9cef5554d0
+33
View File
@@ -28,6 +28,17 @@ def _model_module(args: argparse.Namespace, name: str):
return None
def _own_steps(args: argparse.Namespace):
"""A scenario that isn't trained on a cohort build runs its own steps: its `model.run_steps`, or `None`."""
from importlib import import_module
try:
model = import_module(f"models.{args.domain}.{args.scenario}.model")
except ModuleNotFoundError:
return None
return getattr(model, "run_steps", None)
def _cohort_file(args: argparse.Namespace, model):
"""The build's exported file; `None` and a message on stderr if it's missing."""
from persistance.settings import settings
@@ -132,6 +143,15 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
return 0
def _tea_analyze(args: argparse.Namespace) -> int:
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
from models.eeg_analysis import analyze_pending
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
return 1 if s.failed else 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file."""
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
@@ -168,6 +188,8 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if (own := _own_steps(args)) is not None:
return own(args)
if (args.estimate or args.store) and not args.output:
parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
@@ -427,6 +449,17 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.set_defaults(run=lambda args: _run(run, args))
tea = commands.add_parser("tea", help="TEA's EEG analysis")
tea.set_defaults(run=lambda args: _show_help(tea))
tea_actions = tea.add_subparsers(dest="action", metavar="<action>")
analyze = tea_actions.add_parser(
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
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)
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
+236
View File
@@ -0,0 +1,236 @@
"""TEA's EEG analysis against the database: which EEGs to analyse, the batch, and its results written to bronze.
An EEG is pending when it has an EDF and was never analysed, or was analysed with another plan or other module
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
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.
`cluster` is the `tea` library's: "sync" runs in this process, "local" on a LocalCluster, "auto" on the scheduler in
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
"""
import uuid
from collections.abc import Callable, Mapping
from dataclasses import dataclass
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 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
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
def checked_settings() -> Settings:
"""The analysis's settings, checked against the metric catalog the tables use."""
s = model_settings()
codes = sorted(m.code for m in s.metrics)
if codes != sorted(c.value for c in MetricaEeg):
raise ValueError(f"model.toml must map every MetricaEeg code once, not {codes}")
return s
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
everything: bool = False, limit: int | None = None) -> list[str]:
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
out, expected = [], None
for eeg_id, valid, stored_hash, stored_versions, error in session.exec(query):
if everything or stored_hash != plan_hash or stored_versions != versions:
out.append(eeg_id)
elif valid == 1 and error is None:
stored = dict(session.exec(select(EegMetrica.met_codigo, EegMetrica.met_modelo)
.where(EegMetrica.met_eeg_id == eeg_id)).all())
expected = models() if expected is None else expected
if any(stored.get(code) != label for code, label in expected.items()):
out.append(eeg_id)
if limit is not None and len(out) >= limit:
break
return out
def age_months(born, studied, days_per_month: float) -> float | None:
if born is None or studied is None or studied < born:
return None
return round((studied - born).days / days_per_month, 1)
def inputs(session: Session, eeg_id: str, days_per_month: float) -> tuple[bytes, float | None]:
eeg = session.get(Eeg, eeg_id)
if eeg is None or eeg.eeg_estudio is None:
raise LookupError(f"no EDF for EEG {eeg_id!r}")
born = session.exec(select(Pacientes.pac_fecha_nacimiento).where(Pacientes.pac_id == eeg.eeg_pac_id)).first()
return bytes(eeg.eeg_estudio), age_months(born, eeg.eeg_fecha_estudio, days_per_month)
def row_id(*parts: object) -> str:
return str(uuid.uuid5(uuid.NAMESPACE_URL, "tea:eeg/" + "/".join("" if p is None else str(p) for p in parts)))
@dataclass
class Rows:
eeg: dict
criteria: list[EegCriterio]
metrics: list[EegMetrica]
electrodes: list[EegMetricaElectrodo]
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
eeg = {
"eeg_valido": m.valid, "eeg_nivel": m.level, "eeg_fraccion_limpia": m.clean_fraction,
"eeg_canales_malos": m.bad_channels, "eeg_ruido_linea_db": m.line_db, "eeg_con_sueno": m.asleep,
"eeg_edad_meses": m.age_months, "eeg_plan_hash": m.plan_hash, "eeg_versiones": m.versions,
"eeg_analizado_en": at or datetime.now(timezone.utc).replace(tzinfo=None), "eeg_error": m.error,
}
if m.channels is not None:
eeg["eeg_canales"] = m.channels
if m.duration_min is not None:
eeg["eeg_duracion_min"] = m.duration_min
seen: dict[tuple[str, str | None], int] = {}
criteria = []
for c in m.checks:
n = seen[c.code, c.electrode] = seen.get((c.code, c.electrode), 0) + 1
criteria.append(EegCriterio(
cri_id=row_id(m.key, "criterio", c.code, c.electrode, n), cri_eeg_id=m.key, cri_codigo=c.code,
cri_electrodo=c.electrode, cri_valor=c.value, cri_valor_texto=c.text, cri_unidad=c.unit,
cri_bajo=c.low, cri_alto=c.high, cri_decisivo=int(c.decisive), cri_anormal=int(c.abnormal),
))
by_code = {metric.code: metric for metric in s.metrics}
metrics, electrodes = [], []
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)
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)
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,
))
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,
met_p5=deviation.p5 if deviation else None, met_mediana=deviation.median if deviation else 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)
def save(session: Session, eeg_id: str, new: Rows) -> None:
"""Replaces the EEG's analysis in the caller's session; the caller commits."""
eeg = session.get(Eeg, eeg_id)
if eeg is None:
raise LookupError(f"no EEG {eeg_id!r}")
for column, value in new.eeg.items():
setattr(eeg, column, value)
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(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])
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
if m.error:
quality = f"error: {m.error}"
elif m.valid:
quality = f"valido: {m.level}"
else:
quality = "no valido: " + "; ".join(c.code for c in m.checks if c.abnormal and c.decisive)
return ExtractionRun(
domain=s.domain, entity="eeg", entity_pk=m.key, column_extracted=COLUMNS,
source_description="eeg.eeg_estudio (EDF)", source_started_at=started, source_ended_at=ended,
transform_description=f"tea {s.impl}, plan {s.plan} {m.plan_hash}; {m.versions}",
quality_validation=quality,
estatus=(EstatusExtraccion.FALLIDA if m.error else EstatusExtraccion.COMPLETADA).value,
)
@dataclass
class Summary:
pending: int = 0
valid: int = 0
not_valid: int = 0
failed: int = 0
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]
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
return out
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
settings: Settings | None = None, baselines: Baselines | None = None,
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
from tea.pipeline.dask_runner import run as run_batch
from persistance.tea import eeg_repository
s = settings or checked_settings()
b = baselines or Baselines(s.domain)
pipe = pipeline(s)
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
with eeg_repository.open_session() as session:
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
everything=everything, limit=limit)
summary = Summary(pending=len(ids))
def write(m: Measurement) -> None:
ended = _now()
with eeg_repository.open_session() as session:
save(session, m.key, rows(m, s, b, at=ended))
session.commit()
if log_runs:
from persistance.governance import extraction_run_repository
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
if m.error:
summary.failed += 1
elif m.valid:
summary.valid += 1
else:
summary.not_valid += 1
def lost(args, exc) -> Measurement:
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
error=f"{type(exc).__name__}: the batch lost this study")
for start in range(0, len(ids), batch):
argsets = []
with eeg_repository.open_session() as session:
for eeg_id in ids[start:start + batch]:
edf, age = inputs(session, eeg_id, s.days_per_month)
argsets.append((eeg_id, edf, age, s))
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost)
return summary
+6 -1
View File
@@ -43,6 +43,7 @@ from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, Trainin
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
REFERENCE_SOURCE = "referencia" # `cohort.source` of a version trained on a cohort outside the platform
@dataclass(frozen=True)
@@ -232,6 +233,8 @@ class ModelRegistry:
run = self.client.get_run(mv.run_id)
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
dbt_build = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == "dbt" else None
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
metrics = run.data.metrics
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
sha = mv.tags.get(MODEL_SHA_TAG, "")
@@ -239,6 +242,8 @@ class ModelRegistry:
cohort_detail = f"huella {armado['huella'][:12]}"
elif dbt_build is not None:
cohort_detail = f"dbt build {dbt_build} de {mv.tags.get(COHORT_URL_TAG)}"
elif reference:
cohort_detail = f"cohorte de referencia {mv.tags.get(COHORT_URL_TAG)}, listado {reference[:12]}"
else:
cohort_detail = "sin cohorte"
return [
@@ -246,7 +251,7 @@ class ModelRegistry:
PromotionCheck(
"ML-03",
"enlazada al armado de cohorte con el que se entrenó",
armado is not None or dbt_build is not None,
armado is not None or dbt_build is not None or bool(reference),
cohort_detail,
),
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
+1
View File
@@ -0,0 +1 @@
"""TEA's models: the EEG analysis (`eeg`)."""
+6
View File
@@ -0,0 +1,6 @@
"""TEA's EEG analysis: the `tea` library run on one stored EDF, without the database.
`settings.py` maps each metric to a library feature (`model.toml`); `analyze.py` measures one EEG; `baselines.py`
compares a value with its promoted age baseline. Reading the EDFs and writing the results back to bronze is
`models.eeg_analysis` (`python -m models tea analyze`).
"""
+246
View File
@@ -0,0 +1,246 @@
"""One EEG through the `tea` library: validation, then preprocessing, the processes and the metrics' biomarkers.
`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age, touches
no database and returns a `Measurement` with the verdict, every quality check and each metric's raw value. The
deviation from the age baselines is added afterwards (`baselines.py`), where the registered models are.
The library reads EDFs from paths only, so the bytes go to a temporary file for the duration of the call.
"""
import re
import tempfile
import time
from dataclasses import dataclass, field
from pathlib import Path
from types import SimpleNamespace
from models.tea.eeg.settings import Settings
# Channel codes the library builds from the reason's first words, and the fixed code each is stored as.
CHANNEL_CODES = {"intermittent-contact-by": "intermittent-bursts"}
@dataclass(frozen=True)
class Check:
code: str
electrode: str | None
value: float | None
text: str | None
unit: str | None
low: float | None
high: float | None
decisive: bool
abnormal: bool
@dataclass(frozen=True)
class MetricValue:
code: str
value: float | None
electrodes: dict[str, float | None] = field(default_factory=dict)
@dataclass(frozen=True)
class Measurement:
key: str
age_months: float | None
plan_hash: str
versions: str
valid: int | None = None
level: str | None = None
clean_fraction: float | None = None
bad_channels: int | None = None
line_db: float | None = None
channels: int | None = None
duration_min: float | None = None
asleep: int | None = None
checks: tuple[Check, ...] = ()
metrics: tuple[MetricValue, ...] = ()
error: str | None = None
seconds: float = 0.0
def pipeline(settings: Settings):
from tea.pipeline import Pipeline
return Pipeline.default(impl=settings.impl)
def plan(settings: Settings) -> dict:
from tea.preprocessing import PLANS
return PLANS[settings.plan].to_dict()
def phase_detector(pipe, phase: str):
base = pipe.module("spindle_detection")
return type(base)(variant=base.variant, phase=phase)
def processes(pipe, settings: Settings) -> list[str]:
"""The processes the metrics need, in dependency order. Spindle detection itself runs once per sleep stage, so
the phased biomarkers contribute only what their stage's detector requires."""
from tea.pipeline.run_study import order_for
needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n]
requires = {r for n in needs for r in pipe.module(n).requires}
for phase in settings.phases:
requires.update(phase_detector(pipe, phase).requires)
return order_for(["metrics"], {**pipe.modules, "metrics": SimpleNamespace(requires=tuple(sorted(requires)))})
def versions(pipe, settings: Settings) -> str:
"""What produced an analysis, as `name=version;...`: a new version of any module analyses every EEG again."""
names = ["validation", "preprocessing", *processes(pipe, settings)]
if settings.phases:
names.append("spindle_detection")
names += settings.biomarkers
return ";".join(f"{n}={getattr(pipe.module(n), 'version', '?')}" for n in dict.fromkeys(names))
def criterion_code(code: str, text: str, electrode: str | None) -> str:
"""The library's channel codes are the first words of the reason, numbers included (`amplitude-4.5-x`)."""
if electrode is None:
return code
if code.startswith("amplitude"):
return "aux-amplitude" if "out of range" in text else "amplitude"
return CHANNEL_CODES.get(code, code)
def _number(value) -> float | None:
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if number == number else None
def checks(validation, run: dict) -> tuple[Check, ...]:
out = []
for c in validation.checks_of(run):
text = c.value if isinstance(c.value, str) else None
out.append(Check(
code=criterion_code(c.code, c.display, c.electrode), electrode=c.electrode,
value=None if text is not None else _number(c.value), text=text, unit=c.unit or None,
low=_number(c.low), high=_number(c.high), decisive=bool(c.decisive), abnormal=bool(c.abnormal),
))
return tuple(out)
def gate_reasons(summary, plan: dict) -> list[str]:
"""The plan's gates on top of the validator's verdict, as the library's own batch applies them."""
reasons = list(summary.extra.get("reasons", []))
gates = plan.get("gates", {})
if gates.get("skip_no_analizable", True) and summary.level == "no_analizable" and not reasons:
reasons.append("triage level no_analizable")
least = gates.get("min_clean")
if least is not None and summary.clean_fraction == summary.clean_fraction and summary.clean_fraction < least:
reasons.append(f"plan gate: {100 * summary.clean_fraction:.0f}% clean < {100 * least:.0f}%")
return reasons
Features = dict[tuple[str, str | None], dict[str, float | None]]
def features(pipe, study, settings: Settings) -> Features:
"""Every feature of each biomarker the metrics read, by biomarker and sleep stage (`None`: no stage), with
spindle detection run once per stage."""
by_phase = {None: study}
for phase in settings.phases:
by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study))
out: Features = {}
for m in settings.metrics:
for biomarker in (m.biomarker, m.electrodes):
if biomarker and (biomarker, m.phase) not in out:
out[biomarker, m.phase] = {k: _number(v) for k, v in
pipe.module(biomarker).measure(by_phase[m.phase]).items()}
return out
def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]:
out = []
for m in settings.metrics:
electrodes = {}
if m.electrodes:
electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items()
if name.startswith(m.electrode_prefix)}
out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes))
return tuple(out)
def _error(exc: Exception) -> str:
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}"
def _study(pipe, path, settings: Settings, the_plan: dict, age_months: float | None, line_hz: float):
"""Validation, then, for a valid study, preprocessing and the processes: (validation run, summary, verdict,
study or None)."""
from tea.contracts import Study
validation = pipe.module("validation")
run = validation.run(path, line_hz=line_hz)
summary = validation.summary_of(run)
valid = int(bool(summary.valid) and not gate_reasons(summary, the_plan))
if not valid:
return run, summary, valid, None
preprocessing = pipe.module("preprocessing")
study = Study(preprocessing.run(path, preprocessing.plan_for(summary, the_plan), age_months=age_months))
for name in processes(pipe, settings):
study = study.with_labels(pipe.module(name).predict(study))
return run, summary, valid, study
def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) -> Measurement:
"""Never raises: a failure is a `Measurement` with `error` set, keeping the verdict and checks if validation
finished before it."""
started = time.time()
pipe = pipeline(settings)
the_plan = plan(settings)
result = dict(key=key, age_months=age_months, plan_hash=the_plan.get("hash", ""), versions=versions(pipe, settings))
try:
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "study.edf"
path.write_bytes(edf)
validation = pipe.module("validation")
run, summary, valid, study = _study(pipe, path, settings, the_plan, age_months, settings.line_hz)
result.update(
valid=valid, level=summary.level, clean_fraction=_number(summary.clean_fraction),
bad_channels=len(summary.bad_channels), line_db=_number(summary.line_db),
channels=len(run.get("channels", [])) or None,
duration_min=round(run["duration_s"] / 60, 2) if run.get("duration_s") else None,
checks=checks(validation, run),
)
if study is None:
return Measurement(**result, seconds=round(time.time() - started, 1))
asleep = int((study.label("sleep_state").per_window == "sueno").any())
return Measurement(**result, asleep=asleep, metrics=_metrics(features(pipe, study, settings), settings),
seconds=round(time.time() - started, 1))
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop the batch
return Measurement(**result, error=_error(exc), seconds=round(time.time() - started, 1))
@dataclass(frozen=True)
class ReferenceStudy:
"""One study of a reference cohort, measured for training: its age, verdict, and every feature of each
biomarker the metrics read, by biomarker and sleep stage. No path, file name or date."""
key: str
age_months: float
valid: int | None = None
features: Features = field(default_factory=dict)
error: str | None = None
def reference(key: str, path: str, age_months: float, settings: Settings, line_hz: float) -> ReferenceStudy:
"""A reference study read from a local or `s3://` path, at the mains frequency of the cohort's country. Never
raises: a failure is a `ReferenceStudy` with `error` set."""
from tea.pipeline.storage import local_copy
pipe = pipeline(settings)
try:
with local_copy(path) as local:
_, _, valid, study = _study(pipe, local, settings, plan(settings), age_months, line_hz)
measured = features(pipe, study, settings) if study is not None else {}
return ReferenceStudy(key, age_months, valid, measured)
except Exception as exc: # noqa: BLE001 -- one unreadable study must not stop the batch
return ReferenceStudy(key, age_months, error=_error(exc))
+102
View File
@@ -0,0 +1,102 @@
"""The promoted age baselines: a metric's raw value against its curve at the child's age.
Each baseline is a trained `tea` biomarker module registered as `tea-<scenario>` with the `produccion` alias. Without
one in production a metric keeps its raw value and no deviation, the same as a model never configured.
"""
import math
from dataclasses import dataclass
import numpy as np
from models.io.lineage import registered_name
from models.io.registry import registry as default_registry
@dataclass(frozen=True)
class Deviation:
z: float | None
outside: int | None
p5: float | None
median: float | None
p95: float | None
def _number(value) -> float | None:
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if math.isfinite(number) else None
def _feature_baseline(module, feature: str):
baselines = getattr(module, "baselines", None)
return baselines[feature] if baselines is not None else module.baseline
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
"""p5, median and p95 of a centile curve at an age, interpolated on log age as the library's z is; none for a
baseline without a curve or an age outside it."""
curve = getattr(baseline, "curva", None)
if curve is None or age_months is None or age_months <= 0:
return None, None, None
rows = curve.dropna(subset=["p5", "mediana", "p95"])
if not len(rows):
return None, None, None
log_ages = np.log(rows["edad_meses"].to_numpy(float))
at = math.log(age_months)
if not log_ages.min() <= at <= log_ages.max():
return None, None, None
return tuple(_number(np.interp(at, log_ages, rows[c].to_numpy(float))) for c in ("p5", "mediana", "p95"))
class Baselines:
"""Resolves each scenario's production version once per instance, and loads it the first time it is used."""
def __init__(self, domain: str = "tea", registry=default_registry, loader=None):
self.domain = domain
self.registry = registry
self._loader = loader
self._resolved: dict[str, object | None] = {}
self._loaded: dict[str, object] = {}
def _resolve(self, scenario: str):
if scenario not in self._resolved:
try:
self._resolved[scenario] = self.registry.resolve(self.domain, scenario)
except LookupError:
self._resolved[scenario] = None
return self._resolved[scenario]
def label(self, scenario: str) -> str | None:
"""`tea-<scenario>/<version>` of the version in production, or none."""
resolved = self._resolve(scenario)
return f"{registered_name(self.domain, scenario)}/{resolved.version}" if resolved else None
def module(self, scenario: str):
"""The trained biomarker module in production, or none."""
resolved = self._resolve(scenario)
if resolved is None:
return None
if scenario not in self._loaded:
if self._loader is not None:
self._loaded[scenario] = self._loader(resolved.model_uri)
else:
from tea.serving import load_biomarker
self._loaded[scenario] = load_biomarker(resolved.model_uri)
return self._loaded[scenario]
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | 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."""
module = self.module(scenario)
if module is None:
return None
baseline = _feature_baseline(module, feature)
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))
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)
+51
View File
@@ -0,0 +1,51 @@
"""TEA's EEG baselines as a model of the platform: `python -m models run tea eeg --train [--promote]`.
A baseline isn't trained on a cohort build of the platform but on the reference cohort (`train.py`), so this
scenario runs its own steps (`run_steps`) in place of `run`'s cohort-file ones: training every scenario's baseline,
then promoting each through the registry's checks.
"""
import argparse
import sys
from models.tea.eeg.settings import settings
SETTINGS = settings()
def run_steps(args: argparse.Namespace) -> int:
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
from models.tea.eeg import train
if args.export or args.estimate or args.store or args.version:
print("tea/eeg trains on its reference cohort: only --train and --promote apply", file=sys.stderr)
return 2
environment = args.environment.upper()
versions: dict[str, str] = {}
if args.train:
for scenario, (version, new) in train.train_all(SETTINGS, environment).items():
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
versions[scenario] = version
if not args.promote:
return 0
code = 0
for scenario in SETTINGS.scenarios:
version = versions.get(scenario) or getattr(train.latest(scenario, environment), "version", None)
if version is None:
print(f"{scenario}: no {environment} version to promote; use --train", file=sys.stderr)
code = 1
continue
try:
current = registry.client.get_model_version_by_alias(registered_name("tea", scenario), PRODUCTION_ALIAS)
except Exception: # noqa: BLE001 -- no version in production yet
current = None
if current is not None and str(current.version) == str(version):
print(f"{scenario}: version {version} already in production")
continue
try:
registry.promote("tea", scenario, str(version))
print(f"{scenario}: version {version} promoted")
except PromotionBlocked as blocked:
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
print(f"{scenario}: version {version} not promoted, missing: {failed}", file=sys.stderr)
code = 1
return code
+52
View File
@@ -0,0 +1,52 @@
# The EEG analysis: the `tea` library's plan and modules, and the library feature each stored metric is.
domain = "tea"
plan = "director-cluster"
impl = "modern"
line_hz = 60.0
# Completed months at the study: days / days_per_month, as the TEA cohort counts them.
days_per_month = 30.4375
# The baselines' kind (the library's: "curves", centile curves on log age; or "age_blocks").
baseline = "curves"
# The reference cohort the age baselines are trained on: the Helsinki HK1K EEGs (public), its EDFs and the table of
# their ages under `prefix` in the cluster's S3, children of `ages` months. Its mains are at `line_hz`.
[reference]
name = "hk1k"
prefix = "raw/eeg-helsinki/"
ages_table = "anon_codex_age_sex.csv"
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.
# The feature each metric maps to is provisional until the domain expert confirms it.
[[metrics]]
code = "RITMO_POSTERIOR"
biomarker = "posterior_rhythm"
feature = "posterior_rhythm_hz"
[[metrics]]
code = "HUSOS_SUENO_N2"
biomarker = "spindles"
phase = "N2"
feature = "spindle_density_per_min_channel"
electrodes = "spindle_topography"
electrode_prefix = "topo_enh_"
[[metrics]]
code = "HUSOS_SUENO_N3"
biomarker = "spindles"
phase = "N3"
feature = "spindle_density_per_min_channel"
electrodes = "spindle_topography"
electrode_prefix = "topo_enh_"
[[metrics]]
code = "PICOS_PAROXISTICOS"
biomarker = "spikes"
feature = "spike_rate_nrem"
[[metrics]]
code = "GRADIENTE_ANTEROPOSTERIOR"
biomarker = "gradient"
feature = "gradient_delta_sueno"
+82
View File
@@ -0,0 +1,82 @@
"""The analysis's settings (`model.toml`): the plan, the implementation and the metrics with their library features.
Each trained baseline is a registered model `tea-<scenario>`, one per biomarker and sleep stage
(`eeg-spindles-n2`, `eeg-spindle-topography-n2`, `eeg-posterior-rhythm`, ...).
"""
import tomllib
from dataclasses import dataclass
from functools import cache
from pathlib import Path
@dataclass(frozen=True)
class Metric:
code: str
biomarker: str
feature: str
phase: str | None = None
electrodes: str | None = None
electrode_prefix: str = ""
@property
def scenario(self) -> str:
return scenario_of(self.biomarker, self.phase)
@property
def electrode_scenario(self) -> str | None:
return scenario_of(self.electrodes, self.phase) if self.electrodes else None
@dataclass(frozen=True)
class Reference:
name: str
prefix: str
ages_table: str
line_hz: float
ages: tuple[float, float]
@dataclass(frozen=True)
class Settings:
domain: str
plan: str
impl: str
line_hz: float
days_per_month: float
baseline: str
reference: Reference
metrics: tuple[Metric, ...]
@property
def phases(self) -> tuple[str, ...]:
return tuple(dict.fromkeys(m.phase for m in self.metrics if m.phase))
@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]
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]
return tuple(dict.fromkeys(names))
def scenario_of(biomarker: str, phase: str | None) -> str:
return "eeg-" + biomarker.replace("_", "-") + (f"-{phase.lower()}" if phase else "")
@cache
def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings:
raw = tomllib.loads(path.read_text())
metrics = tuple(Metric(**m) for m in raw.pop("metrics"))
reference = raw.pop("reference")
reference = Reference(**{**reference, "ages": tuple(reference["ages"])})
codes = [m.code for m in metrics]
if len(set(codes)) != len(codes):
raise ValueError(f"model.toml maps a metric code twice: {codes}")
if raw["impl"] != "modern":
raise ValueError("the analysis stores the modern validation's checks: impl must be 'modern'")
return Settings(metrics=metrics, reference=reference, **raw)
+217
View File
@@ -0,0 +1,217 @@
"""The age baselines: trained on the reference cohort and registered, one version per scenario (biomarker and sleep
stage), as `tea-<scenario>`.
1. `listing`: the reference cohort's EDFs and ages, within `[reference] ages`, read from the cluster's S3 in a worker
(only the workers reach it). Its hash identifies the cohort a version was trained on (ML-03).
2. `measure`: each study through the analysis's own unit of work (`analyze.reference`), as a Dask batch.
3. `train_scenario`: a fresh library module trained on the valid studies' features and ages, logged with the
library's MLflow model (`tea.serving.log_biomarker`, whose guard refuses groups under 5 and anything per child),
then its run and version given what the registry's promotion checks read: environment, the reference cohort,
the model's hash, the five routine records and its metrics.
Promotion is the registry's (`registry.promote`), as for every model: it waits for the technical, clinical and
interpretability reports, so the domain expert's validation is what puts a baseline in production.
"""
import hashlib
import json
import tempfile
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from models.io.lineage import (
COHORT_BUILD_TAG,
COHORT_SOURCE_TAG,
COHORT_URL_TAG,
MODEL_SHA_TAG,
code_version,
registered_name,
)
from models.io.registry import REFERENCE_SOURCE
from models.io.tracking import routine_path
from models.tea.eeg.analyze import ReferenceStudy, pipeline, plan, reference
from models.tea.eeg.settings import Settings
DOMAIN = "tea"
@dataclass(frozen=True)
class Listing:
"""The reference studies to measure, (key, path, age in months), and the hash that identifies them. Keys are
positions, never file names."""
studies: tuple[tuple[str, str, float], ...]
sha256: str
@classmethod
def of(cls, name: str, paths_and_ages: list[tuple[str, float]]) -> "Listing":
ordered = sorted(paths_and_ages)
digest = hashlib.sha256("\n".join(f"{p}|{a}" for p, a in ordered).encode()).hexdigest()
return cls(tuple((f"{name}-{k:04d}", p, a) for k, (p, a) in enumerate(ordered, 1)), digest)
def list_reference(s: Settings) -> list[tuple[str, float]]:
"""In a worker: (s3 path, age in months) of each reference EDF with an age inside `[reference] ages`."""
from tea.pipeline.storage import s3
r = s.reference
fs = s3()
paths = fs.find(r.prefix)
tables = [p for p in paths if p.endswith(r.ages_table)]
if not tables:
raise FileNotFoundError(f"no {r.ages_table} under {r.prefix}")
with fs.open(tables[0], "rb") as f:
ages = pd.read_csv(f)
ages.columns = ["archivo", "edad_anos", *ages.columns[2:]]
edfs = {Path(p).name: p for p in paths if p.endswith(".edf")}
found = [("s3://" + edfs[row.archivo], round(float(row.edad_anos) * 12, 1))
for row in ages.itertuples() if row.archivo in edfs]
return [(p, a) for p, a in found if r.ages[0] <= a <= r.ages[1]]
def listing(s: Settings, cluster: str = "auto") -> Listing:
from tea.pipeline.dask_runner import run as run_batch
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
return Listing.of(s.reference.name, found)
def measure(found: Listing, s: Settings, cluster: str = "auto") -> list[ReferenceStudy]:
from tea.pipeline.dask_runner import run as run_batch
def lost(args, exc):
return ReferenceStudy(args[0], args[2], error=f"{type(exc).__name__}: the batch lost this study")
return run_batch(reference, [(k, p, a, s, s.reference.line_hz) for k, p, a in found.studies], cluster=cluster,
on_error=lost)
def table(studies: list[ReferenceStudy], biomarker: str, phase: str | None) -> pd.DataFrame:
"""The valid studies' features of one biomarker and stage, with their ages: what a baseline is trained on."""
rows = [{**st.features[biomarker, phase], "age_months": st.age_months} for st in studies
if st.valid == 1 and st.error is None and (biomarker, phase) in st.features]
return pd.DataFrame(rows)
def _module_state(module) -> tuple[str, dict]:
"""The trained module's hash (its saved parameters and baselines) and its baselines' state, by feature."""
with tempfile.TemporaryDirectory() as folder:
module.save(folder)
files = sorted(Path(folder).glob("*.json"))
digest = hashlib.sha256(b"".join(f.name.encode() + f.read_bytes() for f in files)).hexdigest()
baselines = json.loads((Path(folder) / "baseline.json").read_text())
return digest, baselines
def _covered(state: dict, n_min: float) -> tuple[float, float] | None:
"""The ages every feature's curve covers with at least `n_min` effective studies."""
spans = []
for baseline in (state.values() if "name" not in state else [state]):
curve = baseline.get("curva") or {}
ages = [a for a, n in zip(curve.get("edad_meses", []), curve.get("n_efectivo", [])) if n and n >= n_min]
if not ages:
return None
spans.append((min(ages), max(ages)))
return (max(lo for lo, _ in spans), min(hi for _, hi in spans)) if spans else None
def find_trained(scenario: str, expected: dict[str, str]):
"""The newest version of the scenario whose tags hold every expected value, or `None`."""
from mlflow import MlflowClient
found = MlflowClient().search_model_versions(f"name='{registered_name(DOMAIN, scenario)}'")
matching = [mv for mv in found if all(mv.tags.get(k) == v for k, v in expected.items())]
return max(matching, key=lambda mv: int(mv.version), default=None)
def expected_tags(scenario: str, found: Listing, s: Settings, environment: str) -> dict[str, str]:
biomarker, phase = s.scenarios[scenario]
module = pipeline(s).module(biomarker)
return {"environment": environment, COHORT_BUILD_TAG: found.sha256, "plan_hash": plan(s).get("hash", ""),
"module": biomarker, "module_version": getattr(module, "version", "?"), "phase": phase or "",
"baseline": s.baseline}
def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing, s: Settings, environment: str) -> str:
"""Trains, logs and registers one scenario's baseline; returns its version."""
from mlflow import MlflowClient
from tea.serving import log_biomarker
biomarker, phase = s.scenarios[scenario]
data = table(studies, biomarker, phase)
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
module.train(data)
sha, state = _module_state(module)
name = registered_name(DOMAIN, scenario)
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
experiment=name)
client, run_id, version = MlflowClient(), mv.run_id, str(mv.version)
tags = {"domain": DOMAIN, "scenario": scenario, MODEL_SHA_TAG: sha,
COHORT_URL_TAG: f"{DOMAIN}/{REFERENCE_SOURCE}/{s.reference.name}", COHORT_SOURCE_TAG: REFERENCE_SOURCE,
**expected_tags(scenario, found, s, environment)}
for key, value in {**tags, **code_version()}.items():
client.set_tag(run_id, key, value)
for key, value in tags.items():
client.set_model_version_tag(name, version, key, value)
features = [c for c in data.columns if c != "age_months"]
present = {f: int(data[f].notna().sum()) for f in features}
params = getattr(module, "baseline_params", {}) or {}
n_min = float(params.get("n_min", 30))
covered = _covered(state, n_min) if s.baseline == "curves" else None
measured = [st for st in studies if st.error is None]
routines = {
"MUESTREO": {"cohorte": s.reference.name, "edades_meses": list(s.reference.ages),
"estudios_listados": len(found.studies), "medidos": len(measured),
"validos": sum(st.valid == 1 for st in measured), "con_error": len(studies) - len(measured),
"usados": len(data), "fase_de_sueno": phase},
"DATOS_FALTANTES": {"criterio": "cada curva usa los estudios con ese rasgo medido; los demás se omiten",
"estudios_con_valor_por_rasgo": present},
"METODO_ANALITICO": {"modulo": biomarker, "version_modulo": tags["module_version"], "linea_base": s.baseline,
"parametros": params, "plan": s.plan, "plan_hash": tags["plan_hash"],
"red_electrica_hz": s.reference.line_hz},
"BALANCE_CLASES": {"aplica": False, "motivo": "una curva de referencia por edad no tiene clases"},
"CONFIANZA_SALIDA": {"salida": "z contra la curva a la edad del niño; -1/+1 debajo del p5 / arriba del p95",
"edades_cubiertas_meses": list(covered) if covered else None,
"n_efectivo_minimo": n_min},
}
for kind, record in routines.items():
client.log_text(run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
client.log_metric(run_id, "n_referencia", len(data))
for feature, n in present.items():
client.log_metric(run_id, f"n.{feature}", n)
if covered:
client.log_metric(run_id, "edad_min_cubierta", covered[0])
client.log_metric(run_id, "edad_max_cubierta", covered[1])
client.update_model_version(name, version, description=(
f"Curva de referencia por edad de {biomarker}{f' en sueño {phase}' if phase else ''}, entrenada en "
f"{s.reference.name} ({len(data)} estudios de {s.reference.ages[0]:g} a {s.reference.ages[1]:g} meses). "
"Pendiente de validación clínica."))
return version
def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Listing | None = None,
studies: list[ReferenceStudy] | None = None) -> dict[str, tuple[str, bool]]:
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
scenario needs it."""
found = found or listing(s, cluster)
out, pending = {}, []
for scenario in s.scenarios:
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
if existing is not None:
out[scenario] = (str(existing.version), False)
else:
pending.append(scenario)
if pending:
studies = studies if studies is not None else measure(found, s, cluster)
for scenario in pending:
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
return out
def latest(scenario: str, environment: str):
"""The newest version of the scenario trained in `environment`, or `None`."""
return find_trained(scenario, {"environment": environment})
+5 -1
View File
@@ -2,7 +2,7 @@
name = "models"
version = "0.1.0"
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
requires-python = ">=3.11"
requires-python = ">=3.12"
dependencies = [
"persistance",
"extraction",
@@ -15,9 +15,12 @@ dependencies = [
"scikit-learn>=1.4",
# The values of the cohort and estimate files (`models.io.contracts`).
"pandera>=0.20",
"tea",
]
[project.optional-dependencies]
# Reading the EEG baselines' reference cohort from the cluster's S3 (`models.tea.eeg.train`).
eeg-reference = ["tea[s3]"]
# Running uploaded notebooks without Quarto (models.io.rendering.JupyterRenderer, models.pipelines.experiment).
notebooks = [
"nbclient>=0.10",
@@ -28,6 +31,7 @@ notebooks = [
[tool.uv.sources]
persistance = { path = "../Persistance", editable = true }
extraction = { path = "../Extraction", editable = true }
tea = { path = "libs/tea", editable = true }
[build-system]
requires = ["hatchling"]
+7
View File
@@ -33,6 +33,13 @@ def cacu_db(tmp_path, monkeypatch):
engine.cache_clear()
@pytest.fixture
def tea_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "tea", "core.tea.base", "TeaModel")
yield
engine.cache_clear()
@pytest.fixture
def mlflow_tracking(tmp_path, monkeypatch):
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
+123
View File
@@ -0,0 +1,123 @@
"""Synthetic EDF+ studies for the EEG analysis's tests: every signal is generated, nothing comes from a patient.
`edf_bytes(minutes=4, bad=...)` returns a file the `tea` library reads as a real study:
- background: pink noise mixed over the head (sources weighted by distance), so neighbouring electrodes correlate;
- wake: a posterior rhythm at `rhythm_hz`, strongest on O1 O2 P3 P4, and blinks on Fp1 Fp2;
- sleep: frontal slow waves and 13 Hz spindles on the central and frontal electrodes;
- EKG, EOG and the mains line; states annotated as the hospital writes them ("Paciente despierto", "Dormido");
- `bad`: `flat` channels (no signal) or `loud` ones (eight times the amplitude).
Written as the hospital's converter writes them: plain labels, microvolts, one fixed range, digital ±32767.
"""
import tempfile
from datetime import time
from pathlib import Path
import numpy as np
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
EARS = ("A1", "A2")
AUX = ("LOC", "ROC", "EKG")
POSTERIOR = ("O1", "O2", "P3", "P4")
SPINDLE = ("F3", "F4", "Fz", "C3", "C4", "Cz")
FRONTAL = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8")
FULL_SCALE = 4999.9
def _positions():
import mne
pos = mne.channels.make_standard_montage("colin27_1020").get_positions()["ch_pos"]
return {ch: np.asarray(pos[ch], float) for ch in SCALP + list(EARS)}
def _pink(rng, n, fs):
f = np.fft.rfftfreq(n, 1 / fs)
spec = rng.normal(size=f.size) + 1j * rng.normal(size=f.size)
spec[1:] /= np.sqrt(f[1:])
spec[0] = 0
x = np.fft.irfft(spec, n)
return x / x.std()
def signals(*, fs: float, minutes: float, rhythm_hz: float, line_hz: float, bad: dict, seed: int):
rng = np.random.default_rng(seed)
n = int(round(minutes * 60 * fs))
t = np.arange(n) / fs
wake = t < t[-1] / 2
sleep = ~wake
pos = _positions()
names = SCALP + list(EARS)
src = rng.normal(size=(24, 3))
src *= np.mean([np.linalg.norm(p) for p in pos.values()]) / np.linalg.norm(src, axis=1, keepdims=True)
sources = np.stack([_pink(rng, n, fs) for _ in range(len(src))])
data = {}
for ch in names:
w = np.exp(-np.linalg.norm(src - pos[ch], axis=1) / 0.04)
w /= w.sum()
data[ch] = 18.0 * (w @ sources) / np.sqrt((w ** 2).sum()) / np.sqrt(len(src)) * 3 + 4.0 * _pink(rng, n, fs)
alpha = np.sin(2 * np.pi * rhythm_hz * t + rng.uniform(0, 2 * np.pi))
for ch in names:
y = pos[ch][1]
amp = 30.0 if ch in POSTERIOR else 12.0 * np.exp(-(y + 0.05) * 25) if y < 0.05 else 3.0
data[ch] += amp * alpha * wake
slow = np.zeros(n)
k = 0
while k < n:
length = int(fs * rng.uniform(0.8, 1.6))
if k + length < n and sleep[k]:
slow[k:k + length] = -rng.uniform(80, 200) * np.sin(np.pi * np.arange(length) / length)
k += length + int(fs * rng.uniform(0.2, 1.5))
spindles = np.zeros(n)
for c in np.arange(5.0, n / fs, 8.0):
i0 = int(c * fs)
if i0 < n and sleep[i0]:
length = int(fs * rng.uniform(0.6, 1.8))
tt = np.arange(length) / fs
seg = 35.0 * np.exp(-0.5 * ((tt - tt[-1] / 2) / (tt[-1] / 5)) ** 2) * np.sin(2 * np.pi * 13.0 * tt)
spindles[i0:i0 + length] += seg[: max(0, min(length, n - i0))]
for ch in names:
data[ch] += slow if ch in FRONTAL else 0.6 * slow if ch in SPINDLE else 0
if ch in SPINDLE:
data[ch] += spindles
blinks = np.zeros(n)
for c in np.arange(2.0, n / fs, 4.0):
i0, length = int((c + rng.uniform(-0.5, 0.5)) * fs), int(0.3 * fs)
if 0 <= i0 < n - length and wake[i0]:
blinks[i0:i0 + length] += 120 * np.hanning(length)
data["Fp1"] += blinks
data["Fp2"] += blinks
data["LOC"] = 0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
data["ROC"] = -0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
ekg = 20 * rng.normal(size=n)
for c in np.arange(0.3, n / fs, 1 / 1.6):
i0 = int(c * fs)
if i0 + 10 < n:
ekg[i0:i0 + 10] += 900 * np.hanning(10)
data["EKG"] = ekg
for ch in data:
data[ch] = data[ch] + 2.0 * np.sin(2 * np.pi * line_hz * t)
for ch in bad.get("flat", ()):
data[ch] = rng.normal(0, 0.05, n)
for ch in bad.get("loud", ()):
data[ch] = data[ch] * 8
return data, n / fs
def edf_bytes(*, fs: float = 250.0, minutes: float = 4.0, rhythm_hz: float = 7.0, line_hz: float = 60.0,
bad: dict | None = None, seed: int = 0) -> bytes:
from edfio import Edf, EdfAnnotation, EdfSignal
data, duration = signals(fs=fs, minutes=minutes, rhythm_hz=rhythm_hz, line_hz=line_hz, bad=bad or {}, seed=seed)
labels = SCALP + list(EARS) + list(AUX)
annotations = [EdfAnnotation(0.5, None, "Paciente despierto"), EdfAnnotation(duration / 2 + 0.5, None, "Dormido")]
edf = Edf([EdfSignal(np.clip(data[ch], -FULL_SCALE, FULL_SCALE), fs, label=ch, physical_dimension="uV",
physical_range=(-FULL_SCALE, FULL_SCALE), digital_range=(-32767, 32767)) for ch in labels],
starttime=time(10, 0, 0), data_record_duration=1.0, annotations=annotations)
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "study.edf"
edf.write(path)
return path.read_bytes()
+117
View File
@@ -0,0 +1,117 @@
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
library.
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
posterior channels flat; and bytes that are not an EDF.
"""
import pytest
from synth_edf import edf_bytes
from core.tea.enums import CriterioEeg, ELECTRODOS_10_20, MetricaEeg
from models.eeg_analysis import checked_settings
from models.tea.eeg.analyze import criterion_code, measure, pipeline
from models.tea.eeg.settings import scenario_of, settings
FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
@pytest.fixture(scope="module")
def measured():
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old."""
s = settings()
return {
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
"flat": measure("flat", edf_bytes(minutes=4, bad={"flat": FLAT}, seed=1), 27.5, s),
"broken": measure("broken", b"not an edf", None, s),
}
def test_every_metric_is_a_feature_of_its_biomarker():
"""Pins down: each `MetricaEeg` code maps to a feature the library's biomarker actually measures.
Fails if `model.toml` names a feature, biomarker or electrode prefix the library doesn't have (a renamed feature
would otherwise leave the metric null on every EEG), or leaves a `MetricaEeg` code unmapped.
"""
s = checked_settings()
pipe = pipeline(s)
assert sorted(m.code for m in s.metrics) == sorted(c.value for c in MetricaEeg)
for m in s.metrics:
assert m.feature in pipe.module(m.biomarker).features, m.code
if m.electrodes:
electrodes = [f.removeprefix(m.electrode_prefix) for f in pipe.module(m.electrodes).features
if f.startswith(m.electrode_prefix)]
assert electrodes and set(electrodes) <= set(ELECTRODOS_10_20), m.code
def test_each_baseline_has_its_own_scenario_per_sleep_stage():
"""Pins down: a biomarker's baseline is registered per sleep stage, as `eeg-<biomarker>[-<stage>]`.
Fails if the two stages' spindles share one registered model, or the naming changes without the trained models.
"""
assert scenario_of("spindle_topography", "N2") == "eeg-spindle-topography-n2"
assert scenario_of("posterior_rhythm", None) == "eeg-posterior-rhythm"
assert len({m.scenario for m in settings().metrics}) == len(settings().metrics)
def test_a_clean_study_is_valid_and_has_every_metric(measured):
"""Pins down: a clean study gets the verdict, the study-wide checks and one value per metric, with the
spindles' value per electrode, the sleep it contains and the age it was measured at.
Fails if `measure` stops running the processes the biomarkers need, drops a metric, or loses the electrodes.
"""
m = measured["clean"]
assert (m.valid, m.level, m.error, m.asleep, m.age_months) == (1, "completo", None, 1, 27.5)
assert {c.code for c in m.checks} >= {"clean-windows", "internal-coverage", "usable-scalp", "triage-level"}
assert not any(c.abnormal for c in m.checks)
values = {v.code: v for v in m.metrics}
assert set(values) == {c.value for c in MetricaEeg}
assert values["RITMO_POSTERIOR"].value == pytest.approx(7.0, abs=0.5)
assert values["HUSOS_SUENO_N2"].value > 0
assert set(values["HUSOS_SUENO_N2"].electrodes) <= set(ELECTRODOS_10_20)
assert m.plan_hash and "spindle_detection=" in m.versions
def test_flat_channels_make_the_study_not_valid_with_a_check_per_electrode(measured):
"""Pins down: a study the validator rejects keeps its checks, one per bad channel with its electrode, and has
no metrics.
Fails if a rejected study is measured anyway, or the channel checks lose their electrode or normalised code.
"""
m = measured["flat"]
assert (m.valid, m.error, m.metrics) == (0, None, ())
dead = {c.electrode for c in m.checks if c.code == CriterioEeg.CANAL_MUERTO.value}
assert dead == set(FLAT)
assert any(c.decisive and c.abnormal and c.electrode is None for c in m.checks)
def test_a_file_that_is_not_an_edf_is_not_valid_rather_than_an_error(measured):
"""Pins down: unreadable bytes are the validator's `file` check, not an analysis error.
Fails if `measure` raises, or reports the file as an error (which would retry it on every run).
"""
m = measured["broken"]
assert (m.valid, m.error) == (0, None)
assert [c.code for c in m.checks] == [CriterioEeg.ARCHIVO.value]
def test_every_check_code_is_in_the_catalog(measured):
"""Pins down: the codes `measure` stores are `CriterioEeg` values.
Fails if the library adds or rewords a check and `criterion_code` stops normalising it.
"""
codes = {c.code for m in measured.values() for c in m.checks}
assert codes <= {c.value for c in CriterioEeg}
def test_channel_codes_lose_their_numbers():
"""Pins down: the library's channel codes, which embed the measured numbers, become fixed codes.
Fails if `criterion_code` stops mapping amplitude or burst reasons, or touches the study-wide codes.
"""
assert criterion_code("amplitude-4.5-x", "amplitude 4.5 x the scalp median", "C3") == "amplitude"
assert criterion_code("amplitude-25000-uv,", "amplitude 25000 uV, out of range even for ekg", "EKG") == \
"aux-amplitude"
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
"intermittent-bursts"
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
+223
View File
@@ -0,0 +1,223 @@
"""What this module covers: the EEG analysis around `measure`: the baselines' deviation (`models.tea.eeg.baselines`),
and `models.eeg_analysis`: writing an analysis back to bronze, choosing the pending EEGs, and the batch with its
governance log.
Fixtures: `tea_db` and `governance_db` (empty SQLite databases); `bronze`, two patients born 2024-01-01 with one EEG
each, studied 2026-03-01 (26.0 months): `e-1` with an EDF, `e-2` without one; `curves`, a baselines stand-in whose
posterior-rhythm curve has p5/median/p95 of 5/6/7 Hz at 24 months; `fake_measure`, a `measure` that returns a valid
measurement with a 9 Hz posterior rhythm and a spindle value at Fz, without the library.
"""
import math
from datetime import date
from types import SimpleNamespace
import pandas as pd
import pytest
from sqlmodel import select
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
from models.eeg_analysis import age_months, analyze_pending, checked_settings as settings, rows, save
from models.tea.eeg.analyze import Check, Measurement, MetricValue
from models.tea.eeg.baselines import Baselines, centiles
@pytest.fixture
def curves():
"""`Baselines` whose only production version is `tea-eeg-posterior-rhythm/3`, a centile curve over 12-36 months."""
from tea.biomarkers.posterior_rhythm._baseline import CentileCurves
curve = pd.DataFrame({"edad_meses": [12.0, 24.0, 36.0], "n_efectivo": [50.0] * 3, "p5": [4.0, 5.0, 6.0],
"p25": [4.5, 5.5, 6.5], "mediana": [5.0, 6.0, 7.0], "p75": [5.5, 6.5, 7.5],
"p95": [6.0, 7.0, 8.0]})
module = SimpleNamespace(baseline=CentileCurves(curva=curve))
class Registry:
def resolve(self, domain, scenario):
if scenario != "eeg-posterior-rhythm":
raise LookupError(scenario)
return SimpleNamespace(version="3", model_uri="models:/tea-eeg-posterior-rhythm/3")
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
@pytest.fixture
def bronze(tea_db):
"""Patients 1 and 2, born 2024-01-01; EEG `e-1` (patient 1, with an EDF) and `e-2` (patient 2, without)."""
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
session.add_all([
Pacientes(pac_id=1, pac_fecha_nacimiento=date(2024, 1, 1)),
Pacientes(pac_id=2, pac_fecha_nacimiento=date(2024, 1, 1)),
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1), eeg_estudio=b"edf", eeg_canales=99),
Eeg(eeg_id="e-2", eeg_pac_id=2, eeg_fecha_estudio=date(2026, 3, 1)),
])
session.commit()
def current(s):
"""The plan hash and module versions an analysis made now would store."""
from models.tea.eeg.analyze import pipeline, plan, versions
return plan(s)["hash"], versions(pipeline(s), s)
def fake_measure(key, edf, age, s):
"""A valid measurement of `key` with the current plan and versions: 9 Hz posterior rhythm, N2 spindles
3.0/min, 1.5 at Fz for each sleep stage's spindles, and one channel check."""
assert edf == b"edf"
values = {"RITMO_POSTERIOR": 9.0, "HUSOS_SUENO_N2": 3.0}
plan_hash, versions = current(s)
return Measurement(
key=key, age_months=age, plan_hash=plan_hash, versions=versions, valid=1, level="completo", clean_fraction=0.9,
bad_channels=1, line_db=10.0, channels=21, duration_min=20.0, asleep=1,
checks=(Check("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, True, False),
Check("dead-channel", "T3", None, "dead channel", None, None, None, False, True)),
metrics=tuple(MetricValue(m.code, values.get(m.code), {"Fz": 1.5} if m.electrodes else {})
for m in s.metrics),
)
def _all(model):
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
return session.exec(select(model)).all()
def test_a_value_is_compared_with_the_curve_at_the_childs_age(curves):
"""Pins down: z, -1/0/+1 and the curve's p5/median/p95 come from the promoted baseline at the age given.
Fails if `deviation` reads the wrong baseline, stops interpolating the centiles at the age, or reports a
deviation for a metric without a baseline in production.
"""
d = curves.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 9.0, 24.0)
assert (d.outside, d.p5, d.median, d.p95) == (1, 5.0, 6.0, 7.0)
assert d.z == pytest.approx((9.0 - 6.0) / (1.0 / 1.645))
assert curves.deviation("eeg-spikes", "spike_rate_nrem", 1.0, 24.0) is None
assert curves.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 9.0, None).z is None
assert curves.label("eeg-posterior-rhythm") == "tea-eeg-posterior-rhythm/3"
def test_an_age_outside_the_curve_has_no_centiles(curves):
"""Pins down: no p5/median/p95 outside the ages the curve covers, as the library gives no z there.
Fails if `centiles` extrapolates the curve.
"""
baseline = curves.module("eeg-posterior-rhythm").baseline
assert centiles(baseline, 60.0) == (None, None, None)
assert centiles(baseline, 18.0)[1] == pytest.approx(5.0 + math.log(18 / 12) / math.log(2))
def test_the_age_is_completed_months_at_the_study():
"""Pins down: the age is days / 30.4375 to one decimal, and unknown without both dates or before birth.
Fails if the analysis counts ages differently from the TEA cohort.
"""
assert age_months(date(2024, 1, 1), date(2026, 3, 1), 30.4375) == 26.0
assert age_months(None, date(2026, 3, 1), 30.4375) is None
assert age_months(date(2026, 3, 2), date(2026, 3, 1), 30.4375) is None
def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves):
"""Pins down: writing an analysis sets the EEG's columns and replaces its checks, metrics and electrodes; a
second write of the same analysis leaves the same rows with the same ids.
Fails if `save` appends instead of replacing, or row ids stop deriving from the EEG and what each row is (the
silver load would then see every re-analysis as new rows).
"""
from persistance.tea import eeg_repository
m = fake_measure("e-1", b"edf", 26.0, settings())
for _ in range(2):
with eeg_repository.open_session() as session:
save(session, "e-1", rows(m, settings(), curves))
session.commit()
eeg = eeg_repository.get("e-1")
assert (eeg.eeg_valido, eeg.eeg_nivel, eeg.eeg_canales, eeg.eeg_edad_meses, eeg.eeg_plan_hash) == \
(1, "completo", 21, 26.0, current(settings())[0])
assert sorted((c.cri_codigo, c.cri_electrodo) for c in _all(EegCriterio)) == \
[("dead-channel", "T3"), ("usable-scalp", None)]
metrics = {x.met_codigo: x for x in _all(EegMetrica)}
assert len(metrics) == 5
assert (metrics["RITMO_POSTERIOR"].met_fuera, metrics["RITMO_POSTERIOR"].met_modelo) == \
(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"))
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
"""Pins down: only EEGs with an EDF are analysed, the child's age goes to the measurement, each result is
logged as an `ExtractionRun`, and a second batch with the same plan, versions and baselines does nothing.
Fails if the pending selection stops skipping analysed EEGs or EEGs without an EDF, or the batch stops logging.
"""
from persistance.governance import extraction_run_repository
first = analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure)
assert (first.pending, first.valid, first.failed) == (1, 1, 0)
assert {e.eeg_id: e.eeg_edad_meses for e in _all(Eeg)} == {"e-1": 26.0, "e-2": None}
assert [(r.entity, r.entity_pk, r.estatus) for r in extraction_run_repository.list()] == \
[("eeg", "e-1", "COMPLETADA")]
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure).pending == 0
def test_a_new_baseline_in_production_makes_valid_eegs_pending(bronze, governance_db, curves):
"""Pins down: a valid EEG analysed against one baseline version is pending again once another is promoted.
Fails if the pending selection stops comparing `met_modelo` with the versions now in production.
"""
analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure)
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure).pending == 0
curves._resolved["eeg-posterior-rhythm"] = SimpleNamespace(version="4", model_uri="models:/x/4")
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure, log_runs=False).pending == 1
def test_a_failed_study_is_stored_and_not_retried(bronze, governance_db, curves):
"""Pins down: a study whose analysis failed is written with its error and logged FALLIDA, and the next batch
with the same plan and versions leaves it alone.
Fails if a failure stops being stored (the EEG would be retried on every cycle) or stops being logged.
"""
from persistance.governance import extraction_run_repository
def failed(key, edf, age, s):
plan_hash, versions = current(s)
return Measurement(key=key, age_months=age, plan_hash=plan_hash, versions=versions,
error="MemoryError: worker killed")
def never(*args):
raise AssertionError("an EEG that failed with these versions was analysed again")
summary = analyze_pending(cluster="sync", baselines=curves, measure_fn=failed)
assert (summary.pending, summary.failed) == (1, 1)
assert {e.eeg_id: e.eeg_error for e in _all(Eeg)}["e-1"] == "MemoryError: worker killed"
assert [r.estatus for r in extraction_run_repository.list()] == ["FALLIDA"]
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=never).pending == 0
def test_the_real_analysis_writes_a_synthetic_study(tea_db, governance_db, curves):
"""Pins down: the whole chain on the real library, from an EDF stored in `eeg` to its verdict, checks and
metrics in bronze, with the posterior rhythm compared with its curve.
Fails if `measure` and `store` stop agreeing on the shape of a measurement, or the batch stops reading the
stored EDF.
"""
from synth_edf import edf_bytes
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
session.add_all([Pacientes(pac_id=1, pac_fecha_nacimiento=date(2024, 1, 1)),
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 7, 1),
eeg_estudio=edf_bytes(minutes=4))])
session.commit()
summary = analyze_pending(cluster="sync", baselines=curves)
assert (summary.valid, summary.failed) == (1, 0)
assert eeg_repository.get("e-1").eeg_con_sueno == 1
rhythm = {m.met_codigo: m for m in _all(EegMetrica)}["RITMO_POSTERIOR"]
assert rhythm.met_valor == pytest.approx(7.0, abs=0.5)
assert 6.0 < rhythm.met_mediana < 7.0 and rhythm.met_p5 < rhythm.met_valor < rhythm.met_p95
assert rhythm.met_fuera == 0
assert {c.cri_codigo for c in _all(EegCriterio)} >= {"clean-windows", "usable-scalp"}
+132
View File
@@ -0,0 +1,132 @@
"""What this module covers: the EEG age baselines (`models.tea.eeg.train`, `models.tea.eeg.model`): the reference
listing, the training table, training and registering each scenario with what the registry's promotion checks read,
promotion, and the analysis scoring a value with a promoted baseline.
Fixtures: `mlflow_tracking` (a SQLite MLflow per test); `reference`, a synthetic reference cohort with no EDF: 200
children of 16 to 36 months whose every feature rises with age plus noise, as `ReferenceStudy` rows of each biomarker
and sleep stage the metrics read, and the listing they'd come from.
"""
import numpy as np
import pytest
from models.tea.eeg import train
from models.tea.eeg.analyze import ReferenceStudy, pipeline
from models.tea.eeg.settings import settings
@pytest.fixture
def reference():
"""(listing, studies): 200 valid children whose features are 1 + 0.02 x age + noise; one more invalid and one
failed, which training must leave out."""
s = settings()
pipe = pipeline(s)
rng = np.random.default_rng(0)
ages = np.round(np.sort(rng.uniform(16, 36, 200)), 1)
found = train.Listing.of("prueba", [(f"s3://prueba/{k}.edf", float(a)) for k, a in enumerate(ages)])
studies = []
for (key, _, age) in found.studies:
features = {(b, phase): {f: float(abs(1 + 0.02 * age + rng.normal(0, 0.2))) for f in pipe.module(b).features}
for b, phase in s.scenarios.values()}
studies.append(ReferenceStudy(key, age, 1, features))
studies += [ReferenceStudy("prueba-x", 20.0, 0), ReferenceStudy("prueba-y", 20.0, error="ValueError: boom")]
return found, studies
def test_a_listing_is_identified_by_its_studies_not_their_order():
"""Pins down: the listing's keys are positions (no file names leave), and its hash depends on which studies and
ages it holds, not on the order they were found in.
Fails if a key carries a file name, or the hash changes with the order S3 lists the files in.
"""
a = train.Listing.of("hk1k", [("s3://x/b.edf", 20.0), ("s3://x/a.edf", 30.0)])
b = train.Listing.of("hk1k", [("s3://x/a.edf", 30.0), ("s3://x/b.edf", 20.0)])
assert a == b and [k for k, _, _ in a.studies] == ["hk1k-0001", "hk1k-0002"]
assert train.Listing.of("hk1k", [("s3://x/a.edf", 31.0), ("s3://x/b.edf", 20.0)]).sha256 != a.sha256
def test_the_table_takes_only_valid_measured_studies(reference):
"""Pins down: a baseline trains on the valid, measured studies' features of its biomarker and stage, with their
ages. Fails if an invalid or failed study reaches a curve."""
_, studies = reference
data = train.table(studies, "spindles", "N2")
assert len(data) == 200 and "age_months" in data and "spindle_density_per_min_channel" in data
def test_each_scenario_is_registered_with_what_promotion_checks(mlflow_tracking, reference):
"""Pins down: training registers every scenario as `tea-<scenario>` with its environment, the reference cohort
(ML-03), its model hash (ML-01b), the five routine records (ML-01a) and metrics; training again on the same
listing, plan and module versions registers nothing; and until the reports are attached, promotion is refused.
Fails if a scenario is missing, a promotion input stops being recorded, re-training duplicates versions, or a
baseline reaches production without the clinical validation report.
"""
from models.io.registry import PromotionBlocked, registry
found, studies = reference
s = settings()
first = train.train_all(s, "PROD", found=found, studies=studies)
assert set(first) == set(s.scenarios) and all(new for _, new in first.values())
assert train.train_all(s, "PROD", found=found, studies=[]) == {k: (v, False) for k, (v, _) in first.items()}
version = first["eeg-posterior-rhythm"][0]
checks = {(c.code, c.requirement): c for c in registry.checks("tea", "eeg-posterior-rhythm", version)}
passed = {code for (code, _), c in checks.items() if c.passed}
assert {"ML-02", "ML-03", "ML-01a", "ML-01b"} <= passed
assert "listado" in checks["ML-03", "enlazada al armado de cohorte con el que se entrenó"].detail
assert "MLD-01b" not in passed
with pytest.raises(PromotionBlocked):
registry.promote("tea", "eeg-posterior-rhythm", version)
def test_a_promoted_baseline_scores_the_analysis(mlflow_tracking, reference):
"""Pins down: once its reports are attached, a baseline is promoted, and the analysis's `Baselines` loads it
from the registry and gives a value at an age its curve covers a z, -1/0/+1 and the curve's centiles.
Fails if the registered model stops being the library's (the analysis couldn't load it), or promotion and the
analysis disagree on the scenario's registered name.
"""
from models.io.registry import registry
from models.tea.eeg.baselines import Baselines
found, studies = reference
s = settings()
(version, _) = train.train_all(s, "PROD", found=found, studies=studies)["eeg-posterior-rhythm"]
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
registry.promote("tea", "eeg-posterior-rhythm", version)
baselines = Baselines("tea")
median = 1 + 0.02 * 26
d = baselines.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", median, 26.0)
assert d is not None and abs(d.z) < 1 and d.outside == 0 and d.p5 < median < d.p95
assert baselines.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", median + 2, 26.0).outside == 1
assert baselines.label("eeg-posterior-rhythm") == f"tea-eeg-posterior-rhythm/{version}"
def test_run_takes_only_train_and_promote_for_the_baselines(mlflow_tracking):
"""Pins down: `models run tea eeg` runs the baselines' own steps: a cohort step is refused, and promoting with
nothing trained says so and fails.
Fails if the scenario falls back to the cohort-file steps, which it has no file for.
"""
from models.__main__ import main
assert main(["run", "tea", "eeg", "--export"]) == 2
assert main(["run", "tea", "eeg", "--promote"]) == 1
def test_a_reference_study_is_measured_from_its_path(tmp_path):
"""Pins down: `reference` reads a study from a path, at the cohort's mains frequency, and returns every feature
of each biomarker and stage the metrics read.
Fails if the reference unit stops sharing the analysis's study (validation, processes, per-stage spindles).
"""
from synth_edf import edf_bytes
from models.tea.eeg.analyze import reference as measure_reference
path = tmp_path / "study.edf"
path.write_bytes(edf_bytes(minutes=4, line_hz=50.0))
st = measure_reference("prueba-0001", str(path), 27.0, settings(), 50.0)
assert (st.valid, st.error) == (1, None)
assert set(st.features) == set(settings().scenarios.values())
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)