aab20683aa
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.
746 lines
26 KiB
Python
746 lines
26 KiB
Python
from __future__ import annotations
|
|
|
|
import hashlib
|
|
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 core.tea.ados2 import algorithm_score
|
|
from core.tea.reasons import INSUFFICIENT_DATA
|
|
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")
|
|
ITEM_ALTERED = 2
|
|
CSS_HIGH = 8
|
|
MIN_EVENTS = 5
|
|
Q_FAMILY = "biomarker"
|
|
CLIP_Z = 0
|
|
|
|
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"},
|
|
),
|
|
}
|
|
|
|
SPIKE_GROUPS = {
|
|
"any": tuple(ZONES),
|
|
"left": ("frontal_left", "temporal_left"),
|
|
"right": ("frontal_right", "temporal_right"),
|
|
"central": ("central",),
|
|
}
|
|
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
|
|
RHYTHM_ITEMS = (20, 22)
|
|
|
|
CSS = "CSS"
|
|
|
|
|
|
def item_code(n: int) -> str:
|
|
return f"ados2_item_{n:02d}"
|
|
|
|
|
|
def outcome_code(pair: dict) -> str:
|
|
if pair["kind"] == "domain":
|
|
return pair["outcome"]
|
|
if pair["kind"] == "composite":
|
|
return "ados2_items_" + "_".join(f"{n:02d}" for n in pair["outcome"])
|
|
return item_code(pair["outcome"])
|
|
|
|
|
|
def outcome_items(pair: dict) -> list[int]:
|
|
if pair["kind"] == "domain":
|
|
return []
|
|
return list(pair["outcome"]) if pair["kind"] == "composite" else [pair["outcome"]]
|
|
|
|
|
|
def _pair(biomarker: str, zone: str, predictor: str, kind: str, outcome) -> dict:
|
|
return {
|
|
"biomarker": biomarker,
|
|
"zone": zone,
|
|
"predictor": predictor,
|
|
"kind": kind,
|
|
"outcome": outcome,
|
|
}
|
|
|
|
|
|
def pairs(level: str) -> list[dict]:
|
|
def spikes(zone, kind, outcome):
|
|
return _pair("spikes", zone, f"spikes_any_{zone}", kind, outcome)
|
|
|
|
out = [spikes("any", "domain", CSS)]
|
|
if level == "item":
|
|
out += [
|
|
spikes("left", "composite", [1, 18]),
|
|
spikes("right", "composite", [4, 5, 7]),
|
|
spikes("central", "exploratory", 21),
|
|
]
|
|
out += [_pair("spindles", z, f"z_spindles_{z}", "domain", CSS) for z in SPINDLE_ZONES]
|
|
rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)]
|
|
out += [
|
|
_pair("posterior_rhythm", "posterior", "z_posterior_rhythm", kind, outcome)
|
|
for kind, outcome in rhythm
|
|
]
|
|
out.append(_pair("gradient", "global", "z_gradient", "domain", CSS))
|
|
return out
|
|
|
|
|
|
def spikes_any(features: dict) -> dict[str, float]:
|
|
minutes = features.get("minutes") or 0
|
|
out = {}
|
|
for group, zones in SPIKE_GROUPS.items():
|
|
rates = [features.get(f"electrode_{e}") for zone in zones for e in ZONES[zone]]
|
|
counts = [rate * minutes for rate in rates if rate is not None]
|
|
known = minutes > 0 and bool(counts)
|
|
out[f"spikes_any_{group}"] = float(any(n > 0 for n in counts)) if known else np.nan
|
|
return out
|
|
|
|
|
|
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)
|
|
scores = [
|
|
algorithm_score(value, module, column) if module in ITEMS[n][2] else np.nan
|
|
for value, module in zip(cohort[column], cohort["ados_module"], strict=True)
|
|
]
|
|
return pd.Series(scores, index=cohort.index, dtype=float)
|
|
|
|
|
|
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 _complete(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> pd.DataFrame:
|
|
return t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
|
|
|
|
|
|
def _firth_fits(d: pd.DataFrame, y: np.ndarray, predictor: str) -> bool:
|
|
return len(d) >= MIN_ROWS and 2 <= y.sum() <= len(y) - 2 and d[predictor].std() != 0
|
|
|
|
|
|
def _firth_scoring(X, y, b) -> dict:
|
|
eta = X[:, 1:] @ b[1:]
|
|
flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
|
return {"beta": [float(v) for v in b[1:]], "intercept": float(flic)}
|
|
|
|
|
|
def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
|
|
d = _complete(t, outcome, predictor, adjust)
|
|
y = d[outcome].to_numpy(float)
|
|
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
|
|
if not _firth_fits(d, y, predictor):
|
|
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))
|
|
state = _firth_scoring(X, y, b)
|
|
return _summary("firth", len(d), b[1], lo, hi, p, design, state, events=int(y.sum()))
|
|
|
|
|
|
def firth_state(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict | None:
|
|
d = _complete(t, outcome, predictor, adjust)
|
|
y = d[outcome].to_numpy(float)
|
|
if not _firth_fits(d, y, predictor):
|
|
return None
|
|
design = Design.of(d, predictor, adjust)
|
|
X = design.matrix(d)
|
|
b, _ = _fit_firth(X, y)
|
|
return {"design": design.to_dict(), **_firth_scoring(X, y, b)}
|
|
|
|
|
|
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_fits(d: pd.DataFrame, levels: np.ndarray, predictor: str) -> bool:
|
|
return len(d) >= MIN_ROWS and len(levels) >= 2 and d[predictor].std() != 0
|
|
|
|
|
|
def _ordinal_data(d: pd.DataFrame, outcome: str, predictor: str, adjust, levels: np.ndarray):
|
|
design = Design.of(d, predictor, adjust)
|
|
return design, design.matrix(d)[:, 1:], np.searchsorted(levels, d[outcome].to_numpy())
|
|
|
|
|
|
def _separated(beta: np.ndarray) -> bool:
|
|
return abs(beta[0]) > 20
|
|
|
|
|
|
def _ordinal_scoring(par, levels: np.ndarray, high: float) -> dict:
|
|
K = len(levels)
|
|
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
|
k = int(np.searchsorted(levels, high))
|
|
return {
|
|
"beta": [float(v) for v in par[K - 1 :]],
|
|
"threshold": float(theta[k - 1]) if 0 < k < K else None,
|
|
"always": None if 0 < k < K else float(k == 0),
|
|
}
|
|
|
|
|
|
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
|
|
d = _complete(t, outcome, predictor, adjust)
|
|
levels = np.sort(d[outcome].unique())
|
|
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
|
|
if not _ordinal_fits(d, levels, predictor):
|
|
return {**out, "reason": "too few data or no variation"}
|
|
design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels)
|
|
K = len(levels)
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("ignore")
|
|
par, nll = _fit_ordinal(X, yk, K)
|
|
beta = par[K - 1 :]
|
|
if _separated(beta):
|
|
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))
|
|
state = _ordinal_scoring(par, levels, high)
|
|
return _summary("ordinal", len(d), beta[0], lo, hi, p, design, state, levels=K)
|
|
|
|
|
|
def ordinal_state(
|
|
t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float
|
|
) -> dict | None:
|
|
d = _complete(t, outcome, predictor, adjust)
|
|
levels = np.sort(d[outcome].unique())
|
|
if not _ordinal_fits(d, levels, predictor):
|
|
return None
|
|
design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels)
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("ignore")
|
|
par, _ = _fit_ordinal(X, yk, len(levels))
|
|
if _separated(par[len(levels) - 1 :]):
|
|
return None
|
|
return {"design": design.to_dict(), **_ordinal_scoring(par, levels, high)}
|
|
|
|
|
|
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 _digest(key) -> str:
|
|
return hashlib.sha256(str(key).encode()).hexdigest()[:16]
|
|
|
|
|
|
def _prepare(cohort: pd.DataFrame, settings: dict) -> pd.DataFrame:
|
|
d = cohort.copy()
|
|
clip = settings["clip_z"]
|
|
for column in d.columns:
|
|
if column.startswith(("z_", "spikes_any_")):
|
|
v = pd.to_numeric(d[column], errors="coerce").replace([np.inf, -np.inf], np.nan)
|
|
d[column] = v.clip(-clip, clip) if clip > 0 and column.startswith("z_") else v
|
|
return d
|
|
|
|
|
|
def _css(cohort: pd.DataFrame) -> pd.Series:
|
|
return pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
|
|
|
|
|
|
def _outcome(cohort: pd.DataFrame, pair: dict, settings: dict) -> tuple[pd.Series, pd.Series]:
|
|
if pair["kind"] == "domain":
|
|
css = _css(cohort)
|
|
return (css >= settings["css_high"]).astype(float).where(css.notna()), css
|
|
scores = pd.concat([item_scores(cohort, n) for n in outcome_items(pair)], axis=1)
|
|
complete = scores.notna().all(axis=1)
|
|
altered = (scores >= settings["item_altered"]).sum(axis=1).astype(float).where(complete)
|
|
level = altered if pair["kind"] == "composite" else scores.iloc[:, 0]
|
|
return (altered >= 1).astype(float).where(complete), level
|
|
|
|
|
|
def _high(pair: dict, settings: dict) -> int:
|
|
if pair["kind"] == "composite":
|
|
return 1
|
|
return settings["css_high" if pair["kind"] == "domain" else "item_altered"]
|
|
|
|
|
|
def _event(pair: dict, settings: dict) -> str:
|
|
if pair["kind"] == "composite":
|
|
return f"alguno >={settings['item_altered']}"
|
|
return f">={_high(pair, settings)}"
|
|
|
|
|
|
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 _fit_pair(d: pd.DataFrame, pair: dict, settings: dict) -> dict:
|
|
predictor = pair["predictor"]
|
|
used = d[["_yes", predictor]].dropna()
|
|
events = int(used["_yes"].sum())
|
|
without = len(used) - events
|
|
short = min(events, without) < settings["min_events"]
|
|
counted = short and pair["kind"] == "composite"
|
|
binary = _guarded(firth, "firth", d, "_yes", predictor, ADJUST)
|
|
graded = _guarded(
|
|
ordinal, "ordinal", d, "_level", predictor, ADJUST, high=_high(pair, settings)
|
|
)
|
|
ordinal_first = pair["kind"] == "domain" or counted
|
|
principal, sensitivity = (graded, binary) if ordinal_first else (binary, graded)
|
|
if short and principal.get("odds_ratio") is not None:
|
|
note = (
|
|
f"{INSUFFICIENT_DATA}{events} con evento y {without} sin evento "
|
|
f"(minimo {settings['min_events']})"
|
|
)
|
|
if counted:
|
|
note += "; se usa el numero de reactivos alterados"
|
|
principal = {**principal, "reason": note}
|
|
return {**pair, "principal": principal, "sensitivity": sensitivity}
|
|
|
|
|
|
def _q_values(rows: list[dict], settings: dict) -> np.ndarray:
|
|
tested = np.array([r["kind"] != "exploratory" for r in rows], bool)
|
|
families = np.array(
|
|
[r["biomarker"] if settings["q_family"] == "biomarker" else "all" for r in rows]
|
|
)
|
|
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
|
|
q = np.full(len(rows), np.nan)
|
|
for family in dict.fromkeys(families[tested]):
|
|
chosen = tested & (families == family)
|
|
q[chosen] = bh(p[chosen]).round(5)
|
|
return q
|
|
|
|
|
|
def _state(model: str, d: pd.DataFrame, pair: dict, settings: dict) -> dict | None:
|
|
try:
|
|
if model == "firth":
|
|
return firth_state(d, "_yes", pair["predictor"], ADJUST)
|
|
return ordinal_state(d, "_level", pair["predictor"], ADJUST, _high(pair, settings))
|
|
except (np.linalg.LinAlgError, ValueError):
|
|
return None
|
|
|
|
|
|
def _probability(model: str, state: dict, t: pd.DataFrame) -> np.ndarray:
|
|
return firth_probability(state, t) if model == "firth" else ordinal_probability(state, t)
|
|
|
|
|
|
def _reference(fit: dict) -> float:
|
|
reference = firth_reference if fit["model"] == "firth" else ordinal_reference
|
|
return reference(fit["state"])
|
|
|
|
|
|
def _scores(t: pd.DataFrame, fitted: set[str], pair: dict, settings: dict) -> np.ndarray:
|
|
fit = pair["principal"]
|
|
probability = _probability(fit["model"], fit["state"], t)
|
|
train = t[t["key"].map(_digest).isin(fitted)]
|
|
child = t["child" if "child" in t else "key"]
|
|
for name in child[train.index].unique():
|
|
own = (child == name).to_numpy()
|
|
state = _state(fit["model"], train[child[train.index] != name], pair, settings)
|
|
probability[own] = np.nan if state is None else _probability(fit["model"], state, t[own])
|
|
return probability
|
|
|
|
|
|
class Ados2Association:
|
|
name = "ados2_association"
|
|
version = "0.4.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}")
|
|
if fitted is not None and not {"settings", "pairs"} <= fitted.keys():
|
|
raise ValueError(
|
|
f"{self.name}: the saved model has no settings and pairs; retrain the association"
|
|
)
|
|
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")
|
|
settings = {
|
|
"item_altered": ITEM_ALTERED,
|
|
"css_high": CSS_HIGH,
|
|
"min_events": MIN_EVENTS,
|
|
"q_family": Q_FAMILY,
|
|
"clip_z": CLIP_Z,
|
|
}
|
|
prepared = _prepare(cohort, settings)
|
|
tested = pairs(level)
|
|
rows = []
|
|
for pair in tested:
|
|
if pair["predictor"] not in prepared:
|
|
continue
|
|
d = prepared.copy()
|
|
d["_yes"], d["_level"] = _outcome(d, pair, settings)
|
|
rows.append(_fit_pair(d, pair, settings))
|
|
for r, v in zip(rows, _q_values(rows, settings), strict=True):
|
|
r["q"] = None if np.isnan(v) else float(v)
|
|
self.fitted = {
|
|
"level": level,
|
|
"n": len(cohort),
|
|
"rows": rows,
|
|
"settings": settings,
|
|
"pairs": tested,
|
|
"css_sources": {"computed": int(_css(cohort).notna().sum())},
|
|
"keys": sorted(_digest(k) for k in cohort.get("key", [])),
|
|
}
|
|
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"]
|
|
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
|
|
out.append(
|
|
{
|
|
"biomarker": r["biomarker"],
|
|
"zone": r["zone"],
|
|
"kind": r["kind"],
|
|
"outcome": r["outcome"],
|
|
"outcome_code": outcome_code(r),
|
|
"event": _event(r, self.fitted["settings"]),
|
|
"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, leave_one_out: bool = True) -> pd.DataFrame:
|
|
rows = self._rows()
|
|
settings = self.fitted["settings"]
|
|
prepared = _prepare(cohort, settings)
|
|
fitted = set(self.fitted["keys"]) if leave_one_out else set()
|
|
parts = []
|
|
for r in rows:
|
|
f, predictor = r["principal"], r["predictor"]
|
|
if f.get("odds_ratio") is None or predictor not in prepared:
|
|
continue
|
|
t = prepared
|
|
for n in outcome_items(r):
|
|
t = t[t["ados_module"].isin(ITEMS[n][2])]
|
|
t = t[t[predictor].notna()].copy()
|
|
if not len(t):
|
|
continue
|
|
t["_yes"], t["_level"] = _outcome(t, r, settings)
|
|
prob = _scores(t, fitted, r, settings)
|
|
kept = np.isfinite(prob)
|
|
parts.append(
|
|
pd.DataFrame(
|
|
{
|
|
"key": t["key"].to_numpy()[kept],
|
|
"biomarker": r["biomarker"],
|
|
"zone": r["zone"],
|
|
"outcome_code": outcome_code(r),
|
|
"z": pd.to_numeric(cohort.loc[t.index, predictor]).to_numpy(float)[kept],
|
|
"probability": prob[kept].round(4),
|
|
"reference_probability": round(_reference(f), 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)
|