Files
models/models/tea/jobs.py
T

138 lines
5.8 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 reference cohort of TEA_REFERENCE_DIR (its EDFs and
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
or ages table that changes is measured 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 cluster
from models.tea.eeg import analysis, curves, reference
from persistance import eeg, registry, silver
MODELS = curves.SCENARIOS
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)
def _reference() -> tuple[str, list[dict]]:
"""The reference cohort's hash and each study's verdict and features, cached."""
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
studies = reference.listing(folder, ages)
digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text())
measured = reference.measure(studies)
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
@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) -> 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 = _reference()
table = 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": reference.NAME, "cohort_sha256": digest, "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": reference.NAME, "cohort_sha256": digest}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
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