Files
models/models/tea/jobs.py
T

174 lines
7.7 KiB
Python

"""TEA jobs analyse the hospital's EEGs and score them against seven age curves
(models.tea.eeg.curves). Training uses a named reference cohort or the legacy
TEA_REFERENCE_DIR and TEA_REFERENCE_AGES settings.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
features are kept in TEA_REFERENCE_CACHE in a JSON file named by the cohort and its hash.
Changes to the study list, ages or mains frequency require measuring the cohort again."""
import hashlib
import json
import os
from dataclasses import dataclass
from datetime import date
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from models import execution
from models.tea.eeg import analysis, curves
from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
MODELS = curves.SCENARIOS
CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
GOLD_SELECT = ["tea_eeg_analyses+", "tea_eeg_metrics+"] # what a rebuild of TEA's gold selects
class Baseline(mlflow.pyfunc.PythonModel):
"""An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z,
outside, p5, median and p95 out, for one of its features."""
def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = scenario, baseline
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
feature = (params or {}).get("feature", "value")
rows = model_input.to_dict("records")
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
r.get("age_months"), r.get("exposure"))
for r in rows]) # fmt: skip
def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
edf, birth, signal = item
return edf, analysis.analyze(signal, birth)
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
"""The EEGs in scope (default: those not analysed yet), analysed in the ambient
execution; then, unless told not to, gold's TEA tables are rebuilt. Bronze is written
once, after the last study, so a cancelled run leaves it as it was."""
rows = eeg.select(scope or eeg.Scope())
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows) # lazy: bytes travel
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
eeg.save_analyses(found)
if rebuild_gold:
silver.build(GOLD_SELECT)
return len(found)
def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
"""The reference cohort's hash, cached measurements, name and mains frequency."""
if reference is None:
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
name, line_hz = cohort_reference.NAME, 50
else:
folder = cluster.reference_dir(reference.name)
ages = folder / "edades.csv"
if not ages.is_file():
raise ValueError(f"reference cohort {reference.name!r} has no edades.csv")
name, line_hz = reference.name, reference.line_hz
studies = cohort_reference.listing(folder, ages)
if reference is not None and not studies:
raise ValueError(f"reference cohort {name!r} has no EDF with an age from 16 to 36 months")
content = "\n".join(f"{p.name}|{a}" for _, p, a in studies)
if line_hz != 50:
content += f"|line_hz={line_hz}"
digest = hashlib.sha256(content.encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{name}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text()), name, line_hz
measured = cohort_reference.measure(studies, mains_hz=float(line_hz))
measured = [{**m, "key": str(m["key"])} for m in measured]
if path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(measured))
return digest, measured, name, line_hz
@dataclass(frozen=True)
class Jobs:
"""The domain's model jobs (models.definitions): every curve is routine."""
def routine(self) -> list[str]:
return list(MODELS)
JOBS = Jobs()
def registered(name: str) -> str:
return f"tea.{name}"
def train(name: str, as_of: date | None = None, reference: cluster.Reference | None = None) -> int:
"""A new version of one age curve, trained on the reference cohort's valid studies,
with its two reports: the cohort it learned from, and its centile curves."""
digest, measured, cohort, hz = _reference(reference)
table = cohort_reference.tables(measured)[name]
baseline = curves.train(table, name)
valid = [m for m in measured if m["valid"] and m["error"] is None]
technical = {
"model": name, "method": "age curves (weighted centiles on log age)",
"cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured),
"valid_studies": len(valid),
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
"features": sorted(baseline),
} # fmt: skip
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
def score_curves() -> dict[str, int | None]:
"""The version of each age curve's champion that scored, None without a champion."""
return {name: score(name) for name in CURVES}
def relate() -> int | None:
"""The ADOS-2 association: scores every analysed EEG with the `ados2_association`
champion (Phase 2). Returns the version that scored, None when the model has no champion.
It writes bronze only (ASSOCIATION_SCORES); the gold rebuild is the job's last step, not
this one's. Until Phase 2 exists it does nothing."""
return None
def score(name: str) -> int | None:
"""The champion curve's scores of every analysed EEG: the metric's value, and each
electrode and zone it measures; None without a champion."""
found = registry.champion(registered(name))
if found is None:
return None
version, model = found
baseline = model.unwrap_python_model().baseline
scenario, label = MODELS[name], f"{registered(name)}/{version}"
rows = []
for one in eeg.analysed():
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
if metric is None:
continue
exposure = (
(one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None
)
for part in scenario.parts:
sites = {"": metric["value"]} if part == "value" else metric[part]
prefix = "" if part == "value" else curves.PREFIX[part]
for site, value in sites.items():
feature = "value" if part == "value" else prefix + site
if feature not in baseline:
continue
s = curves.score(baseline[feature], value, one["age_months"], exposure)
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
"scenario": name, "model": label, "metric": scenario.metric,
"part": part, "site": site or None, **s}) # fmt: skip
eeg.save_scores(name, rows)
return version