gradient: vendor the director's gradiente.py and baselines (APIs pending)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Modern gradient: API pending."""
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
Baselines, ported as they are (private copy; every biomarker owns one).
|
||||
|
||||
Functions copied verbatim:
|
||||
- biomarcadores-tea/biomarcadores/curvas.py @ 7dfc641: CUANTILES, rejilla,
|
||||
cuantil_ponderado, ajustar, en_edad, z_y_posicion
|
||||
- codigo/perfil_alteraciones.py @ c7a4736: MIN_CONTROLES_BLOQUE, bordes_edad,
|
||||
z_por_bloques, marcar_fuera (the cut-offs = p5/p95 of the controls' own z,
|
||||
as in construir_perfil.mete), with BLOQUES from codigo/curva_desarrollo.py
|
||||
|
||||
Two classes wrap them with fit / deviation / to_dict / from_dict:
|
||||
CentileCurves outside: below p5 or above p95 of the age curve; z = z_robusto
|
||||
AgeBlockZ outside: z beyond the controls' z p5 / p95; z = (x - median) / MAD
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
# ------------------------------------------------------------------ curvas.py (verbatim)
|
||||
CUANTILES = {"p5": 0.05, "p25": 0.25, "mediana": 0.5, "p75": 0.75, "p95": 0.95}
|
||||
|
||||
|
||||
def rejilla(edad_min=1.0, edad_max=216.0, puntos=120) -> np.ndarray:
|
||||
"""Edades (meses) espaciadas en escala log."""
|
||||
return np.exp(np.linspace(np.log(edad_min), np.log(edad_max), puntos))
|
||||
|
||||
|
||||
def cuantil_ponderado(x: np.ndarray, w: np.ndarray, q: float) -> float:
|
||||
"""Cuantil con pesos (interpolando entre los puntos medios de cada peso acumulado)."""
|
||||
o = np.argsort(x)
|
||||
x, w = x[o], w[o]
|
||||
c = (np.cumsum(w) - 0.5 * w) / w.sum()
|
||||
return float(np.interp(q, c, x))
|
||||
|
||||
|
||||
def ajustar(valores, edades_meses, ancho_log=0.2, n_min=30, edades=None) -> pd.DataFrame:
|
||||
"""Curva de percentiles: una fila por edad de la rejilla (edad_meses, n_efectivo, p5…p95)."""
|
||||
v = np.asarray(valores, dtype=float)
|
||||
e = np.asarray(edades_meses, dtype=float)
|
||||
ok = np.isfinite(v) & np.isfinite(e) & (e > 0)
|
||||
v, le = v[ok], np.log(e[ok])
|
||||
edades = rejilla() if edades is None else np.asarray(edades, dtype=float)
|
||||
filas = []
|
||||
for a in edades:
|
||||
w = np.exp(-0.5 * ((le - np.log(a)) / ancho_log) ** 2)
|
||||
n_ef = w.sum() ** 2 / (w ** 2).sum() if w.sum() > 0 else 0.0
|
||||
fila = {"edad_meses": round(float(a), 3), "n_efectivo": round(float(n_ef), 1)}
|
||||
dentro = len(le) and le.min() <= np.log(a) <= le.max()
|
||||
for nom, q in CUANTILES.items():
|
||||
fila[nom] = (round(cuantil_ponderado(v, w, q), 4) if n_ef >= n_min and dentro
|
||||
else np.nan)
|
||||
filas.append(fila)
|
||||
return pd.DataFrame(filas)
|
||||
|
||||
|
||||
def en_edad(edad_meses: float, curva: pd.DataFrame) -> dict | None:
|
||||
"""p5…p95 a una edad exacta (interpolados en log(edad)); None si la curva no la cubre."""
|
||||
c = curva.dropna(subset=list(CUANTILES))
|
||||
if not len(c) or not np.isfinite(edad_meses) or edad_meses <= 0:
|
||||
return None
|
||||
la, lx = np.log(edad_meses), np.log(c.edad_meses.to_numpy())
|
||||
if la < lx.min() or la > lx.max():
|
||||
return None
|
||||
return {nom: float(np.interp(la, lx, c[nom].to_numpy())) for nom in CUANTILES}
|
||||
|
||||
|
||||
def z_y_posicion(valores, edades_meses, curva: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""`z_robusto` y `posicion` de muchos valores a la vez (mismo resultado, sin bucle por fila)."""
|
||||
v = np.asarray(valores, dtype=float)
|
||||
e = np.asarray(edades_meses, dtype=float)
|
||||
z = np.full(v.shape, np.nan)
|
||||
pos = np.full(v.shape, "sin referencia", dtype=object)
|
||||
c = curva.dropna(subset=list(CUANTILES))
|
||||
if not len(c):
|
||||
return z, pos
|
||||
lx = np.log(c.edad_meses.to_numpy())
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
la = np.where(e > 0, np.log(np.where(e > 0, e, 1.0)), np.nan)
|
||||
ok = np.isfinite(v) & np.isfinite(la) & (la >= lx.min()) & (la <= lx.max())
|
||||
q = {k: np.interp(la, lx, c[k].to_numpy()) for k in CUANTILES}
|
||||
lado = np.where(v < q["mediana"], q["mediana"] - q["p5"], q["p95"] - q["mediana"])
|
||||
zz = (v - q["mediana"]) / (lado / 1.645)
|
||||
z[ok] = np.where(lado[ok] > 0, zz[ok], np.nan)
|
||||
pos[ok] = np.where(v[ok] < q["p5"][ok], "bajo p5",
|
||||
np.where(v[ok] > q["p95"][ok], "sobre p95", "dentro"))
|
||||
return z, pos
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ perfil_alteraciones.py (verbatim)
|
||||
BLOQUES = (2, 4, 6, 9, 12, 18, 24, 36, 48, 60, 84, 120, 192) # curva_desarrollo.BLOQUES
|
||||
MIN_CONTROLES_BLOQUE = 12
|
||||
|
||||
|
||||
def bordes_edad(edad_min, edad_max):
|
||||
"""Bloques de la curva de desarrollo recortados al rango pedido."""
|
||||
b = [x for x in BLOQUES if edad_min < x < edad_max]
|
||||
return [edad_min] + b + [edad_max]
|
||||
|
||||
|
||||
def z_por_bloques(xT, edadT, xC, edadC, bordes):
|
||||
"""
|
||||
z de cada caso contra la mediana y el MAD de los controles de su bloque
|
||||
de edad, y el z de los propios controles para sacar los cortes.
|
||||
|
||||
Un bloque con menos de MIN_CONTROLES_BLOQUE controles usa la normativa
|
||||
del rango completo, y se avisa: una banda de 8 controles es una línea
|
||||
firme dibujada sobre nada.
|
||||
"""
|
||||
xT = np.asarray(xT, dtype=float)
|
||||
xC = np.asarray(xC, dtype=float)
|
||||
bT = np.digitize(np.asarray(edadT, dtype=float), bordes[1:-1])
|
||||
bC = np.digitize(np.asarray(edadC, dtype=float), bordes[1:-1])
|
||||
okC = np.isfinite(xC)
|
||||
med_g = float(np.nanmedian(xC))
|
||||
mad_g = float(1.4826 * np.nanmedian(np.abs(xC - med_g))) or np.nan
|
||||
|
||||
zT = np.full(len(xT), np.nan)
|
||||
zC = np.full(len(xC), np.nan)
|
||||
for b in range(len(bordes) - 1):
|
||||
enC = okC & (bC == b)
|
||||
if enC.sum() >= MIN_CONTROLES_BLOQUE:
|
||||
med = float(np.median(xC[enC]))
|
||||
mad = float(1.4826 * np.median(np.abs(xC[enC] - med)))
|
||||
else:
|
||||
med, mad = med_g, mad_g
|
||||
if not np.isfinite(mad) or mad == 0:
|
||||
continue
|
||||
zT[bT == b] = (xT[bT == b] - med) / mad
|
||||
zC[enC] = (xC[enC] - med) / mad
|
||||
return zT, zC
|
||||
|
||||
|
||||
def marcar_fuera(P, cortes):
|
||||
F = pd.DataFrame(0, index=P.index,
|
||||
columns=[f"fuera_{c}" for c in P.columns])
|
||||
for c in P.columns:
|
||||
lo, hi = cortes[c]
|
||||
F.loc[P[c] < lo, f"fuera_{c}"] = -1
|
||||
F.loc[P[c] > hi, f"fuera_{c}"] = 1
|
||||
return F
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ wrappers
|
||||
class CentileCurves:
|
||||
name = "curves"
|
||||
|
||||
def __init__(self, ancho_log=0.2, n_min=30, curva=None):
|
||||
self.ancho_log = ancho_log
|
||||
self.n_min = n_min
|
||||
self.curva = curva
|
||||
|
||||
def fit(self, values, ages_months):
|
||||
self.curva = ajustar(values, ages_months, ancho_log=self.ancho_log, n_min=self.n_min)
|
||||
return self
|
||||
|
||||
def deviation(self, values, ages_months):
|
||||
z, pos = z_y_posicion(values, ages_months, self.curva)
|
||||
outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0))
|
||||
return outside.astype(int), z
|
||||
|
||||
def to_dict(self):
|
||||
return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min,
|
||||
"curva": self.curva.replace({np.nan: None}).to_dict("list")}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d):
|
||||
curva = pd.DataFrame(d["curva"]).astype(float)
|
||||
return cls(d["ancho_log"], d["n_min"], curva)
|
||||
|
||||
|
||||
class AgeBlockZ:
|
||||
name = "age_blocks"
|
||||
|
||||
def __init__(self, edad_min=12.0, edad_max=60.0, state=None):
|
||||
self.edad_min = edad_min
|
||||
self.edad_max = edad_max
|
||||
self.state = state
|
||||
|
||||
def fit(self, values, ages_months):
|
||||
v = np.asarray(values, float)
|
||||
e = np.asarray(ages_months, float)
|
||||
keep = (e >= self.edad_min) & (e <= self.edad_max) # perfil_alteraciones.filtra
|
||||
v, e = v[keep], e[keep]
|
||||
bordes = bordes_edad(self.edad_min, self.edad_max)
|
||||
_, zC = z_por_bloques(v, e, v, e, bordes)
|
||||
zC = zC[np.isfinite(zC)]
|
||||
blocks = []
|
||||
bC = np.digitize(e, bordes[1:-1])
|
||||
ok = np.isfinite(v)
|
||||
med_g = float(np.nanmedian(v))
|
||||
mad_g = float(1.4826 * np.nanmedian(np.abs(v - med_g))) or np.nan
|
||||
for b in range(len(bordes) - 1):
|
||||
en = ok & (bC == b)
|
||||
if en.sum() >= MIN_CONTROLES_BLOQUE:
|
||||
med = float(np.median(v[en]))
|
||||
blocks.append({"median": med, "mad": float(1.4826 * np.median(np.abs(v[en] - med))),
|
||||
"n": int(en.sum())})
|
||||
else:
|
||||
blocks.append({"median": med_g, "mad": mad_g, "n": int(en.sum()), "fallback": True})
|
||||
self.state = {"bordes": bordes, "blocks": blocks,
|
||||
"cortes": [float(np.percentile(zC, 5)), float(np.percentile(zC, 95))]
|
||||
if len(zC) else [np.nan, np.nan], "n": int(len(v))}
|
||||
return self
|
||||
|
||||
def deviation(self, values, ages_months):
|
||||
v = np.asarray(values, float)
|
||||
e = np.asarray(ages_months, float)
|
||||
bordes = self.state["bordes"]
|
||||
b = np.digitize(e, bordes[1:-1])
|
||||
z = np.full(len(v), np.nan)
|
||||
for i, (x, k) in enumerate(zip(v, b)):
|
||||
blk = self.state["blocks"][k]
|
||||
if np.isfinite(blk["mad"]) and blk["mad"] != 0:
|
||||
z[i] = (x - blk["median"]) / blk["mad"]
|
||||
P = pd.DataFrame({"m": z})
|
||||
F = marcar_fuera(P, {"m": tuple(self.state["cortes"])})
|
||||
return F["fuera_m"].to_numpy().astype(int), z
|
||||
|
||||
def to_dict(self):
|
||||
return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max,
|
||||
"state": self.state}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d):
|
||||
return cls(d["edad_min"], d["edad_max"], d["state"])
|
||||
|
||||
|
||||
BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ}
|
||||
|
||||
|
||||
def make(name, **params):
|
||||
try:
|
||||
return BASELINES[name](**params)
|
||||
except KeyError:
|
||||
raise ValueError(f"unknown baseline {name!r}; one of {', '.join(BASELINES)}") from None
|
||||
|
||||
|
||||
def from_dict(d):
|
||||
return BASELINES[d["name"]].from_dict(d)
|
||||
Reference in New Issue
Block a user