237 lines
11 KiB
Python
237 lines
11 KiB
Python
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
|
||
(models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the
|
||
children whose diagnosis ruled TEA out, persistance.eeg.ruled_out) and scoring every
|
||
analysed EEG against the child's age. The math is the old platform's, proved on its HK1K
|
||
cohort by models/tests/test_eeg.py."""
|
||
|
||
import hashlib
|
||
from dataclasses import dataclass
|
||
from datetime import date
|
||
|
||
import mlflow.pyfunc
|
||
import pandas as pd
|
||
|
||
from core.tea import ados2
|
||
from core.tea import association as relation
|
||
from models import cluster
|
||
from models.jobs import EmptyCohort
|
||
from models.tea import association
|
||
from models.tea.eeg import analysis, curves, reference
|
||
from persistance import eeg, registry, silver
|
||
|
||
CURVES = curves.SCENARIOS
|
||
ASSOCIATION = "eeg-ados2" # trained on the champion curves' z: after they are promoted
|
||
MODELS = [*CURVES, ASSOCIATION]
|
||
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
|
||
|
||
|
||
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() -> int:
|
||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
||
pending = eeg.pending()
|
||
done = cluster.run(
|
||
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
|
||
) # one task per EEG
|
||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||
eeg.save_analyses(found)
|
||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||
return len(found)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Jobs:
|
||
"""The domain's model jobs (models.definitions): every curve is routine."""
|
||
|
||
def routine(self) -> list[str]:
|
||
return list(MODELS)
|
||
|
||
def scored(self) -> list[str]:
|
||
return list(MODELS) # the curves, then the association on their scores
|
||
|
||
|
||
JOBS = Jobs()
|
||
|
||
|
||
def registered(name: str) -> str:
|
||
return f"tea.{name}"
|
||
|
||
|
||
def train(name: str, as_of: date | None = None) -> int:
|
||
if name == ASSOCIATION:
|
||
return _train_association(as_of)
|
||
return _train_curve(name, as_of)
|
||
|
||
|
||
def _train_curve(name: str, as_of: date | None = None) -> int:
|
||
"""A new version of one age curve, trained on the site's reference group as known on
|
||
`as_of` (today by default), with its two reports: the group it learned from, and its
|
||
centile curves."""
|
||
day = as_of or date.today()
|
||
measured = eeg.ruled_out(day)
|
||
if not measured:
|
||
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
|
||
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
|
||
table = reference.tables(measured)[name]
|
||
baseline = curves.train(table, name)
|
||
ages = [m["age_months"] for m in measured]
|
||
technical = {
|
||
"model": name, "method": "age curves (weighted centiles on log age)",
|
||
"cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day),
|
||
"studies": len(measured), "valid_studies": len(measured),
|
||
"ages_months": [min(ages), max(ages)], "features": sorted(baseline),
|
||
} # fmt: skip
|
||
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
||
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
|
||
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
|
||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
|
||
|
||
|
||
def score(name: str) -> int | None:
|
||
if name == ASSOCIATION:
|
||
return _score_association()
|
||
return _score_curve(name)
|
||
|
||
|
||
def _score_curve(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 = CURVES[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
|
||
|
||
|
||
class Association(mlflow.pyfunc.PythonModel):
|
||
"""The fitted association as MLflow serves it: a cohort in, each child's probabilities."""
|
||
|
||
def __init__(self, fitted: dict):
|
||
self.fitted = fitted
|
||
|
||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||
return pd.DataFrame(association.score(self.fitted, model_input))
|
||
|
||
|
||
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||
"""(fit, scored): every valid EEG of a child with an ADOS-2 (known by `as_of`), her age,
|
||
module, items, CSS and the z of each biomarker; fitted on each child's first EEG with
|
||
any z, every EEG scored."""
|
||
day = str(as_of) if as_of else None
|
||
rows = []
|
||
for r in eeg.association_inputs(relation.BIOMARKERS):
|
||
a = r["ados2"]
|
||
evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None
|
||
if day and (r["study_date"] > day or (evaluated and evaluated > day)):
|
||
continue
|
||
css = None
|
||
if evaluated and r["birth_date"]:
|
||
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
|
||
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
|
||
rows.append({"key": r["edf"], "person": r["person_id"], "age_months": r["age_months"],
|
||
"module": a.get("module"), "css": css,
|
||
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
|
||
**{k: v for k, v in r.items() if k.startswith("z_")}}) # fmt: skip
|
||
scored = pd.DataFrame(rows)
|
||
if scored.empty:
|
||
return scored, scored
|
||
predictors = [c for c in scored.columns if c.startswith("z_")]
|
||
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
|
||
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
|
||
return fit.drop(columns=["person"]), scored.drop(columns=["person"])
|
||
|
||
|
||
def _train_association(as_of: date | None = None) -> int:
|
||
"""A new version of the association, fitted on the site's children, with its reports:
|
||
the cohort and pairs it estimated, and the pairs themselves."""
|
||
fit, _ = association_cohort(as_of)
|
||
if fit.empty:
|
||
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
|
||
fitted = association.fit(fit)
|
||
pairs = association.associations(fitted)
|
||
estimated = [p for p in pairs if p["odds_ratio"] is not None]
|
||
technical = {
|
||
"model": ASSOCIATION, "method": "Firth logistic (items) / cumulative logit (CSS), "
|
||
"adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
|
||
"cohort": "site: children with an ADOS-2 and a valid EEG",
|
||
"as_of": str(as_of or date.today()),
|
||
"children": int(fitted["n"]), "level": fitted["level"], "pairs": len(pairs),
|
||
"estimated": len(estimated), "clear": sum(1 for p in estimated if (p["q"] or 1) < 0.05),
|
||
} # fmt: skip
|
||
interpretability = {"model": ASSOCIATION, "kind": "associations", "level": fitted["level"],
|
||
"children": int(fitted["n"]), "rows": pairs} # fmt: skip
|
||
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
|
||
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
|
||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||
return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports)
|
||
|
||
|
||
def _score_association() -> int | None:
|
||
"""The champion association's probabilities for every scored EEG; None without one."""
|
||
found = registry.champion(registered(ASSOCIATION))
|
||
if found is None:
|
||
return None
|
||
version, model = found
|
||
fitted = model.unwrap_python_model().fitted
|
||
label = f"{registered(ASSOCIATION)}/{version}"
|
||
_, scored = association_cohort()
|
||
kept = ("biomarker", "zone", "kind", "outcome_code", "event", "n", "odds_ratio", "ci_low",
|
||
"ci_high", "p", "q", "sens_odds_ratio", "same_direction", "reason") # fmt: skip
|
||
pairs = [{**{k: p[k] for k in kept}, "model": label,
|
||
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
|
||
"metric": relation.BIOMARKERS[p["biomarker"]], "principal": p["model"],
|
||
"sensitivity": p["sens_model"]}
|
||
for p in association.associations(fitted) if p["odds_ratio"] is not None] # fmt: skip
|
||
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, or the CSS
|
||
if not scored.empty:
|
||
keys = scored["key"].tolist()
|
||
for n in relation.ITEMS:
|
||
items = association.item_scores(scored, n).tolist()
|
||
observed[relation.item_code(n)] = dict(zip(keys, items, strict=True))
|
||
observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), strict=True))
|
||
scores = []
|
||
for one in association.score(fitted, scored) if not scored.empty else []:
|
||
seen = observed.get(one["outcome_code"], {}).get(one["key"])
|
||
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
|
||
shown = None if seen is None or seen != seen else float(seen)
|
||
scores.append({**one, "edf": one["key"], "model": label, "key": f"{one['key']}|{pair}",
|
||
"observed": shown}) # fmt: skip
|
||
eeg.save_association(label, pairs, scores)
|
||
return version
|