Survival rates its scenarios' risk factors as Luis's code does; recurrence shares the factor code
This commit is contained in:
@@ -1,35 +1,20 @@
|
||||
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has.
|
||||
|
||||
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
|
||||
most frequent category by four criteria: (1) its adjusted odds ratio's 95 % CI excludes 1 and
|
||||
its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least FREQ_MIN of
|
||||
the time; (3) its covariate is a parent of the HBN; (4) its Kaplan-Meier recurrence-free
|
||||
survival at the horizon differs from the reference's (95 % CI) in the odds ratio's direction.
|
||||
"Robusto" needs (1) and three criteria, "sugerente" two. Treatments get their odds ratios,
|
||||
adjusted for the intrinsic covariates, but no class: they are associations, not effects."""
|
||||
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has
|
||||
(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2),
|
||||
the horizon's HBN parents give (3))."""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy.stats import false_discovery_control
|
||||
|
||||
from models import factors as rated
|
||||
from models.cama.recurrence.calculator import SCENARIOS, masks
|
||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
||||
from models.cama.recurrence.modeling import CohortFit, variable_of
|
||||
from models.curves import life_table
|
||||
from models.cama.recurrence.modeling import CohortFit
|
||||
from models.factors import FREQ_MIN, ORDER
|
||||
|
||||
ALPHA = 0.05
|
||||
FREQ_MIN = 0.80
|
||||
Z = 1.96
|
||||
ORDER = {
|
||||
"riesgo robusto": 0,
|
||||
"protector robusto": 1,
|
||||
"riesgo sugerente": 2,
|
||||
"protector sugerente": 3,
|
||||
"no concluyente": 4,
|
||||
}
|
||||
OR = "OR_recurrencia"
|
||||
SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S")
|
||||
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
COLUMNS = [
|
||||
"cohorte",
|
||||
@@ -39,16 +24,14 @@ COLUMNS = [
|
||||
"categoria",
|
||||
"referencia",
|
||||
"n_categoria",
|
||||
"OR_recurrencia",
|
||||
OR,
|
||||
"IC95_inf",
|
||||
"IC95_sup",
|
||||
"p",
|
||||
"p_ajustado_BH",
|
||||
"freq_seleccion_bootstrap",
|
||||
"en_manta_markov",
|
||||
"S_libre_categoria",
|
||||
"S_libre_referencia",
|
||||
"delta_S",
|
||||
*SURVIVAL,
|
||||
"delta_IC95_inf",
|
||||
"delta_IC95_sup",
|
||||
"c1_or",
|
||||
@@ -58,39 +41,7 @@ COLUMNS = [
|
||||
"criterios_cumplidos",
|
||||
"clasificacion",
|
||||
]
|
||||
# Scenario presence: the share of the scenario's patients in the category.
|
||||
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
|
||||
DESCRIBING = ("definitoria", "mayoritaria")
|
||||
|
||||
|
||||
def km_at(months, event, horizon) -> tuple[float, float]:
|
||||
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
|
||||
d, _, n = life_table(months, event)
|
||||
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
|
||||
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
|
||||
last = min(horizon, len(d) - 1) + 1
|
||||
S = float(np.prod(q[:last]))
|
||||
return S, S * float(np.sqrt(np.sum(v[:last])))
|
||||
|
||||
|
||||
def _odds_ratios(data: pd.DataFrame, y, variables, reference) -> pd.DataFrame:
|
||||
"""Logistic GLM on every category but each covariate's reference (constant and
|
||||
duplicated dummies dropped): odds ratios with Wald 95 % CI and p."""
|
||||
X = pd.get_dummies(data[variables]).astype(float)
|
||||
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
X = X.loc[:, ~X.T.duplicated()]
|
||||
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ci = np.exp(m.conf_int().loc[X.columns])
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"termino": X.columns,
|
||||
"OR_recurrencia": np.exp(m.params[X.columns].to_numpy()),
|
||||
"IC95_inf": ci[0].to_numpy(),
|
||||
"IC95_sup": ci[1].to_numpy(),
|
||||
"p": m.pvalues[X.columns].to_numpy(),
|
||||
}
|
||||
)
|
||||
DESCRIBING = rated.DESCRIBING
|
||||
|
||||
|
||||
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
|
||||
@@ -103,72 +54,23 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
|
||||
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
|
||||
|
||||
def complete(table, variables):
|
||||
"""Each term's covariate, category, BH p and survival difference to its reference."""
|
||||
table = table.reset_index(drop=True)
|
||||
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
|
||||
table["categoria"] = [
|
||||
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
|
||||
]
|
||||
table["referencia"] = table["variable"].map(reference)
|
||||
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
|
||||
rows = []
|
||||
for v, cat, ref in zip(
|
||||
table["variable"], table["categoria"], table["referencia"], strict=True
|
||||
):
|
||||
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == ref).to_numpy()
|
||||
(sa, ea), (sb, eb) = (
|
||||
km_at(months[a], event[a], horizon),
|
||||
km_at(months[b], event[b], horizon),
|
||||
)
|
||||
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
|
||||
rows.append(
|
||||
{
|
||||
"n_categoria": int(a.sum()),
|
||||
"S_libre_categoria": sa,
|
||||
"S_libre_referencia": sb,
|
||||
"delta_S": delta,
|
||||
"delta_IC95_inf": delta - Z * se,
|
||||
"delta_IC95_sup": delta + Z * se,
|
||||
}
|
||||
)
|
||||
return pd.concat([table, pd.DataFrame(rows)], axis=1)
|
||||
return rated.complete(table, variables, reference, everyone, months, event, horizon,
|
||||
SURVIVAL) # fmt: skip
|
||||
|
||||
intrinsic, treatment = cohort.intrinsic, cohort.treatment
|
||||
tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic)
|
||||
risk = tab["OR_recurrencia"] > 1
|
||||
tab["direccion"] = np.where(risk, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
|
||||
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
|
||||
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab["delta_S"]) == np.where(risk, -1, 1))
|
||||
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
|
||||
hz = fitted.horizons[horizon]
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
||||
lambda v: np.nan if selection is None else selection.get(v, 0.0)
|
||||
)
|
||||
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
||||
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
|
||||
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
|
||||
tab["clasificacion"] = [
|
||||
"no aplica (categoria desconocida)"
|
||||
if cat == UNKNOWN
|
||||
else f"{d} robusto"
|
||||
if c1 and k >= 3
|
||||
else f"{d} sugerente"
|
||||
if k >= 2
|
||||
else "no concluyente"
|
||||
for cat, d, c1, k in zip(
|
||||
tab["categoria"],
|
||||
tab["direccion"],
|
||||
tab["c1_or"],
|
||||
tab["criterios_cumplidos"],
|
||||
strict=True,
|
||||
)
|
||||
]
|
||||
tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
if treatment:
|
||||
both = intrinsic + treatment
|
||||
tr = _odds_ratios(data, y, both, reference)
|
||||
of = tr["termino"].map(lambda x: variable_of(x, both))
|
||||
tr = rated.odds_ratios(data, y, both, reference, OR)
|
||||
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||
tr = complete(
|
||||
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
||||
)
|
||||
@@ -191,72 +93,26 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra
|
||||
tab = pd.concat(found, ignore_index=True)
|
||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
|
||||
keys = ["horizonte_meses", "_kind", "_order", "OR_recurrencia"]
|
||||
keys = ["horizonte_meses", "_kind", "_order", OR]
|
||||
tab = tab.sort_values(keys, ascending=[True, True, True, False])
|
||||
return tab[COLUMNS].round(4)
|
||||
|
||||
|
||||
def _presence(share: float) -> str:
|
||||
if share >= DEFINING:
|
||||
return "definitoria"
|
||||
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
|
||||
|
||||
|
||||
def _listing(part: pd.DataFrame) -> str:
|
||||
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
|
||||
`asociacion`."""
|
||||
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
|
||||
part["clasificacion"].str.split().str[-1]) # fmt: skip
|
||||
return "; ".join(
|
||||
f"{v}={c} ({s}, {p:.0%})"
|
||||
for v, c, s, p in zip(
|
||||
part["variable"], part["categoria"], strength, part["share"], strict=True
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
|
||||
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
||||
patients have (definitorios) or most have (mayoritarios)."""
|
||||
frame, source = fitted.cohort.frame, fitted.cohort.source
|
||||
scenarios = SCENARIOS[source]
|
||||
found = factors[
|
||||
(factors["cohorte"] == source)
|
||||
& factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")
|
||||
]
|
||||
kind = np.where(
|
||||
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
|
||||
)
|
||||
found = found.assign(tipo_efecto=kind)
|
||||
found = rated.classified(factors[factors["cohorte"] == source])
|
||||
rows = []
|
||||
for name, mask in masks(frame, scenarios).items():
|
||||
if not mask.any() or found.empty:
|
||||
continue
|
||||
share = [
|
||||
float((frame.loc[mask, v] == c).mean())
|
||||
for v, c in zip(found["variable"], found["categoria"], strict=True)
|
||||
]
|
||||
detail = found.assign(share=share, presence=[_presence(s) for s in share])
|
||||
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
|
||||
for h in fitted.horizons:
|
||||
d = detail[detail["horizonte_meses"] == h]
|
||||
row = {
|
||||
"cohorte": source,
|
||||
"escenario": name,
|
||||
"definicion": definition,
|
||||
"n_escenario": int(mask.sum()),
|
||||
"horizonte_meses": h,
|
||||
}
|
||||
for k in ("riesgo", "protector", "tratamiento"):
|
||||
for level, label in (
|
||||
("definitoria", "definitorios"),
|
||||
("mayoritaria", "mayoritarios"),
|
||||
):
|
||||
row[f"{k}_{label}"] = _listing(
|
||||
d[(d["tipo_efecto"] == k) & (d["presence"] == level)]
|
||||
)
|
||||
included = (d["tipo_efecto"] == "riesgo") & d["presence"].isin(DESCRIBING)
|
||||
row["n_factores_riesgo_incluidos"] = int(included.sum())
|
||||
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
|
||||
rows.append(row)
|
||||
rows.append({
|
||||
"cohorte": source, "escenario": name, "definicion": definition,
|
||||
"n_escenario": int(mask.sum()), "horizonte_meses": h,
|
||||
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
|
||||
}) # fmt: skip
|
||||
return rows
|
||||
|
||||
@@ -21,6 +21,7 @@ from sklearn.metrics import roc_auc_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.recurrence.cohorts import Cohort, at_horizon
|
||||
from models.factors import variable_of
|
||||
|
||||
HORIZONS = (12, 36, 60) # months
|
||||
SEED = 42
|
||||
@@ -203,12 +204,6 @@ def c_index(cohort: Cohort) -> float:
|
||||
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
|
||||
|
||||
|
||||
def variable_of(term: str, covariates: list[str]) -> str:
|
||||
"""The covariate a dummy belongs to (the longest name it starts with)."""
|
||||
found = [c for c in covariates if term.startswith(c + "_")]
|
||||
return max(found, key=len) if found else term
|
||||
|
||||
|
||||
@dataclass
|
||||
class Horizon:
|
||||
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
|
||||
|
||||
@@ -153,6 +153,7 @@ MODELS = {
|
||||
cap_months=24,
|
||||
scenarios=SCENARIOS,
|
||||
scenario_columns=("age",),
|
||||
treatments=("surgery", "chemotherapy", "radiotherapy"),
|
||||
notes=(
|
||||
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
|
||||
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
|
||||
|
||||
Reference in New Issue
Block a user