Files
models/models/tea/jobs.py
T
alberto a818847b99 Expose TEA baseline centiles by age
Share log-age interpolation with scoring and preserve nulls outside coverage. Use a synthetic geometric midpoint and values on both sides of the median to check numeric parity.
2026-11-29 19:45:50 -06:00

350 lines
15 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 sqlalchemy import bindparam, inspect, text
from core.tea import ADOS2_ITEMS, ados2
from models import execution
from models.jobs import EmptyCohort
from models.tea import association
from models.tea.eeg import analysis, curves
from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
from persistance.destination import engine
ASSOCIATION = "ados2_association"
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+",
"tea_associations",
"tea_association_scores",
]
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 curve(self, feature: str, ages) -> list[dict]:
"""Centiles by age for a feature, using the same interpolation as scoring."""
baseline = self.baseline[feature]
if baseline["kind"] == "count_rate":
raise LookupError("no centiles by age for a count-rate feature")
return [{"age_months": age, **curves.centiles(baseline, age)} for age in ages]
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 | None:
"""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."""
if name == ASSOCIATION:
return train_association(as_of)
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 cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
"""The first EEG with a predictor per child for fitting, and all eligible EEGs for scoring."""
columns = [
"key",
"person_id",
"study_date",
"edf",
"age_months",
"ados_module",
"css",
*ADOS2_ITEMS,
]
records, values = [], {}
with engine().connect() as con:
tables = inspect(con)
if tables.has_table("eeg_analysis", schema="bronze"):
items = ", ".join(ADOS2_ITEMS)
selected_items = ", ".join(f"t.{i}" for i in ADOS2_ITEMS)
query = text(f"""
with first_ados as (
select person_id, module, evaluation_date, {items},
row_number() over (
partition by person_id order by evaluation_date nulls last, known_at
) as rn
from silver.ados2
)
select e.person_id, e.study_date, e.edf, a.age_months,
t.module, t.evaluation_date, p.birth_date, {selected_items}
from silver.eeg as e
join bronze.eeg_analysis as a on a.edf = e.edf
join first_ados as t on t.person_id = e.person_id and t.rn = 1
left join silver.person as p on p.person_id = e.person_id
where a.valid and a.age_months is not null
""")
for raw in con.execute(query).mappings():
row = dict(raw)
for field in ("birth_date", "evaluation_date"):
row[field] = date.fromisoformat(str(row[field])[:10]) if row[field] else None
records.append(
{
**row,
"key": f"{row['person_id']}|{str(row['study_date'])[:10]}",
"ados_module": row["module"],
"css": ados2.score(
row, row["birth_date"] if row["evaluation_date"] else None
)[0],
}
)
if records and tables.has_table("eeg_scores", schema="bronze"):
biomarker = {metric: name for name, metric in association.BIOMARKERS.items()}
query = text("""
select edf, metric, part, site, z from bronze.eeg_scores
where metric in :metrics and z is not null
""").bindparams(bindparam("metrics", expanding=True))
edfs = {row["edf"] for row in records}
for edf, metric, part, site, z in con.execute(query, {"metrics": list(biomarker)}):
if edf not in edfs:
continue
name = biomarker[metric]
if name in ("spikes", "spindles"):
if part != "zones":
continue
predictor = f"z_{name}_{site}"
else:
if part != "value":
continue
predictor = f"z_{name}"
values.setdefault(edf, {})[predictor] = z
scored = pd.DataFrame(records, columns=columns)
if values:
scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="edf")
scored = scored.sort_values(["person_id", "study_date", "key"], na_position="last").reset_index(
drop=True
)
predictors = [c for c in scored.columns if c.startswith("z_")]
fit = (
scored[scored[predictors].notna().any(axis=1)]
.drop_duplicates("person_id")
.reset_index(drop=True)
)
drop = ["person_id", "study_date", "edf"]
return fit.drop(columns=drop), scored.drop(columns=drop)
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
"""Hash the scored EEGs, fit membership, and module identifier in canonical order."""
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
return hashlib.sha256(text.encode()).hexdigest()[:8]
def _records(frame: pd.DataFrame) -> list[dict]:
"""Coerce missing estimates and open interval limits to JSON/SQL nulls."""
clean = frame.replace([float("inf"), -float("inf")], None).astype(object)
return clean.where(clean.notna(), None).to_dict("records")
def train_association(as_of: date | None = None) -> int | None:
fit, scored = cohort()
if fit.empty:
raise EmptyCohort(ASSOCIATION)
estimator = association.Ados2Association(level="auto")
mark = fingerprint(
fit, scored, f"{estimator.name}/{estimator.version}/{estimator.impl}/{estimator.level}"
)
name = registered(ASSOCIATION)
versions = registry.versions(name)
if versions and versions[-1]["params"].get("fingerprint") == mark:
return versions[-1]["version"]
estimator.fit(fit)
pairs = estimator.associations()
level = estimator.fitted["level"]
forest = ["biomarker", "zone", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"]
reports = {
"technical_validation": {
"model": ASSOCIATION,
"method": "Firth / ordinal logistic, profile CI, BH within biomarker",
"level": level,
"cohort": len(fit),
"scored": len(scored),
"fingerprint": mark,
"pairs": _records(pairs),
},
"interpretability": {"kind": "forest", "rows": _records(pairs[forest])},
}
params = {"fingerprint": mark, "level": level}
metrics = {"n_reference": len(fit), "pairs": int(pairs["odds_ratio"].notna().sum())}
return registry.register(name, association.Model(estimator.fitted), params, metrics, reports)
def relate() -> int | None:
found = registry.champion(registered(ASSOCIATION))
if found is None:
return None
version, model = found
estimator = association.Ados2Association(fitted=model.unwrap_python_model().fitted)
_, scored = cohort()
rows = []
for row in _records(estimator.associations()):
if row["odds_ratio"] is None or row["odds_ratio"] <= 0:
continue
row["key"] = f"{row['biomarker']}|{row['zone']}|{row['outcome_code']}"
row["method"] = row.pop("model")
row.pop("outcome")
row["level"] = estimator.fitted["level"]
row["n_cohort"] = estimator.fitted["n"]
row["reason"] = row["reason"] or None
rows.append(row)
keys = {row["key"] for row in rows}
scores = []
for row in model.predict(scored).to_dict("records"):
pair = "|".join(row.pop(field) for field in ("biomarker", "zone", "outcome_code"))
if pair in keys:
eeg_id = row["key"]
scores.append({**row, "eeg_id": eeg_id, "pair": pair, "key": f"{eeg_id}|{pair}"})
eeg.save_associations(version, rows)
eeg.save_association_scores(version, scores)
return version
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