"""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.""" import warnings import numpy as np import pandas as pd import statsmodels.api as sm from scipy.stats import false_discovery_control 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 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, } TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" COLUMNS = [ "cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia", "delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia", "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(), } ) def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame: cohort = fitted.cohort frame = at_horizon(cohort.frame, horizon) data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy() reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates} t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates] months = np.floor(np.minimum(t, horizon + 1)).astype(int) 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) 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)) 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["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 = complete( tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment ) tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS tab = pd.concat([tab, tr], ignore_index=True) tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon return tab def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame: """Every horizon's table: by horizon, factors before treatments, by class, by odds ratio (decreasing); rounded to 4 places. `selection` (per horizon, the share of bootstrap LRs each covariate entered) defaults to the fit's own bootstrap.""" if selection is None: covariates = fitted.cohort.covariates selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()} with warnings.catch_warnings(), np.errstate(over="ignore"): warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons] 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"] 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) 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) return rows