Files
models/models/tea/association.py
T

596 lines
20 KiB
Python

from __future__ import annotations
import json
import warnings
from dataclasses import dataclass, field
from pathlib import Path
import mlflow.pyfunc
import numpy as np
import pandas as pd
from scipy import optimize, stats
from scipy.special import expit
from core.tea import ADOS2_ITEMS
from models.tea.eeg.spindles import ZONES
ASSOCIATION_COLUMNS = (
"biomarker",
"zone",
"kind",
"outcome",
"outcome_code",
"event",
"model",
"n",
"odds_ratio",
"ci_low",
"ci_high",
"p",
"q",
"sens_model",
"sens_odds_ratio",
"same_direction",
"reason",
)
SCORE_COLUMNS = (
"key",
"biomarker",
"zone",
"outcome_code",
"z",
"probability",
"reference_probability",
)
ADJUST = ("age_months", "ados_module")
ITEMS = {
1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}),
2: ("Señalar", "SA", {"toddler", "module_1", "module_2"}),
3: ("Gestos", "SA", {"toddler", "module_1", "module_2"}),
4: ("Contacto visual inusual", "SA", {"toddler", "module_1", "module_2"}),
5: ("Expresiones faciales dirigidas a otros", "SA", {"toddler", "module_1", "module_2"}),
6: ("Integración de la mirada con otras conductas", "SA", {"toddler", "module_1"}),
7: ("Disfrute compartido en la interacción", "SA", {"toddler", "module_1", "module_2"}),
8: ("Respuesta al nombre", "SA", {"toddler"}),
9: ("Búsqueda de atención cuando se le ignora", "SA", {"toddler"}),
10: ("Pedir", "SA", {"toddler"}),
11: ("Mostrar", "SA", {"toddler", "module_1", "module_2"}),
12: (
"Iniciación espontánea de la atención conjunta",
"SA",
{"toddler", "module_1", "module_2"},
),
13: ("Respuesta a la atención conjunta", "SA", {"toddler", "module_1"}),
14: ("Calidad de los acercamientos sociales", "SA", {"toddler", "module_1", "module_2"}),
15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"toddler"}),
16: ("Cantidad de comunicación social recíproca", "SA", {"module_2"}),
17: ("Calidad general de la relación", "SA", {"toddler", "module_2"}),
18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"toddler", "module_1"}),
19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"module_1", "module_2"}),
20: ("Interés sensorial inusual", "RRB", {"toddler", "module_1", "module_2"}),
21: ("Manierismos de manos y dedos", "RRB", {"toddler", "module_1", "module_2"}),
22: (
"Intereses repetitivos o conductas estereotipadas",
"RRB",
{"toddler", "module_1", "module_2"},
),
}
ZONE_ITEMS = {
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
"frontal_right": (4, 5, 7, 14, 22),
"frontal_midline": (6, 11, 12, 13, 14),
"central": (21,),
"parietal": (6, 13, 20),
"temporal_left": (1, 16, 18, 19),
"temporal_right": (4, 5, 8),
"occipital": (4, 20),
}
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
RHYTHM_ITEMS = (20, 22)
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1
def item_code(n: int) -> str:
return f"ados2_item_{n:02d}"
def pairs(level: str) -> list[dict]:
out = []
for zone in ZONES:
outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)]
out += [
{
"biomarker": "spikes",
"zone": zone,
"predictor": f"z_spikes_{zone}",
"kind": k,
"outcome": o,
}
for k, o in outcomes
]
out += [
{
"biomarker": "spindles",
"zone": zone,
"predictor": f"z_spindles_{zone}",
"kind": "domain",
"outcome": CSS,
}
for zone in SPINDLE_ZONES
]
rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)]
out += [
{
"biomarker": "posterior_rhythm",
"zone": "posterior",
"predictor": "z_posterior_rhythm",
"kind": k,
"outcome": o,
}
for k, o in rhythm
]
out.append(
{
"biomarker": "gradient",
"zone": "global",
"predictor": "z_gradient",
"kind": "domain",
"outcome": CSS,
}
)
return out
def algorithm_score(v) -> pd.Series:
v = pd.to_numeric(pd.Series(v), errors="coerce")
return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2)
def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
column = ADOS2_ITEMS[n - 1]
if "ados_module" not in cohort or column not in cohort:
return pd.Series(np.nan, index=cohort.index)
return algorithm_score(cohort[column]).where(cohort["ados_module"].isin(ITEMS[n][2]))
def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool:
scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1)
return int(scores.notna().any(axis=1).sum()) >= minimum
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8
@dataclass
class Design:
predictor: str
numeric: dict[str, float] = field(default_factory=dict)
categorical: dict[str, list[str]] = field(default_factory=dict)
reference: dict[str, str] = field(default_factory=dict)
@classmethod
def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design:
d = cls(predictor)
for a in adjust:
if a not in t:
continue
v = t[a]
if pd.api.types.is_numeric_dtype(v):
v = v.astype(float)
if v.std() > 0:
d.numeric[a] = float(v.mean())
else:
ref = v.value_counts().index[0]
levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)]
if levels:
d.categorical[a] = [str(lv) for lv in levels]
d.reference[a] = str(ref)
return d
@property
def names(self) -> list[str]:
return ["intercept", self.predictor, *self.numeric] + [
f"{a}={lv}" for a, levels in self.categorical.items() for lv in levels
]
def matrix(self, t: pd.DataFrame) -> np.ndarray:
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
for a, mean in self.numeric.items():
cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan))
for a, levels in self.categorical.items():
v = t[a].astype(str) if a in t else pd.Series([None] * len(t))
for lv in levels:
cols.append((v == lv).to_numpy(float))
X = np.column_stack(cols)
known = np.ones(len(t), bool)
for a, levels in self.categorical.items():
seen = {self.reference[a], *levels}
known &= (
t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy()
if a in t
else False
)
X[~known] = np.nan
return X
def to_dict(self) -> dict:
return {
"predictor": self.predictor,
"numeric": self.numeric,
"categorical": self.categorical,
"reference": self.reference,
}
@classmethod
def from_dict(cls, d: dict) -> Design:
return cls(
d["predictor"],
dict(d["numeric"]),
{k: list(v) for k, v in d["categorical"].items()},
dict(d["reference"]),
)
def _pl(b, X, y):
eta = X @ b
p = expit(eta)
w = p * (1 - p)
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
if sign <= 0:
return -np.inf
return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet)
def _score(b, X, y):
p = expit(X @ b)
w = p * (1 - p)
info = X.T @ (X * w[:, None])
h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
return X.T @ (y - p + h * (0.5 - p)), info
def _fit_firth(X, y, max_iter=200, tol=1e-10):
b = np.zeros(X.shape[1])
pl = _pl(b, X, y)
for _ in range(max_iter):
U, info = _score(b, X, y)
step = np.linalg.solve(info, U)
t = 1.0
while t > 1e-8:
nb = b + t * step
npl = _pl(nb, X, y)
if npl >= pl - 1e-12:
break
t /= 2
b, pl = nb, npl
if np.max(np.abs(t * step)) < tol:
break
return b, pl
def _profile_firth(value, j, X, y, b0):
free = [k for k in range(X.shape[1]) if k != j]
def f(bf):
b = np.empty(X.shape[1])
b[free], b[j] = bf, value
v = _pl(b, X, y)
if not np.isfinite(v):
return 1e10, np.zeros(len(free))
U, _ = _score(b, X, y)
return -v, -U[free]
return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun)
def _interval(profile, centre, maximum, scale):
g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
limits = []
for sign in (-1, 1):
previous, limit = centre, sign * np.inf
for k in range(1, 80):
v = centre + sign * scale * k
if g(v) > 0:
limit = optimize.brentq(g, min(previous, v), max(previous, v))
break
previous = v
limits.append(limit)
return limits[0], limits[1]
def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict:
return {
"model": model,
"n": n,
"coef": round(float(coef), 4),
"odds_ratio": round(float(np.exp(coef)), 4),
"ci_low": round(float(np.exp(lo)), 4),
"ci_high": round(float(np.exp(hi)), 4),
"p": round(p, 5),
"adjusted_for": ", ".join(design.names[2:]),
"reason": "",
**extra,
"state": {"design": design.to_dict(), **state},
}
def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor, adjust)
X = design.matrix(d)
b, pl = _fit_firth(X, y)
_, info = _score(b, X, y)
se = float(np.sqrt(np.linalg.inv(info)[1, 1]))
profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731
lo, hi = _interval(profile, b[1], pl, max(se, 0.05))
p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1))
eta = X[:, 1:] @ b[1:]
flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
return _summary(
"firth",
len(d),
b[1],
lo,
hi,
p,
design,
{"beta": [float(v) for v in b[1:]], "intercept": float(flic)},
events=int(y.sum()),
)
def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
X = Design.from_dict(state["design"]).matrix(t)
return expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"]))
def firth_reference(state: dict) -> float:
return float(expit(state["intercept"]))
def _nll_ordinal(par, X, yk, K):
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
eta = X @ par[K - 1 :]
n = len(yk)
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk]
return -float(np.sum(np.log(np.clip(pr, 1e-300, None))))
def _fit_ordinal(X, yk, K, fixed=None):
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
if fixed is None:
r = optimize.minimize(lambda q: _nll_ordinal(q, X, yk, K), start, method="BFGS")
return r.x, float(r.fun)
j, value = fixed
idx = [k for k in range(len(start)) if k != K - 1 + j]
def f(q):
par = np.empty(len(start))
par[idx], par[K - 1 + j] = q, value
return _nll_ordinal(par, X, yk, K)
return None, float(optimize.minimize(f, start[idx], method="BFGS").fun)
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor, adjust)
X = design.matrix(d)[:, 1:]
K = len(levels)
yk = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _fit_ordinal(X, yk, K)
beta = par[K - 1 :]
if abs(beta[0]) > 20:
return {**out, "reason": "does not converge (separation)"}
profile = lambda v: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731
lo, hi = _interval(profile, beta[0], -nll, 0.1)
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
return _summary(
"ordinal",
len(d),
beta[0],
lo,
hi,
p,
design,
{
"beta": [float(v) for v in beta],
"threshold": float(theta[k - 1]) if 0 < k < K else None,
"always": None if 0 < k < K else float(k == 0),
},
levels=K,
)
def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
X = Design.from_dict(state["design"]).matrix(t)[:, 1:]
if state["threshold"] is None:
return np.where(np.isnan(X).any(axis=1), np.nan, state["always"])
return 1 - expit(state["threshold"] - X @ np.asarray(state["beta"]))
def ordinal_reference(state: dict) -> float:
return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"]))
def bh(p) -> np.ndarray:
p = np.asarray(p, dtype=float)
q = np.full(len(p), np.nan)
ok = np.isfinite(p)
if ok.any():
v = p[ok]
o = np.argsort(v)
r = v[o] * len(v) / np.arange(1, len(v) + 1)
r = np.minimum.accumulate(r[::-1])[::-1]
q[np.flatnonzero(ok)[o]] = np.minimum(r, 1)
return q
def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
if pair["kind"] == "item":
score = item_scores(cohort, pair["outcome"])
return (score >= ALTERED).astype(float).where(score.notna()), score
css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
return (css >= CSS_HIGH).astype(float).where(css.notna()), css
def _guarded(fit, model: str, *args, **kwargs) -> dict:
try:
return fit(*args, **kwargs)
except (np.linalg.LinAlgError, ValueError) as error:
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
p = pair["predictor"]
fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731
if pair["kind"] == "item":
return fit_firth(), _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=ALTERED)
return _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=CSS_HIGH), fit_firth()
def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
if fit["model"] == "firth":
return firth_probability(fit["state"], t), firth_reference(fit["state"])
return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"])
class Ados2Association:
name = "ados2_association"
version = "0.1.0"
impl = "modern"
def __init__(self, level: str = "auto", fitted: dict | None = None):
if level not in ("auto", "item", "domain"):
raise ValueError(f"level must be auto, item or domain, not {level!r}")
self.level = level
self.fitted = fitted
def fit(self, cohort: pd.DataFrame) -> Ados2Association:
level = self.level if self.level != "auto" else ("item" if has_items(cohort) else "domain")
rows = []
for pair in pairs(level):
if pair["predictor"] not in cohort:
continue
d = cohort.copy()
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
d["_yes"], d["_level"] = _outcome(cohort, pair)
principal, sensitivity = _models(d, pair)
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
q = np.full(len(rows), np.nan)
biomarkers = np.array([r["biomarker"] for r in rows])
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
for b in dict.fromkeys(biomarkers):
q[biomarkers == b] = bh(p[biomarkers == b]).round(5)
for r, v in zip(rows, q, strict=True):
r["q"] = None if np.isnan(v) else float(v)
self.fitted = {"level": level, "n": len(cohort), "rows": rows}
return self
def _rows(self) -> list[dict]:
if self.fitted is None:
raise ValueError(f"{self.name}: fit() before associations() or score()")
return self.fitted["rows"]
def associations(self) -> pd.DataFrame:
out = []
for r in self._rows():
f, s = r["principal"], r["sensitivity"]
kind = r["kind"]
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
out.append(
{
"biomarker": r["biomarker"],
"zone": r["zone"],
"kind": kind,
"outcome": r["outcome"],
"outcome_code": item_code(r["outcome"]) if kind == "item" else CSS,
"event": f">={ALTERED if kind == 'item' else CSS_HIGH}",
"model": f["model"],
"n": f["n"],
"odds_ratio": ors,
"ci_low": f.get("ci_low"),
"ci_high": f.get("ci_high"),
"p": f.get("p"),
"q": r["q"],
"sens_model": s["model"],
"sens_odds_ratio": sens,
"same_direction": (
None
if ors is None or sens is None
else bool(np.sign(ors - 1) == np.sign(sens - 1))
),
"reason": f.get("reason", ""),
}
)
return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS))
def score(self, cohort: pd.DataFrame) -> pd.DataFrame:
parts = []
for r in self._rows():
f = r["principal"]
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
continue
t = cohort
if r["kind"] == "item":
modules = set(ITEMS[r["outcome"]][2])
t = cohort[cohort["ados_module"].isin(modules)]
t = t[t[r["predictor"]].notna()]
if not len(t):
continue
prob, ref = _probability(f, t)
kept = np.isfinite(prob)
parts.append(
pd.DataFrame(
{
"key": t["key"].to_numpy()[kept],
"biomarker": r["biomarker"],
"zone": r["zone"],
"outcome_code": item_code(r["outcome"]) if r["kind"] == "item" else CSS,
"z": t[r["predictor"]].to_numpy(float)[kept],
"probability": prob[kept].round(4),
"reference_probability": round(ref, 4),
}
)
)
if not parts:
return pd.DataFrame(columns=list(SCORE_COLUMNS))
return pd.concat(parts, ignore_index=True)[list(SCORE_COLUMNS)]
def save(self, path) -> None:
Path(path, "association.json").write_text(
json.dumps({"level": self.level, "fitted": self.fitted}, default=float)
)
@classmethod
def load(cls, path) -> Ados2Association:
d = json.loads(Path(path, "association.json").read_text())
return cls(d["level"], d["fitted"])
class Model(mlflow.pyfunc.PythonModel):
def __init__(self, fitted: dict):
self.fitted = json.loads(json.dumps(fitted, default=float))
def predict(self, context, cohort_df):
return Ados2Association(fitted=self.fitted).score(cohort_df)