diff --git a/models/cama/recurrence/factors.py b/models/cama/recurrence/factors.py index 3b07781..a46835c 100644 --- a/models/cama/recurrence/factors.py +++ b/models/cama/recurrence/factors.py @@ -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 diff --git a/models/cama/recurrence/modeling.py b/models/cama/recurrence/modeling.py index 438a2b8..aee6adb 100644 --- a/models/cama/recurrence/modeling.py +++ b/models/cama/recurrence/modeling.py @@ -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 diff --git a/models/cama/specs.py b/models/cama/specs.py index 9af412b..66d59b5 100644 --- a/models/cama/specs.py +++ b/models/cama/specs.py @@ -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 " diff --git a/models/factors.py b/models/factors.py new file mode 100644 index 0000000..455cca5 --- /dev/null +++ b/models/factors.py @@ -0,0 +1,178 @@ +"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models. + +Each category of an intrinsic covariate (not a treatment) is rated against its covariate's +most frequent category by up to 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 in the outcome's Markov blanket in the HBN; (4) its +Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's +direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three +criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get +their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations, +not effects. Each clinical scenario then lists the classified factors nearly all of its +patients have (definitorios) or most have (mayoritarios).""" + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.stats import false_discovery_control + +from models.curves import life_table + +ALPHA = 0.05 +FREQ_MIN = 0.80 +Z = 1.96 +CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia") +ORDER = { + "riesgo robusto": 0, + "protector robusto": 1, + "riesgo sugerente": 2, + "protector sugerente": 3, + "no concluyente": 4, +} +UNKNOWN_CLASS = "no aplica (categoria desconocida)" +# 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 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 + + +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, name: str) -> pd.DataFrame: + """Logistic GLM on every category but each covariate's reference (constant and + duplicated dummies dropped): odds ratios (column `name`) 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, + name: 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 complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame, + months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip + """Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at + `horizon` over `everyone` (`names`: the category's, the reference's and the difference's + survival columns).""" + 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 [] + category, ref, delta_name = names + rows = [] + for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True): + a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy() + sa, ea = km_at(months[a], event[a], horizon) + sb, eb = km_at(months[b], event[b], horizon) + delta, se = sa - sb, np.sqrt(ea**2 + eb**2) + rows.append({ + "n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta, + "delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se, + }) # fmt: skip + return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name, + "delta_IC95_inf", "delta_IC95_sup"])], + axis=1) # fmt: skip + + +def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str, + evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip + """c1 and c4 from the table, then each category's class; c2 and c3 must already be set + for the criteria `evaluated`.""" + risk = tab[or_name] > 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_name]) == np.where(risk, -1, 1)) + tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1) + robust = min(3, len(evaluated)) + tab["clasificacion"] = [ + UNKNOWN_CLASS + if cat == unknown + else f"{d} robusto" + if c1 and k >= robust + 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, + ) + ] + return tab + + +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 classified(factors: pd.DataFrame) -> pd.DataFrame: + """The factors a scenario can list (classified ones and treatments), with `tipo_efecto`: + riesgo, protector or tratamiento.""" + found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")] + kind = np.where( + found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0] + ) + return found.assign(tipo_efecto=kind) + + +def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict: + """What one scenario's patients (`mask` over `frame`) have of the `classified` factors: + the listings by kind and presence, and how many risk factors describe it.""" + 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]) + row = {} + for k in ("riesgo", "protector", "tratamiento"): + for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")): + row[f"{k}_{label}"] = listing( + detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)] + ) + included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING) + row["n_factores_riesgo_incluidos"] = int(included.sum()) + row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0 + return row diff --git a/models/survival.py b/models/survival.py index d7ebb41..8588e79 100644 --- a/models/survival.py +++ b/models/survival.py @@ -9,6 +9,8 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi category of its own (UNKNOWN). """ +import json +import warnings from dataclasses import dataclass, field from itertools import pairwise @@ -267,6 +269,8 @@ class Spec: # "in", value) on the members' covariates and `scenario_columns` (kept for them only). scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict) scenario_columns: tuple[str, ...] = () + # Features that are treatments: their odds ratios are reported as associations, unclassified. + treatments: tuple[str, ...] = () @property def horizons(self) -> tuple[float, ...]: @@ -503,4 +507,102 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: "escenarios": scenarios, "escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths "min_fallecidos_escenario": MIN_SCENARIO_EVENTS, + **risk_factor_report(spec, model, members), + } + + +# ---------------------------------------------------------------- risk factors + +FACTOR_COLUMNS = ( + "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", + "IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia", + "delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov", + "c4_supervivencia", "criterios_cumplidos", "clasificacion", +) # fmt: skip +SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S") +TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" +# The model has no variable selection to resample, so stability (2) is not evaluated. +EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia") + + +def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame: + """The members' risk factors of death by the last horizon (`models.factors`, as the + SEER-trained original rates them): odds ratios of dying before it, among those dead before + it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at + `cap_months`); the Markov blanket is the HBN's parents in any interval.""" + from models import factors as rated + + horizon = spec.borders[-1] + months, event = members["months"].to_numpy(), members["event"].to_numpy(bool) + died = event & (months < horizon) + known = died | (months >= horizon) + data = spec._combinations(members)[known].reset_index(drop=True) + y, months, event = died[known].astype(int), months[known], event[known] + empty = pd.DataFrame(columns=list(FACTOR_COLUMNS)) + if len(data) == 0 or y.min() == y.max(): + return empty + features = list(spec.features) + treatment = [f for f in features if f in spec.treatments] + intrinsic = [f for f in features if f not in spec.treatments] + reference = {v: data[v].value_counts().idxmax() for v in features} + blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents} + + def complete(table, variables): + return rated.complete(table, variables, reference, data, months, event, horizon, + SURVIVAL_COLUMNS) # fmt: skip + + with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"): + warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios + try: + tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"), + intrinsic) # fmt: skip + except (np.linalg.LinAlgError, ValueError): + return empty + tab["c2_estabilidad"] = np.nan + tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket) + tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED) + tab["tipo"] = "factor de riesgo" + if treatment: + both = intrinsic + treatment + try: + tr = rated.odds_ratios(data, y, both, reference, "OR_muerte") + except (np.linalg.LinAlgError, ValueError): + tr = None + if tr is not None: + of = tr["termino"].map(lambda x: rated.variable_of(x, both)) + tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], + treatment) # fmt: skip + tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS + tab = pd.concat([tab, tr], ignore_index=True) + tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) + tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5) + tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False]) + return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True) + + +def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]: + """Per clinical scenario, the classified factors and treatments nearly all of its + members have (definitorios) or most have (mayoritarios).""" + from models import factors as rated + + found = rated.classified(table) if len(table) else table + data = spec._combinations(members) + rows = [] + for name, mask in scenario_masks(members, spec.scenarios).items(): + if not mask.any() or found.empty: + continue + rows.append({ + "escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]], + "n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found), + }) # fmt: skip + return rows + + +def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict: + """The interpretability report's risk factors: the table and each scenario's summary.""" + table = risk_factors(spec, model, members) + rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON + return { + "factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows}, + "factores_escenarios": scenario_factors(spec, members, table), } diff --git a/tests/test_survival_seer.py b/tests/test_survival_seer.py index 724dc6e..47ad5bb 100644 --- a/tests/test_survival_seer.py +++ b/tests/test_survival_seer.py @@ -180,3 +180,32 @@ def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")] gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max() print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}") + + +# The original's names for the categories both rate alike (stage, grade, receptors). +SAME = { + ("Estadio", "IV"): ("stage", "IV"), ("Estadio", "III"): ("stage", "III"), + ("Estadio", "II"): ("stage", "II"), ("Estadio", "0 (in situ)"): ("stage", "0"), + ("Grado_histologico", "G3"): ("grade", "3"), ("Grado_histologico", "G1"): ("grade", "1"), + ("Receptor_progesterona", "Negativo"): ("pr", "negative"), +} # fmt: skip + + +def test_risk_factors_rate_as_the_originals(trained): + """The risk factors of death by 18 months (models.factors, as `06_factores_riesgo.py`) + on the same SEER cases: the same direction for every category both rate, the same class + for stage and grade, odds ratios within 20 % and 18-month survival within 0.05. The + original also rates the stability of its stepwise selection and reads the Markov blanket + of a learned network; the platform's model has neither stepwise selection nor PR among + its network's parents, so PR negative is "sugerente" here and "robusto" there.""" + spec, model, _, data = trained + members = pd.concat([data["train"], data["test"]]).reset_index(drop=True) + ours = survival.risk_factors(spec, model, members).set_index(["variable", "categoria"]) + theirs = _original("factores_riesgo.csv").set_index(["variable", "categoria"]) + for key, mine in SAME.items(): + a, b = theirs.loc[key], ours.loc[mine] + assert b["clasificacion"].split()[0] == a["clasificacion"].split()[0], key + if key[0] != "Receptor_progesterona": + assert b["clasificacion"] == a["clasificacion"], key + assert b["OR_muerte"] == pytest.approx(a["OR_muerte"], rel=0.2), key + assert b["S_categoria"] == pytest.approx(a["S18_categoria"], abs=0.05), key