Files
models/models/tea/jobs.py
T
alberto aab20683aa F7b: ADOS-2 association as library 0.4.0 with the accepted spike tests
The 33 zone x item spike pairs could not be estimated with about 46
children. The four spike tests accepted before seeing the ADOS-2 replace
them: any zone with the total CSS (repetitive behaviours and social affect
are one pair until the hospital sends CSS by domain), left with items 1 and
18, right with items 4, 5 and 7, and central with item 21 as exploratory.
The predictor is any useful spike in NREM on the group's electrodes.

Item altered from 2, CSS high from 8, at least 5 children with and without
the event, q within each biomarker without the exploratory pair, one CSS
family adjusted by age and module, no z clipping. The settings are module
constants; each fit saves them with its pairs, and a model without them is
refused. score() leaves each fitted child out. Keys are stored hashed.
2026-12-03 22:27:11 -06:00

312 lines
12 KiB
Python

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 core.measures import as_day
from core.tea import ADOS2_ITEMS, ASSOCIATION_BIOMARKERS, ados2
from core.tea.fhir import eeg_study_id
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
ASSOCIATION = "ados2_association"
MODELS = curves.SCENARIOS
GOLD_SELECT = [
"tea_eeg_analyses+",
"tea_eeg_metrics+",
"tea_associations",
"tea_association_scores",
]
class Baseline(mlflow.pyfunc.PythonModel):
def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = scenario, baseline
def curve(self, feature: str, ages) -> list[dict]:
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"),
r.get("electrodes"))
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:
rows = eeg.select(scope or eeg.Scope())
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows)
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 _cohort(source: cluster.TrainingSource, as_of: date) -> tuple[str, list[dict], str, int | None]:
if source.kind == "site":
measured = eeg.without_diagnosis(as_of)
if not measured:
raise EmptyCohort(f"no valid EEG of a child without the diagnosis by {as_of}")
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
return digest, measured, "site", None
folder = cluster.reference_dir(source.folder)
ages = folder / "edades.csv"
if not ages.is_file():
raise ValueError(f"folder {source.folder!r} has no edades.csv")
studies = cohort_reference.listing(folder, ages)
if not studies:
raise ValueError(f"folder {source.folder!r} has no EDF with an age from 16 to 36 months")
content = "\n".join(f"{p.relative_to(folder).as_posix()}|{a}" for _, p, a in studies)
digest = hashlib.sha256(f"{content}|line_hz={source.line_hz}".encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{source.folder}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text()), source.folder, source.line_hz
measured = cohort_reference.measure(studies, mains_hz=float(source.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, source.folder, source.line_hz
@dataclass(frozen=True)
class Jobs:
def routine(self) -> list[str]:
return [*MODELS, ASSOCIATION]
JOBS = Jobs()
def registered(name: str) -> str:
return f"tea.{name}"
def train(
name: str, as_of: date | None = None, source: cluster.TrainingSource | None = None
) -> int | None:
if name == ASSOCIATION:
return train_association(as_of)
day = as_of or date.today()
digest, measured, cohort, hz = _cohort(source or cluster.SiteTrainingSource(kind="site"), day)
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]
found = {"cohort": cohort, "cohort_sha256": digest}
found |= {"as_of": day.isoformat()} if hz is None else {"line_hz": hz}
technical = {
"model": name, "method": "age curves (weighted centiles on log age)", **found,
"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 = {key: str(value) for key, value in found.items()}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
def score_curves() -> dict[str, int | None]:
return {name: score(name) for name in MODELS}
def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
columns = [
"key",
"child",
"person_id",
"study_date",
"edf",
"age_months",
"ados_module",
"css",
"language_level",
*ADOS2_ITEMS,
*(f"spikes_any_{group}" for group in association.SPIKE_GROUPS),
]
biomarker = {metric: name for name, metric in ASSOCIATION_BIOMARKERS.items()}
studies, scores = eeg.association_cohort_rows()
records = []
for row in studies:
row["evaluation_date"] = as_day(row["evaluation_date"]) if row["evaluation_date"] else None
birth = as_day(row["birth_date"]) if row["evaluation_date"] and row["birth_date"] else None
scored = ados2.score(row, birth)
features = json.loads(row["features"] or "{}")
records.append(
{
**row,
**association.spikes_any(features.get("eeg-spikes", {})),
"key": eeg_study_id(row["person_id"], row["study_date"]),
"child": row["person_id"],
"ados_module": row["module"],
"css": scored.css if scored else None,
}
)
values = {}
edfs = {row["edf"] for row in records}
for row in scores:
if row["edf"] not in edfs:
continue
name = biomarker[row["metric"]]
if name == "spikes":
continue
if name == "spindles":
if row["part"] != "zones":
continue
predictor = f"z_{name}_{row['site']}"
else:
if row["part"] != "value":
continue
predictor = f"z_{name}"
values.setdefault(row["edf"], {})[predictor] = row["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_", "spikes_any_"))]
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:
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]:
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", "kind", "outcome_code", "event", "n"]
forest += ["odds_ratio", "ci_low", "ci_high", "q", "reason"]
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:
if name == ASSOCIATION:
return relate()
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
electrodes = (
(one["features"].get(name) or {}).get(f"zone_electrodes_{site}")
if scenario.counts and part == "zones"
else None
)
s = curves.score(baseline[feature], value, one["age_months"], exposure, electrodes)
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