TEA EEG baselines trained on a local cohort and moved between installations as a bundle of group numbers

This commit is contained in:
AlbertoPMDM
2026-11-20 09:36:41 -06:00
parent 7b8a4e8499
commit 70646e64b6
8 changed files with 553 additions and 17 deletions
+1
View File
@@ -33,6 +33,7 @@ WebApi.
| `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. |
| `tea/eeg/reference.py`, `tea/eeg/bundle.py` | Training the baselines where the EEGs live and shipping only the result. `models run tea eeg --train --reference-dir DIR [--reference-ages edades.csv] [--reference-name NAME] [--line-hz 60]` trains on a folder of EDFs on this machine (ages from the table's `archivo` and `edad_meses` or `edad_anos`, or from each EDF header); file names stay in the listing, keyed by position. `models tea export-baselines --out baselines.zip [--environment prod] [--production]` writes every scenario's trained module, plan, routine records, metrics and promotion tags, with a SHA-256 manifest, after the library's privacy guard; `models tea import-baselines baselines.zip` checks the manifest, accepts only the module class the platform runs for each scenario, requires the trained module's hash, and registers new versions with the same tags (an already-registered module is kept). Promotion still waits for the three reports. |
| `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. |
+47
View File
@@ -152,6 +152,37 @@ def _tea_analyze(args: argparse.Namespace) -> int:
return 1 if s.failed else 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
from models.tea.eeg.settings import settings
try:
done = export(settings(), args.out, environment=args.environment.upper(), production=args.production)
except BundleError as error:
print(f"not exported: {error}", file=sys.stderr)
return 1
for scenario, version in done.versions.items():
print(f"{scenario}: version {version}")
print(f"written: {done.path} (sha256 {done.sha256})")
return 0
def _tea_import_baselines(args: argparse.Namespace) -> int:
"""The age baselines of a bundle, registered (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, import_
from models.tea.eeg.settings import settings
try:
done = import_(settings(), args.bundle)
except BundleError as error:
print(f"not imported: {error}", file=sys.stderr)
return 1
for scenario, (version, new) in done.items():
print(f"{scenario}: {'imported as' if new else 'already registered as'} version {version}")
return 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)):
@@ -447,6 +478,11 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.add_argument("--reference-dir", help="tea eeg: train on the EDFs of this folder instead of the configured cohort")
run.add_argument("--reference-ages", help="tea eeg: CSV of `archivo` and `edad_meses` (or `edad_anos`); "
"without it, each EDF header's age")
run.add_argument("--reference-name", help="tea eeg: a name for that cohort (no names or dates of people)")
run.add_argument("--line-hz", type=float, help="tea eeg: the mains frequency where it was recorded (60)")
run.set_defaults(run=lambda args: _run(run, args))
tea = commands.add_parser("tea", help="TEA's EEG analysis")
@@ -459,6 +495,17 @@ 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)
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)")
export_baselines.add_argument("--environment", choices=["dev", "prod"], default="prod")
export_baselines.add_argument("--production", action="store_true",
help="the versions in production, instead of the newest trained in --environment")
export_baselines.set_defaults(run=_tea_export_baselines)
import_baselines = tea_actions.add_parser(
"import-baselines", help="register the age baselines of a bundle; promotion still needs their reports")
import_baselines.add_argument("bundle", help="the bundle `export-baselines` wrote")
import_baselines.set_defaults(run=_tea_import_baselines)
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
+205
View File
@@ -0,0 +1,205 @@
"""Trained age baselines as a bundle: exported where they were trained, imported on each platform installation.
What the bundle holds, per scenario: the trained module's saved state (`params.json`, `baseline.json`), which
module it is (`module.json`), the preprocessing plan (`plan.json`), the routine records, the metrics, the
version's promotion tags and its description; and a manifest with each file's SHA-256. Group numbers only: the
library's privacy guard runs over every file before the bundle is written, and refuses a group under 5.
The import checks the manifest, accepts for each scenario only the library module the platform runs for it,
requires the module's hash to match the one recorded where it was trained, and registers it as a new version
with the same tags, routine records and metrics, so the registry's promotion checks read it as trained. A
version already holding that trained module is kept.
"""
import hashlib
import io
import json
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, GIT_COMMIT_TAG, MODEL_SHA_TAG
from models.io.lineage import registered_name
from models.io.tracking import ROUTINES_PATH, experiment_id
from models.tea.eeg import train
from models.tea.eeg.analyze import pipeline
from models.tea.eeg.settings import Settings
FORMAT = 1
MANIFEST = "manifest.json"
# The version tags a bundle carries: what promotion checks and what identifies the trained module. Report links
# and promotion dates belong to each installation.
TAGS = ("domain", "scenario", "environment", MODEL_SHA_TAG, COHORT_URL_TAG, COHORT_SOURCE_TAG, COHORT_BUILD_TAG,
"plan_hash", "module", "module_version", "phase", "baseline")
SOURCE_COMMIT_TAG = "origen.git_commit"
BUNDLE_TAG = "importado.paquete"
EPOCH = (1980, 1, 1, 0, 0, 0) # every zip entry's date, so the same baselines give the same bundle
class BundleError(ValueError):
"""A bundle that can't be exported or imported as it is, with the reason."""
@dataclass(frozen=True)
class Exported:
path: Path
sha256: str
versions: dict[str, str]
def _sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def state_sha(folder: Path) -> str:
"""The trained module's hash, as training records it (`train._module_state`): its saved JSON files."""
files = sorted(p for p in Path(folder).glob("*.json") if p.name in ("params.json", "baseline.json"))
return _sha(b"".join(f.name.encode() + f.read_bytes() for f in files))
def _version(client, scenario: str, environment: str, production: bool):
from models.io.registry import PRODUCTION_ALIAS
name = registered_name(train.DOMAIN, scenario)
if production:
try:
return client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except Exception: # noqa: BLE001 -- none in production
return None
return train.latest(scenario, environment)
def export(s: Settings, out: str | Path, *, environment: str = "PROD", production: bool = False) -> Exported:
"""Every scenario's baseline into one bundle at `out`: the version in production with `production`, otherwise
the newest trained in `environment`. Refuses a bundle missing a scenario, or holding something the privacy
guard refuses."""
import mlflow.artifacts
from mlflow import MlflowClient
from tea.serving.privacy import check_files, check_group, check_text
client = MlflowClient()
versions = {scenario: _version(client, scenario, environment, production) for scenario in s.scenarios}
missing = sorted(k for k, mv in versions.items() if mv is None)
if missing:
raise BundleError(f"no {'production' if production else environment} version of {', '.join(missing)}")
manifest = {"formato": FORMAT, "dominio": train.DOMAIN, "escenarios": {}}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for scenario, mv in versions.items():
folder = root / scenario
module_dir = folder / "module"
module_dir.mkdir(parents=True)
model = Path(mlflow.artifacts.download_artifacts(artifact_uri=f"models:/{mv.name}/{mv.version}",
dst_path=str(root / ".descargas" / scenario)))
saved = next((p.parent for p in model.rglob("module.json") if p.parent.name == "module"), None)
if saved is None:
raise BundleError(f"{scenario} version {mv.version}: its model has no trained module")
for file in ("params.json", "baseline.json", "module.json", "plan.json"):
if not (saved / file).exists():
raise BundleError(f"{scenario} version {mv.version}: its trained module has no {file}")
(module_dir / file).write_bytes((saved / file).read_bytes())
if state_sha(module_dir) != mv.tags.get(MODEL_SHA_TAG):
raise BundleError(f"{scenario} version {mv.version}: its saved state isn't the one it was trained with")
routines = folder / ROUTINES_PATH
routines.mkdir()
for item in client.list_artifacts(mv.run_id, ROUTINES_PATH):
local = mlflow.artifacts.download_artifacts(run_id=mv.run_id, artifact_path=item.path,
dst_path=str(root / ".descargas"))
(routines / Path(item.path).name).write_text(Path(local).read_text())
run = client.get_run(mv.run_id)
metrics = dict(run.data.metrics)
tags = {k: mv.tags[k] for k in TAGS if k in mv.tags}
if run.data.tags.get(GIT_COMMIT_TAG):
tags[SOURCE_COMMIT_TAG] = run.data.tags[GIT_COMMIT_TAG]
check_group(module_dir, int(metrics.get("n_referencia", 0)) or None)
files = sorted(p for p in folder.rglob("*") if p.is_file())
manifest["escenarios"][scenario] = {
"version_origen": str(mv.version), "tags": tags, "metricas": metrics,
"descripcion": mv.description or "",
"archivos": {p.relative_to(root).as_posix(): _sha(p.read_bytes()) for p in files},
}
text = json.dumps(manifest, ensure_ascii=False, indent=1, sort_keys=True)
check_text(text)
(root / MANIFEST).write_text(text)
for scenario in versions:
check_files(root / scenario)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as z:
for p in sorted(q for q in root.rglob("*") if q.is_file() and ".descargas" not in q.parts):
z.writestr(zipfile.ZipInfo(p.relative_to(root).as_posix(), EPOCH), p.read_bytes())
out = Path(out)
out.write_bytes(buffer.getvalue())
return Exported(out, _sha(buffer.getvalue()), {k: str(mv.version) for k, mv in versions.items()})
def _unpack(data: bytes, root: Path) -> dict:
"""The bundle's files under `root`, each checked against the manifest; the manifest."""
with zipfile.ZipFile(io.BytesIO(data)) as z:
names = z.namelist()
for name in names:
path = PurePosixPath(name)
if path.is_absolute() or ".." in path.parts:
raise BundleError(f"the bundle holds a path outside itself: {name}")
if MANIFEST not in names:
raise BundleError("the bundle has no manifest")
manifest = json.loads(z.read(MANIFEST))
if manifest.get("formato") != FORMAT or manifest.get("dominio") != train.DOMAIN:
raise BundleError("not a bundle of TEA's EEG baselines in a format this platform reads")
listed = {f: sha for entry in manifest["escenarios"].values() for f, sha in entry["archivos"].items()}
if set(listed) != set(names) - {MANIFEST}:
raise BundleError("the bundle's files aren't the ones its manifest lists")
for name, sha in listed.items():
content = z.read(name)
if _sha(content) != sha:
raise BundleError(f"{name} changed after the bundle was written")
target = root / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
return manifest
def import_(s: Settings, bundle: str | Path) -> dict[str, tuple[str, bool]]:
"""Registers every baseline of the bundle; by scenario, (version, whether it's new)."""
from mlflow import MlflowClient
from tea.serving import log_biomarker
data = Path(bundle).read_bytes()
bundle_sha = _sha(data)
pipe = pipeline(s)
out = {}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
manifest = _unpack(data, root)
unknown = sorted(set(manifest["escenarios"]) - set(s.scenarios))
if unknown:
raise BundleError(f"this platform has no scenario {', '.join(unknown)}")
for scenario, entry in manifest["escenarios"].items():
tags = dict(entry["tags"])
module_dir = root / scenario / "module"
sha = state_sha(module_dir)
if sha != tags.get(MODEL_SHA_TAG):
raise BundleError(f"{scenario}: the module isn't the one recorded where it was trained")
biomarker, phase = s.scenarios[scenario]
if tags.get("module") != biomarker or (tags.get("phase") or None) != phase:
raise BundleError(f"{scenario}: the bundle says it's {tags.get('module')}, not {biomarker}")
cls = type(pipe.module(biomarker))
declared = json.loads((module_dir / "module.json").read_text()).get("class")
if declared != f"{cls.__module__}:{cls.__name__}":
raise BundleError(f"{scenario}: the bundle's module class isn't the one this platform runs")
existing = train.find_trained(scenario, {MODEL_SHA_TAG: sha, COHORT_BUILD_TAG: tags.get(COHORT_BUILD_TAG, ""),
"environment": tags.get("environment", "")})
if existing is not None:
out[scenario] = (str(existing.version), False)
continue
module = cls.load(module_dir)
name = registered_name(train.DOMAIN, scenario)
client = MlflowClient()
experiment_id(client, name)
n = int(entry["metricas"].get("n_referencia", 0)) or None
mv = log_biomarker(module, plan=json.loads((module_dir / "plan.json").read_text()), registered_name=name,
run_name=scenario, n_reference=n, experiment=name)
routines = {p.stem: json.loads(p.read_text()) for p in sorted((root / scenario / ROUTINES_PATH).glob("*.json"))}
train.record(client, name, str(mv.version), mv.run_id, tags={**tags, BUNDLE_TAG: bundle_sha},
routines=routines, metrics=entry["metricas"], description=entry["descripcion"])
out[scenario] = (str(mv.version), True)
return out
+12 -2
View File
@@ -2,7 +2,8 @@
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.
then promoting each through the registry's checks. `--reference-dir` trains on a folder of EEGs on this machine
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
"""
import argparse
import sys
@@ -20,9 +21,18 @@ def run_steps(args: argparse.Namespace) -> int:
print("tea/eeg trains on its reference cohort: only --train and --promote apply", file=sys.stderr)
return 2
environment = args.environment.upper()
s = SETTINGS
if getattr(args, "reference_dir", None):
from models.tea.eeg.reference import local
s = local(SETTINGS, folder=args.reference_dir, ages_table=args.reference_ages,
name=args.reference_name or "local", line_hz=args.line_hz or 60.0)
elif getattr(args, "reference_ages", None) or getattr(args, "line_hz", None):
print("--reference-ages and --line-hz go with --reference-dir", file=sys.stderr)
return 2
versions: dict[str, str] = {}
if args.train:
for scenario, (version, new) in train.train_all(SETTINGS, environment).items():
for scenario, (version, new) in train.train_all(s, environment).items():
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
versions[scenario] = version
if not args.promote:
+62
View File
@@ -0,0 +1,62 @@
"""A reference cohort on the training machine's own disk: the site's EEGs, which never leave it.
`local_studies` lists a folder's EDFs (at any depth) with the age of each child at the recording, within
`[reference] ages`. The age comes from the ages table when one is given (`archivo` and `edad_meses` or `edad_anos`
columns, one row per file name) and from each EDF's header (recording start minus birth date) otherwise. A file with
no age is left out. Paths stay in the listing on this machine; what leaves it is the trained baselines and the
listing's hash (`train.Listing`).
"""
import dataclasses
from pathlib import Path
import pandas as pd
from models.tea.eeg.settings import Settings
LOCAL = "local"
def local(s: Settings, *, folder: str | Path, ages_table: str | Path | None = None, name: str = "local",
line_hz: float = 60.0, ages: tuple[float, float] | None = None) -> Settings:
"""`s` with its reference cohort replaced by a folder on this machine."""
r = dataclasses.replace(s.reference, name=name, storage=LOCAL, prefix=str(Path(folder).resolve()),
ages_table=str(Path(ages_table).resolve()) if ages_table else "", line_hz=float(line_hz),
ages=tuple(ages) if ages else s.reference.ages)
return dataclasses.replace(s, reference=r)
def _table_ages(path: Path) -> dict[str, float]:
"""Age in months by file name, from a CSV with `archivo` and `edad_meses` (or `edad_anos`)."""
table = pd.read_csv(path)
if "archivo" not in table:
raise ValueError(f"{path.name}: the ages table needs an `archivo` column with each EDF's file name")
if "edad_meses" in table:
months = table["edad_meses"].astype(float)
elif "edad_anos" in table:
months = table["edad_anos"].astype(float) * 12
else:
raise ValueError(f"{path.name}: the ages table needs `edad_meses` or `edad_anos`")
return {str(f): round(float(m), 1) for f, m in zip(table["archivo"], months) if m == m}
def local_studies(s: Settings) -> list[tuple[str, float]]:
"""(path, age in months) of each EDF under the reference folder with an age inside `[reference] ages`."""
from tea.contracts import header_age_months
r = s.reference
folder = Path(r.prefix)
if not folder.is_dir():
raise FileNotFoundError(f"no folder {folder}")
by_name = _table_ages(Path(r.ages_table)) if r.ages_table else None
found = []
for path in sorted(p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() == ".edf"):
if by_name is not None:
age = by_name.get(path.name)
else:
try:
age = header_age_months(path, days_per_month=s.days_per_month)
except Exception: # noqa: BLE001 -- an unreadable header is a file with no age
age = None
if age is not None and r.ages[0] <= age <= r.ages[1]:
found.append((str(path), age))
return found
+1
View File
@@ -34,6 +34,7 @@ class Reference:
ages_table: str
line_hz: float
ages: tuple[float, float]
storage: str = "s3" # "s3": the cluster's S3, read in a worker; "local": a folder on this machine (`reference.py`)
@dataclass(frozen=True)
+26 -15
View File
@@ -52,10 +52,15 @@ class Listing:
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`."""
"""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)]
@@ -153,11 +158,6 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
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 {}
@@ -179,21 +179,32 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
"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)
metrics = {"n_referencia": len(data), **{f"n.{feature}": n for feature, n in present.items()}}
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=(
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."))
"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
+199
View File
@@ -0,0 +1,199 @@
"""What this module covers: training the EEG age baselines on a cohort on the training machine's own disk
(`models.tea.eeg.reference`), and moving the trained baselines between installations as a bundle
(`models.tea.eeg.bundle`), with nothing per child in it.
Fixtures: `two_stores`, a site's MLflow store and a platform's, each a SQLite file with its own artifact folder,
switched by the returned function; `trained`, the seven baselines trained in the site's store on a synthetic
reference cohort with no EDF (200 children of 16 to 36 months whose features rise with age), as PROD versions.
"""
import io
import json
import zipfile
from datetime import date
import numpy as np
import pytest
from models.tea.eeg import bundle, train
from models.tea.eeg.analyze import ReferenceStudy, pipeline
from models.tea.eeg.reference import local, local_studies
from models.tea.eeg.settings import settings
@pytest.fixture
def two_stores(tmp_path, monkeypatch):
"""`use("sitio")` or `use("plataforma")` points MLflow, and the registry, at that installation's store."""
import mlflow
monkeypatch.chdir(tmp_path)
def use(name: str) -> None:
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / f"{name}-artefactos"))
mlflow.set_tracking_uri(uri)
use("sitio")
return use
@pytest.fixture
def trained(two_stores):
"""The seven scenarios trained as PROD in the site's store; returns their versions by scenario."""
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("sitio", [(f"/datos/eeg/{k}.edf", float(a)) for k, a in enumerate(ages)])
studies = [ReferenceStudy(key, age, 1, {(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()})
for key, _, age in found.studies]
return {k: v for k, (v, _) in train.train_all(s, "PROD", found=found, studies=studies).items()}
def test_a_local_cohort_lists_its_edfs_with_the_table_or_header_age(tmp_path):
"""Pins down: a local cohort is every EDF under its folder, at any depth, with the age of its ages table, or of
its header without one; files without an age or outside the age range are left out.
Fails if a nested EDF is missed, an age outside `[reference] ages` gets in, or the header stops being the
fallback.
"""
from synth_edf import edf_bytes
folder = tmp_path / "eeg"
(folder / "2026").mkdir(parents=True)
born = date(2023, 1, 1)
(folder / "a.edf").write_bytes(edf_bytes(minutes=0.1, birthdate=born, startdate=date(2025, 1, 1))) # 24.0 m
(folder / "2026" / "b.EDF").write_bytes(edf_bytes(minutes=0.1, birthdate=born, startdate=date(2026, 6, 1)))
(folder / "c.edf").write_bytes(edf_bytes(minutes=0.1)) # no birth date in the header
s = local(settings(), folder=folder, line_hz=60)
assert [(p.split("/")[-1], a) for p, a in local_studies(s)] == [("a.edf", 24.0)] # b is 41 months
table = tmp_path / "edades.csv"
table.write_text("archivo,edad_anos\na.edf,1.5\nb.EDF,2.5\nc.edf,\n")
s = local(settings(), folder=folder, ages_table=table, line_hz=60)
assert sorted((p.split("/")[-1], a) for p, a in local_studies(s)) == [("a.edf", 18.0), ("b.EDF", 30.0)]
assert (s.reference.storage, s.reference.line_hz) == ("local", 60.0)
def test_a_local_cohort_trains_through_the_listing(tmp_path, monkeypatch):
"""Pins down: `listing` reads a local cohort on this machine, keyed by position, so its file names never reach
MLflow; its hash still changes with the files.
Fails if the listing goes back to S3 for a local cohort, or a key carries a file name.
"""
from synth_edf import edf_bytes
folder = tmp_path / "eeg"
folder.mkdir()
(folder / "garcia-lopez.edf").write_bytes(edf_bytes(minutes=0.1, birthdate=date(2023, 1, 1),
startdate=date(2025, 1, 1)))
found = train.listing(local(settings(), folder=folder, name="sitio"), cluster="sync")
assert [k for k, _, _ in found.studies] == ["sitio-0001"]
assert "garcia" not in found.sha256
def test_the_bundle_holds_group_numbers_only_and_imports_as_trained(trained, two_stores, tmp_path):
"""Pins down: the bundle has every scenario's trained state, plan, routine records, metrics and tags, and no
reference path or study key; imported into another store, each baseline is a new version with the same model
hash, cohort and routine records, so the registry's checks pass as where it was trained, and it scores the
analysis once promoted; importing the same bundle again registers nothing.
Fails if a per-study value or path reaches the bundle, the import changes the trained module, drops a promotion
input, or duplicates versions.
"""
from models.io.registry import registry
from models.tea.eeg.baselines import Baselines
out = tmp_path / "baselines.zip"
exported = bundle.export(settings(), out, environment="PROD")
assert exported.versions == trained
with zipfile.ZipFile(out) as z:
names = z.namelist()
text = b"".join(z.read(n) for n in names).decode()
manifest = json.loads(z.read(bundle.MANIFEST))
assert set(manifest["escenarios"]) == set(settings().scenarios)
assert "eeg-spindles-n2/module/baseline.json" in names and "eeg-spindles-n2/rutinas/MUESTREO.json" in names
assert "/datos/eeg" not in text and "sitio-0001" not in text
site_sha = manifest["escenarios"]["eeg-posterior-rhythm"]["tags"]["modelo_sha"]
two_stores("plataforma")
first = bundle.import_(settings(), out)
assert all(new for _, new in first.values())
assert bundle.import_(settings(), out) == {k: (v, False) for k, (v, _) in first.items()}
version = first["eeg-posterior-rhythm"][0]
mv = registry.get("tea", "eeg-posterior-rhythm", version)
assert (mv.tags["modelo_sha"], mv.tags["cohort.source"], mv.tags[bundle.BUNDLE_TAG]) == \
(site_sha, "referencia", exported.sha256)
passed = {c.code for c in registry.checks("tea", "eeg-posterior-rhythm", version) if c.passed}
assert {"ML-02", "ML-03", "ML-01a", "ML-01b"} <= passed
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)
d = Baselines("tea").deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 1 + 0.02 * 26, 26.0)
assert d is not None and d.outside == 0
def _rewritten(data: bytes, change) -> bytes:
"""The bundle with `change(files)` applied to its files (name -> bytes), the manifest kept as it was."""
with zipfile.ZipFile(io.BytesIO(data)) as z:
files = {n: z.read(n) for n in z.namelist()}
change(files)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as z:
for name, content in files.items():
z.writestr(name, content)
return buffer.getvalue()
def test_an_altered_bundle_is_refused(trained, two_stores, tmp_path):
"""Pins down: the import refuses a bundle whose file changed after it was written, one with a path outside
itself, and one whose module class, even with its manifest rewritten to match, isn't the one this platform runs
for that scenario.
Fails if the import stops checking the manifest, unpacks outside its folder, or loads a class a bundle names.
"""
out = tmp_path / "baselines.zip"
bundle.export(settings(), out, environment="PROD")
data = out.read_bytes()
two_stores("plataforma")
def bump(files):
files["eeg-gradient/module/baseline.json"] += b" "
def escape(files):
files["../fuera.json"] = b"{}"
def other_class(files):
path = "eeg-gradient/module/module.json"
files[path] = json.dumps({"class": "os:system"}).encode()
manifest = json.loads(files[bundle.MANIFEST])
manifest["escenarios"]["eeg-gradient"]["archivos"][path] = bundle._sha(files[path])
files[bundle.MANIFEST] = json.dumps(manifest).encode()
for change, reason in ((bump, "changed after"), (escape, "outside itself"), (other_class, "module class")):
target = tmp_path / f"{change.__name__}.zip"
target.write_bytes(_rewritten(data, change))
with pytest.raises(bundle.BundleError, match=reason):
bundle.import_(settings(), target)
def test_an_incomplete_export_is_refused(two_stores, tmp_path):
"""Pins down: nothing is written while a scenario has no version to export.
Fails if a partial bundle leaves the site (the platform would score some metrics and not others).
"""
with pytest.raises(bundle.BundleError, match="no PROD version"):
bundle.export(settings(), tmp_path / "baselines.zip", environment="PROD")
assert not (tmp_path / "baselines.zip").exists()
def test_run_takes_local_reference_flags_only_with_a_folder(two_stores):
"""Pins down: the local cohort's ages and mains frequency go with its folder.
Fails if `--line-hz` alone is silently ignored and HK1K's 50 Hz is used for a cohort recorded at 60 Hz.
"""
from models.__main__ import main
assert main(["run", "tea", "eeg", "--train", "--line-hz", "60"]) == 2