241 lines
12 KiB
Python
241 lines
12 KiB
Python
"""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 tea.pipeline.run_monitor import active_monitor, monitor_from_env
|
|
|
|
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 experiment_id, 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: (path, age in months) of each reference EDF with an age inside `[reference] ages`, from the
|
|
cluster's S3 or, for a cohort on this machine, from its folder (`reference.local_studies`)."""
|
|
from tea.pipeline.storage import s3
|
|
|
|
from models.tea.eeg.reference import LOCAL, local_studies
|
|
|
|
r = s.reference
|
|
if r.storage == LOCAL:
|
|
return local_studies(s)
|
|
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, track_progress=False)
|
|
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)
|
|
monitor = active_monitor()
|
|
if monitor is not None:
|
|
monitor.phase("ajustando")
|
|
module.train(data)
|
|
sha, state = _module_state(module)
|
|
name = registered_name(DOMAIN, scenario)
|
|
if monitor is not None:
|
|
monitor.phase("registrando")
|
|
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
|
|
experiment_id(MlflowClient(), name)
|
|
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)}
|
|
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},
|
|
}
|
|
metrics = {"n_referencia": len(data), **{f"n.{feature}": n for feature, n in present.items()}}
|
|
if covered:
|
|
metrics.update(edad_min_cubierta=covered[0], edad_max_cubierta=covered[1])
|
|
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.")
|
|
record(client, name, version, run_id, tags=tags, routines=routines, metrics=metrics, description=description)
|
|
return version
|
|
|
|
|
|
def record(client, name: str, version: str, run_id: str, *, tags: dict[str, str], routines: dict[str, dict],
|
|
metrics: dict[str, float], description: str) -> None:
|
|
"""What the registry's promotion checks read, on a version and its run: the tags (on both, with the code
|
|
version on the run), the routine records, the metrics and the description."""
|
|
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)
|
|
for kind, routine in routines.items():
|
|
client.log_text(run_id, json.dumps(routine, ensure_ascii=False, indent=1, default=str), routine_path(kind))
|
|
for key, value in metrics.items():
|
|
client.log_metric(run_id, key, value)
|
|
client.update_model_version(name, version, description=description)
|
|
|
|
|
|
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."""
|
|
with monitor_from_env() as monitor:
|
|
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:
|
|
if studies is None:
|
|
monitor.total(len(found.studies))
|
|
monitor.phase("midiendo")
|
|
studies = 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})
|