diff --git a/models/cama/experiments/recurrence/01_preparacion_metabric.py b/models/cama/experiments/recurrence/01_preparacion_metabric.py new file mode 100644 index 0000000..d1a959e --- /dev/null +++ b/models/cama/experiments/recurrence/01_preparacion_metabric.py @@ -0,0 +1,71 @@ +import json +import os +import numpy as np +import pandas as pd + +CSV_ENTRADA = "./brca_metabric_clinical_data.tsv" +DIR_INT = "./intermedios_recurrencia" +os.makedirs(DIR_INT, exist_ok=True) +V_MAX = 0.80 + +d = pd.read_csv(CSV_ENTRADA, sep="\t") +d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True) + +out = pd.DataFrame({"paciente": d["Patient ID"]}) +out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float) +out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int) + +def con_desconocido(s): + return s.astype("object").where(s.notna(), "Desconocido").astype(str) + +def cortar(s, cortes, etiquetas): + c = pd.cut(s, cortes, labels=etiquetas, right=False) + return con_desconocido(c.astype("object")) + +out["Edad"] = cortar(d["Age at Diagnosis"], [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) +out["Tamano_tumor"] = cortar(d["Tumor Size"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]) +out["Ganglios_positivos"] = cortar(d["Lymph nodes examined positive"], [0, 1, 4, 1e3], ["0", "1-3", "4+"]) +out["Grado_histologico"] = con_desconocido(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"})) +mc = d["Mutation Count"] +q = mc.quantile([1 / 3, 2 / 3]).values +out["Carga_mutacional"] = cortar(mc, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"]) +for nombre, col in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"), + ("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"), + ("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"), + ("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"), + ("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"), + ("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]: + out[nombre] = con_desconocido(d[col]) + +TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"] +covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento")] + + +def cramer_v(a, b): + t = pd.crosstab(a, b) + from scipy.stats import chi2_contingency + chi2 = chi2_contingency(t, correction=False)[0] + n = t.values.sum() + k = min(t.shape) - 1 + return np.sqrt(chi2 / (n * k)) if k > 0 else 0.0 + + +eliminadas = [] +cand = [c for c in covariables if c not in TRATAMIENTO] +pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True) +for v, a, b in pares: + if v < V_MAX: + break + if a in eliminadas or b in eliminadas: + continue + na_a, na_b = (out[a] == "Desconocido").mean(), (out[b] == "Desconocido").mean() + quitar = a if na_a >= na_b else b + eliminadas.append(quitar) + covariables.remove(quitar) +pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia.csv", index=False) + +out = out[["paciente", "tiempo_meses", "evento"] + covariables] +out.to_csv(f"{DIR_INT}/cohorte_recurrencia.csv", index=False) +with open(f"{DIR_INT}/covariables_recurrencia.json", "w", encoding="utf8") as f: + json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables], + "eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False) diff --git a/models/cama/experiments/recurrence/02_preparacion_scanb.py b/models/cama/experiments/recurrence/02_preparacion_scanb.py new file mode 100644 index 0000000..6c58585 --- /dev/null +++ b/models/cama/experiments/recurrence/02_preparacion_scanb.py @@ -0,0 +1,70 @@ +import json +import os +import numpy as np +import pandas as pd +from scipy.stats import chi2_contingency + +CSV_ENTRADA = "./scanb_clinical_metadata.txt" +V_MAX = 0.80 +DIAS_POR_MES = 30.4375 +DIR_INT = "./intermedios_recurrencia" +os.makedirs(DIR_INT, exist_ok=True) + +d = pd.read_csv(CSV_ENTRADA, sep="\t", low_memory=False) +d = d[d["Gender"] == "F"] +d = d.dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True) + +out = pd.DataFrame({"paciente": d["PatientName"]}) +out["tiempo_meses"] = d["RFI_days"].astype(float) / DIAS_POR_MES +out["evento"] = d["RFI_event"].astype(int) +out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int) + + +def con_desconocido(s): + return s.astype("object").where(s.notna(), "Desconocido").astype(str) + + +def cortar(s, cortes, etiquetas): + return con_desconocido(pd.cut(s, cortes, labels=etiquetas, right=False).astype("object")) + + +out["Edad"] = cortar(d["Age_5year_bin"].astype(float) - 2, [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) +out["Tamano_tumor"] = cortar(d["TumorSize_mm"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]) +out["Ganglios_positivos"] = con_desconocido(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"})) +out["Grado_histologico"] = con_desconocido(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"})) +for nombre, col in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"), + ("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"), + ("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"), + ("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"), + ("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]: + out[nombre] = con_desconocido(d[col]) + +TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"] +covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento", "muerte_sin_recaida")] + + +def cramer_v(a, b): + t = pd.crosstab(a, b) + chi2 = chi2_contingency(t, correction=False)[0] + k = min(t.shape) - 1 + return np.sqrt(chi2 / (t.values.sum() * k)) if k > 0 else 0.0 + + +eliminadas = [] +cand = [c for c in covariables if c not in TRATAMIENTO] +pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True) +for v, a, b in pares: + if v < V_MAX: + break + if a in eliminadas or b in eliminadas: + continue + quitar = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b + eliminadas.append(quitar) + covariables.remove(quitar) +pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia_scanb.csv", index=False) + +out = out[["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] + covariables] +out.to_csv(f"{DIR_INT}/cohorte_recurrencia_scanb.csv", index=False) +with open(f"{DIR_INT}/covariables_recurrencia_scanb.json", "w", encoding="utf8") as f: + json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables], + "eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False) diff --git a/models/cama/experiments/recurrence/03_modelado.py b/models/cama/experiments/recurrence/03_modelado.py new file mode 100644 index 0000000..c9562a5 --- /dev/null +++ b/models/cama/experiments/recurrence/03_modelado.py @@ -0,0 +1,261 @@ +import json +import os +import sys +import warnings +import numpy as np +import pandas as pd +import statsmodels.api as sm +from sklearn.model_selection import train_test_split +from sklearn.metrics import roc_auc_score, roc_curve +from sklearn.calibration import calibration_curve +from lifelines import CoxPHFitter +from lifelines.utils import concordance_index +from pgmpy.estimators import HillClimbSearch, BDeu +from pgmpy.causal_discovery import ExpertKnowledge +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import networkx as nx + +warnings.filterwarnings("ignore") + +COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric" +HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60] +SFX = "" if COHORTE == "metabric" else f"_{COHORTE}" +DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia" +os.makedirs(DIR_INT, exist_ok=True) +os.makedirs(DIR_FIG, exist_ok=True) + +SEMILLA = 42 +N_BOOTSTRAP = int(os.environ.get("N_BOOTSTRAP", 100 if COHORTE == "metabric" else 40)) +BDEU_ESS = 10 +MAX_PADRES = 6 +ALFA_IN, ALFA_OUT, ALFA_PREFILTRO = 0.10, 0.15, 0.10 + +meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8")) +covariables = meta["covariables"] +coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables}) + +TIER_DEMOGRAFIA = ["Edad", "Estado_menopausico"] +TIER_TUMOR = ["Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno", + "Receptor_progesterona", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Cluster_integrativo", "Lateralidad", + "Ki67", "Subtipo_clinico", "Estadio_clinico"] +TIER_TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"] + + +# ---- funciones ---- +def orden_temporal(cols): + tiers = [[c for c in t if c in cols] for t in (TIER_DEMOGRAFIA, TIER_TUMOR, TIER_TRATAMIENTO, ["outcome"])] + sin = [c for c in cols if c not in sum(tiers, [])] + return ([sin] if sin else []) + [t for t in tiers if t] + + +def codificar(df): + X = pd.get_dummies(df[covariables], drop_first=True).astype(float) + return X.loc[:, X.nunique() > 1] + + +def ajuste_logit(y, X): + try: + return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300) + except Exception: + return None + + +def prefiltro(X, y): + keep = [] + for c in X.columns: + m = ajuste_logit(y, X[[c]]) + if m is not None and m.pvalues[c] < ALFA_PREFILTRO: + keep.append(c) + return keep + + +def stepwise(X, y): + incl = [] + for _ in range(200): + cambio = False + mejor, p_mejor = None, ALFA_IN + for c in [c for c in X.columns if c not in incl]: + m = ajuste_logit(y, X[incl + [c]]) + if m is not None and m.pvalues[c] < p_mejor: + mejor, p_mejor = c, m.pvalues[c] + if mejor is not None: + incl.append(mejor) + cambio = True + if incl: + m = ajuste_logit(y, X[incl]) + if m is not None: + p = m.pvalues.drop("const") + if p.max() > ALFA_OUT: + incl.remove(p.idxmax()) + cambio = True + if not cambio: + break + return incl + + +def lr_completo(df_train, df_test): + Xall = codificar(pd.concat([df_train, df_test])) + Xtr, Xte = Xall.loc[df_train.index], Xall.loc[df_test.index] + Xtr = Xtr.loc[:, Xtr.nunique() > 1] + Xte = Xte[Xtr.columns] + cand = prefiltro(Xtr, df_train["y"]) + sel = stepwise(Xtr[cand], df_train["y"]) if cand else [] + if not sel: + return None, [], np.full(len(df_test), df_train["y"].mean()) + m = ajuste_logit(df_train["y"], Xtr[sel]) + return m, sel, m.predict(sm.add_constant(Xte[sel], has_constant="add")).values + + +def variable_de(t): + return next((c for c in sorted(covariables, key=len, reverse=True) if t.startswith(c + "_")), t) + + +def padres_outcome(train, candidatos): + sc = BDeu(train, equivalent_sample_size=BDEU_ESS) + padres, actual = [], sc.local_score("outcome", []) + while len(padres) < MAX_PADRES: + mejor, ganancia = None, 0 + for c in candidatos: + if c in padres: + continue + g = sc.local_score("outcome", padres + [c]) - actual + if g > ganancia: + mejor, ganancia = c, g + if mejor is None: + break + padres.append(mejor) + actual += ganancia + return padres + + +def prob_hbn(train, test, padres): + if not padres: + return np.full(len(test), (train["outcome"] == "1").mean()) + q = int(np.prod([train[p].nunique() for p in padres])) + alpha = BDEU_ESS / (2 * q) + g = train.groupby(padres)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size") + p_glob = (train["outcome"] == "1").mean() + tabla = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()} + return np.array([tabla.get(k, p_glob) for k in map(tuple, test[padres].values)]) + + +def tabla_bn(df): + t = df[covariables].astype(str).copy() + t["outcome"] = df["y"].astype(int).astype(str) + return t + + +def cohorte_a_horizonte(H): + recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H) + libre = coh_total["tiempo_meses"] > H + d = coh_total[recurre | libre].reset_index(drop=True) + d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int) + return d + + +# ---- Cox de referencia (tiempo completo) ---- +cox_df = pd.get_dummies(coh_total[["tiempo_meses", "evento"] + covariables], columns=covariables, drop_first=True).astype(float) +cox_df = cox_df.loc[:, cox_df.nunique() > 1] +ctr, cte = train_test_split(cox_df, test_size=0.3, random_state=SEMILLA, stratify=cox_df["evento"]) +_ok = [c for c in ctr.columns if c in ("tiempo_meses", "evento") or 10 <= ctr[c].sum() <= len(ctr) - 10] +ctr, cte = ctr[_ok], cte[_ok] +cox = CoxPHFitter(penalizer=0.05).fit(ctr, "tiempo_meses", "evento", fit_options={"step_size": 0.5}) +c_index = concordance_index(cte["tiempo_meses"], -cox.predict_partial_hazard(cte), cte["evento"]) + + +# ---- modelos por horizonte ---- +filas_auc, modelos_json, curvas = [], {}, {} +for H in HORIZONTES: + coh = cohorte_a_horizonte(H) + tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=SEMILLA, stratify=coh["y"]) + tr, te = coh.loc[tr_idx], coh.loc[te_idx] + + modelo_lr, sel_lr, p_lr = lr_completo(tr, te) + auc_lr = roc_auc_score(te["y"], p_lr) + + bn_tr, bn_te = tabla_bn(tr), tabla_bn(te) + padres = padres_outcome(bn_tr, covariables) + p_hbn = prob_hbn(bn_tr, bn_te, padres) + auc_hbn = roc_auc_score(te["y"], p_hbn) + + if H == max(HORIZONTES): + expert = ExpertKnowledge(temporal_order=orden_temporal(list(bn_tr.columns))) + estructura = HillClimbSearch(bn_tr).estimate(scoring_method=BDeu(bn_tr, equivalent_sample_size=BDEU_ESS), max_indegree=4, + expert_knowledge=expert, show_progress=False) + arcos_red = [(u, v) for u, v in estructura.edges() if u != "outcome" and v != "outcome"] + [(p, "outcome") for p in padres] + G = nx.DiGraph(arcos_red) + plt.figure(figsize=(10, 7)) + nx.draw(G, nx.spring_layout(G, seed=SEMILLA, k=0.9), with_labels=True, node_color="lightblue", node_size=2200, font_size=7, arrowsize=14) + plt.title(f"Estructura de la red bayesiana ({COHORTE}, {H} meses)") + plt.tight_layout() + plt.savefig(f"{DIR_FIG}/hbn_estructura_{COHORTE}.png", dpi=150) + plt.close() + + rng = np.random.default_rng(SEMILLA) + aucs, cuenta_lr, cuenta_hbn, n_lr, n_hbn = [], {}, {}, 0, 0 + for b in range(N_BOOTSTRAP): + db = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True) + try: + dtr, dte = train_test_split(db, test_size=0.3, random_state=SEMILLA + b, stratify=db["y"]) + m, sel, p = lr_completo(dtr, dte) + a_lr = roc_auc_score(dte["y"], p) + btr, bte = tabla_bn(dtr), tabla_bn(dte) + pa = padres_outcome(btr, covariables) + a_h = roc_auc_score(dte["y"], prob_hbn(btr, bte, pa)) + except Exception: + continue + aucs.append((a_lr, a_h)) + n_lr += 1 + n_hbn += 1 + if m is not None: + for v in {variable_de(t) for t in m.params.drop("const").index}: + cuenta_lr[v] = cuenta_lr.get(v, 0) + 1 + for v in pa: + cuenta_hbn[v] = cuenta_hbn.get(v, 0) + 1 + aucs = np.array(aucs) + for j, (nombre, auc_int) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]): + filas_auc.append({"cohorte": COHORTE, "horizonte_meses": H, "modelo": nombre, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()), + "AUC_validacion_interna": auc_int, "AUC_bootstrap_medio": aucs[:, j].mean(), + "AUC_bootstrap_IC95_inf": np.percentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.percentile(aucs[:, j], 97.5), + "replicas_bootstrap": len(aucs)}) + ci = modelo_lr.conf_int() + modelos_json[str(H)] = {"terminos_lr": list(sel_lr), "padres_hbn": padres, "n_replicas": n_lr, + "seleccion_lr": cuenta_lr, "seleccion_hbn": cuenta_hbn, + "arcos_hbn": [list(a) for a in (arcos_red if H == max(HORIZONTES) else [(p, "outcome") for p in padres])]} + curvas[H] = (te["y"].values, p_lr, p_hbn) + +filas_auc.append({"cohorte": COHORTE, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(coh_total), + "recurrencias": int(coh_total["evento"].sum()), "AUC_validacion_interna": c_index}) +json.dump(modelos_json, open(f"{DIR_INT}/modelos{SFX}.json", "w", encoding="utf8"), indent=1, ensure_ascii=False) + +# ---- consolidado de AUC (un solo archivo con las dos cohortes) ---- +nuevo = pd.DataFrame(filas_auc) +destino = "./auc_recurrencia.csv" +if os.path.exists(destino): + previo = pd.read_csv(destino) + previo = previo[~((previo["cohorte"] == COHORTE) & (previo["horizonte_meses"].astype(str).isin([str(h) for h in HORIZONTES] + ["completo"])))] + nuevo = pd.concat([previo, nuevo], ignore_index=True) +nuevo.round(4).to_csv(destino, index=False) + +# ---- figuras: ROC y calibracion (un panel por horizonte) ---- +for nombre_fig, tipo in [("roc", "roc"), ("calibracion", "cal")]: + fig, axs = plt.subplots(1, len(HORIZONTES), figsize=(5.2 * len(HORIZONTES), 5), squeeze=False) + for ax, H in zip(axs[0], HORIZONTES): + y, pl, ph = curvas[H] + for nom, p in [("LR", pl), ("HBN", ph)]: + if tipo == "roc": + f, t, _ = roc_curve(y, p) + ax.plot(f, t, label=f"{nom} (AUC {roc_auc_score(y, p):.3f})") + else: + fr, mp = calibration_curve(y, p, n_bins=8, strategy="quantile") + ax.plot(mp, fr, "o-", label=nom) + ax.plot([0, 1], [0, 1], "k:") + ax.set_title(f"{COHORTE}: {H} meses") + ax.set_xlabel("1 - especificidad" if tipo == "roc" else "probabilidad predicha de recurrencia") + ax.set_ylabel("sensibilidad" if tipo == "roc" else "frecuencia observada") + ax.legend() + fig.tight_layout() + fig.savefig(f"{DIR_FIG}/{nombre_fig}_{COHORTE}.png", dpi=150) + plt.close(fig) diff --git a/models/cama/experiments/recurrence/04_factores_riesgo.py b/models/cama/experiments/recurrence/04_factores_riesgo.py new file mode 100644 index 0000000..db57602 --- /dev/null +++ b/models/cama/experiments/recurrence/04_factores_riesgo.py @@ -0,0 +1,158 @@ +import sys +import os +import json +import numpy as np +import pandas as pd +import statsmodels.api as sm + +COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric" +HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60] +SFX = "" if COHORTE == "metabric" else f"_{COHORTE}" +DIR_INT = "./intermedios_recurrencia" +ALFA = 0.05 +FREQ_MIN = 0.80 + +meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8")) +variables = meta["covariables"] +tratamiento = meta["tratamiento"] +intrinsecas = [v for v in variables if v not in tratamiento] +modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8")) +coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in variables}) + + +# ---- funciones ---- +def bh(p): + p = np.asarray(p, float) + orden = np.argsort(p) + aj = np.empty_like(p) + m = len(p) + prev = 1.0 + for rango, i in zip(range(m, 0, -1), orden[::-1]): + prev = min(prev, p[i] * m / rango) + aj[i] = prev + return aj + + +def variable_de(termino, vars_modelo): + return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_")) + + +def km_en(m, e, h): + T = int(m.max()) + 2 + d = np.bincount(m[e], minlength=T) + c = np.bincount(m[~e], minlength=T) + en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]]) + with np.errstate(divide="ignore", invalid="ignore"): + q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0) + v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0) + h = min(h, T - 1) + S = np.prod(q[:h + 1]) + return S, S * np.sqrt(np.sum(v[:h + 1])) + + +def procesar_horizonte(H): + recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H) + libre = coh_total["tiempo_meses"] > H + datos_km = coh_total.copy() + coh = coh_total[recurre | libre].reset_index(drop=True) + datos = coh[variables].astype(str) + y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values + meses = np.floor(np.minimum(datos_km["tiempo_meses"].values, H + 1)).astype(int) + evento = ((datos_km["evento"] == 1) & (datos_km["tiempo_meses"] <= H)).values + datos_km = datos_km[variables].astype(str) + + def referencia(v): + return datos[v].value_counts().idxmax() + + def ajustar_or(vars_modelo): + X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float) + refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo} + X = X.drop(columns=[r for r in refs.values() if r in X.columns]) + X = X.loc[:, X.nunique() > 1] + X = X.loc[:, ~X.T.duplicated()] + modelo = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit() + ic = modelo.conf_int() + return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(modelo.params[X.columns].values), + "IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values), + "p": modelo.pvalues[X.columns].values}) + + def delta_s(v, cat, ref): + a = (datos_km[v] == cat).values + b = (datos_km[v] == ref).values + Sa, ea = km_en(meses[a], evento[a], H) + Sb, eb = km_en(meses[b], evento[b], H) + d = Sa - Sb + es = np.sqrt(ea ** 2 + eb ** 2) + return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d, + "delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es}) + + def completar(t, vars_modelo): + t = t.copy() + t["variable"] = [variable_de(x, vars_modelo) for x in t["termino"]] + t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])] + t["referencia"] = [referencia(v) for v in t["variable"]] + t["p_ajustado_BH"] = bh(t["p"]) + ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])]) + return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1) + + tab = completar(ajustar_or(intrinsecas), intrinsecas) + tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector") + tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA) + tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \ + (np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1)) + + mh = modelos.get(str(H), {}) + n_rep = mh.get("n_replicas", 0) + sel = mh.get("seleccion_lr", {}) + tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: sel.get(v, 0) / n_rep if n_rep else np.nan) + tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN + manta = set(mh.get("padres_hbn", [])) + tab["en_manta_markov"] = tab["variable"].isin(manta) + tab["c3_manta_markov"] = tab["en_manta_markov"] + + crit = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"] + tab["criterios_cumplidos"] = tab[crit].astype(bool).sum(axis=1) + + def clasificar(r): + if r["categoria"] == "Desconocido": + return "no aplica (categoria desconocida)" + if r["c1_or"] and r["criterios_cumplidos"] >= 3: + return f"{r['direccion']} robusto" + if r["criterios_cumplidos"] >= 2: + return f"{r['direccion']} sugerente" + return "no concluyente" + + tab["clasificacion"] = tab.apply(clasificar, axis=1) + tab["tipo"] = "factor de riesgo" + + if tratamiento: + tr = ajustar_or(intrinsecas + tratamiento) + tr["_v"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]] + tr = tr[tr["_v"].isin(tratamiento) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v") + tr = completar(tr, tratamiento) + tr["tipo"] = "tratamiento" + tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)" + tab = pd.concat([tab, tr], ignore_index=True) + + tab["cohorte"] = COHORTE + tab["horizonte_meses"] = H + return tab + + +columnas = ["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"] +orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4} + +nuevo = pd.concat([procesar_horizonte(H) for H in HORIZONTES], ignore_index=True) +nuevo["_t"] = (nuevo["tipo"] != "factor de riesgo").astype(int) +nuevo["_o"] = nuevo["clasificacion"].map(orden).fillna(5) +nuevo = nuevo.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[columnas] + +destino = "./factores_riesgo_recurrencia.csv" +if os.path.exists(destino): + previo = pd.read_csv(destino) + previo = previo[previo["cohorte"] != COHORTE] + nuevo = pd.concat([previo, nuevo], ignore_index=True) +nuevo.round(4).to_csv(destino, index=False) diff --git a/models/cama/experiments/recurrence/05_calculadora.py b/models/cama/experiments/recurrence/05_calculadora.py new file mode 100644 index 0000000..ed58797 --- /dev/null +++ b/models/cama/experiments/recurrence/05_calculadora.py @@ -0,0 +1,450 @@ +import sys +import os +import re +import json +import time +import subprocess +import warnings +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.optimize import minimize +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +warnings.filterwarnings("ignore") +try: + import mpmath as mp +except ImportError: + subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"]) + import mpmath as mp + +COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric" +HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60] +SFX = "" if COHORTE == "metabric" else f"_{COHORTE}" +DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia" +os.makedirs(DIR_FIG, exist_ok=True) +SEMILLA = 42 +B_BOOT = int(os.environ.get("N_BOOT_CALC", 200)) +MIN_EVENTOS = 15 +TOPE_MESES = 72 +BDEU_ESS = 10 +COLOR_PUNTOS, MARCA_PUNTOS = "#6a3d9a", "D" + +SUBGRUPOS = { + "metabric": { + "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]}, + "Ganglios 4+": {"Ganglios_positivos": ["4+"]}, + "Tumor >50 mm": {"Tamano_tumor": [">50 mm"]}, + "< 45 años": {"Edad": ["<45"]}, + "≥ 75 años": {"Edad": ["75+"]}, + "Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]}, + "HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]}, + "Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]}, + "RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]}, + "RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, + }, + "scanb": { + "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]}, + "Ganglios 4+": {"Ganglios_positivos": ["4+"]}, + "Tumor >50 mm": {"Tamano_tumor": [">50 mm"]}, + "< 45 años": {"Edad": ["<45"]}, + "≥ 75 años": {"Edad": ["75+"]}, + "Basal-like": {"Subtipo_clinico": ["Basal-like"]}, + "HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]}, + "Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]}, + "Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]}, + "Grado 3": {"Grado_histologico": ["3"]}, + }, +}[COHORTE] + + +# ---- ajuste parametrico (Weibull y Weibull fraccional de Kilbas-Saigo) ---- +from functools import lru_cache +from scipy.special import gammaln + +@lru_cache(maxsize=256) +def _coefs(rho, m, l, N, dps): + mp.mp.dps = dps + rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l) + c = [mp.mpf(1)] + for i in range(N - 1): + c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1))) + return tuple(c) + +def _log_terms(az, rho, m, l, N): + i = np.arange(N - 1) + logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))]) + n = np.arange(N) + with np.errstate(divide="ignore"): + lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0)) + return lt + +def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000): + z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l) + out = np.full(z.shape, np.nan) + az = np.abs(z) + N = 400 + lt = _log_terms(az, rho, m, l, N) + lmax, llast = lt.max(axis=1), lt[:, -1] + zero = az == 0 + out[zero] = 1.0 + okf = (~zero) & (lmax <= 12.0) & (llast < -40.0) + if okf.any(): + terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :] + terms[:, 0] = 1.0 + out[okf] = terms.sum(axis=1) + rest = np.where(~zero & ~okf)[0] + if rest.size: + with np.errstate(over="ignore"): + est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0) + est = np.maximum(est, lmax[rest]) + use = rest[est <= logmax_cap] + if use.size: + est_u = est[est <= logmax_cap] + dps = 30 + int(est_u.max() / 2.3) + 10 + zmax = float(az[use].max()) + with np.errstate(over="ignore"): + N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100)) + N2 = max(N2, 60) + while True: + c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps) + mp.mp.dps = dps + last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1) + if last < tol or N2 >= nmax: + break + N2 *= 2 + if last < tol: + cr = list(c)[::-1] + for j in use: + out[j] = float(mp.polyval(cr, mp.mpf(float(z[j])))) + return out + +def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None): + tau1 = lam if tau1 is None else tau1 + tau2 = lam if tau2 is None else tau2 + t = np.atleast_1d(np.asarray(t, float)) + s = k + alpha - 2 + if k + alpha <= 1 or s + beta <= 0: + return np.full_like(t, np.nan) + m = s/beta + 1; l = s/beta + pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1))) + with np.errstate(divide="ignore", invalid="ignore"): + z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1) + z = np.where(t > 0, z, 0.0) + res = np.ones_like(t) + pos = t > 0 + if pos.any(): + res[pos] = kilbas_saigo(z[pos], beta, m, l) + return np.clip(res, 0.0, 1.0) + + +def S_weibull(t, k, lam): + t = np.asarray(t, float) + return np.exp(-(t/lam)**k) + + +def tabla_eventos(meses, evento): + meses = np.asarray(meses, int); evento = np.asarray(evento, bool) + T = int(meses.max()) + 2 + d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T) + return d, c + +def _nll_from_S(Sfun, d, c): + T = len(d) + grid = np.arange(0, T + 1, dtype=float) + Sg = Sfun(grid) + mid = Sfun(np.arange(T) + 0.5) + pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None) + if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))): + return 1e12 + return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None)))) + +def ajustar_weibull(d, c): + f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c) + best = None + for k0 in (0.7, 1.0, 1.5): + for l0 in (50., 200., 1000.): + r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead", + options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000)) + if best is None or r.fun < best.fun: best = r + k, lam = np.exp(best.x) + return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2, + S=lambda t: S_weibull(t, k, lam)) + +def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120): + amin = max(0.0, 1.0 - k_fijo) + 1e-6 + def unpack(p): + return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2]) + T_max = float(len(d)) + t_fin = time.time() + max_seg + agotado = [False] + def f(p): + if time.time() > t_fin: + agotado[0] = True + return 1e12 + a, b, lam = unpack(p) + if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300: + return 1e12 + try: + return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c) + except Exception: + return 1e12 + lams = [lam_ref] if lam_ref else [] + lams += [100., 500.] + best = None + inicios = [] + if lam_ref: + inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)]) + for l0 in lams: + for a0 in (0.3, 1.0): + for b0 in (0.5, 0.9): + inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)]) + for p0 in inicios: + if time.time() > t_fin and best is not None: break + r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200)) + if best is None or r.fun < best.fun: best = r + a, b, lam = unpack(best.x) + return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3, + S=lambda t: S_ks(t, k_fijo, a, b, lam)) + + +def km_curva(meses_int, evento, T): + d, c = tabla_eventos(meses_int, evento) + L = max(len(d), T + 1) + d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c))) + nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]]) + with np.errstate(divide="ignore", invalid="ignore"): + q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0) + v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0) + S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1] + V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1] + with np.errstate(divide="ignore", invalid="ignore"): + se = np.sqrt(V) / np.abs(np.log(S)) + lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S) + hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S) + return S, lo, hi + +# ---- datos y modelos ya seleccionados en 03_modelado.py ---- +meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8")) +covariables = meta["covariables"] +modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8")) +df = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables}) +N = len(df) +meses_int = np.floor(df["tiempo_meses"].values).astype(int) +evento = (df["evento"] == 1).values +tiempo, ev_num = df["tiempo_meses"].values, df["evento"].values + +X_dum = pd.get_dummies(df[covariables], drop_first=True).astype(float) +codigos = {v: pd.factorize(df[v])[0] for v in covariables} +niveles = {v: int(codigos[v].max()) + 1 for v in covariables} + + +def ajuste_logit(y, X): + try: + return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300) + except Exception: + return None + + +def prob_lr(idx_ent, y_ent, terminos): + if not terminos: + return np.full(N, y_ent.mean()) + m = ajuste_logit(y_ent, X_dum.iloc[idx_ent][terminos]) + if m is None: + return None + return m.predict(sm.add_constant(X_dum[terminos], has_constant="add")).values + + +def clave(padres, filas): + k = np.zeros(len(filas), dtype=np.int64) + for p in padres: + k = k * niveles[p] + codigos[p][filas] + return k + + +def prob_hbn(idx_ent, y_ent, padres): + if not padres: + return np.full(N, y_ent.mean()) + q = int(np.prod([niveles[p] for p in padres])) + alpha = BDEU_ESS / (2 * q) + k_ent = clave(padres, idx_ent) + n = pd.Series(1, index=k_ent).groupby(level=0).sum() + n1 = pd.Series(y_ent, index=k_ent).groupby(level=0).sum() + tabla = (n1 + alpha) / (n + 2 * alpha) + p_glob = y_ent.mean() + return tabla.reindex(clave(padres, np.arange(N))).fillna(p_glob).values + + +def riesgos(idx, H): + t, e = tiempo[idx], ev_num[idx] + rec = (e == 1) & (t <= H) + ok = rec | (t > H) + ent = idx[ok] + y = rec[ok].astype(int) + mh = modelos[str(H)] + pl = prob_lr(ent, y, mh["terminos_lr"]) + ph = prob_hbn(ent, y, mh["padres_hbn"]) + if pl is None: + return None + return pl, ph + + +def riesgo_subgrupo(idx, masks): + out = {n: np.full(len(HORIZONTES), np.nan) for n in masks} + for j, H in enumerate(HORIZONTES): + r = riesgos(idx, H) + if r is None: + return None + comb = (r[0] + r[1]) / 2 + for n, mk in masks.items(): + sel = mk[idx] + if sel.any(): + out[n][j] = comb[idx][sel].mean() + return out + + +# ---- subgrupos y bootstrap ---- +MASCARAS = {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in SUBGRUPOS.items()} +todos = np.arange(N) +puntos = riesgo_subgrupo(todos, MASCARAS) +rng = np.random.default_rng(SEMILLA) +boots = {n: [] for n in MASCARAS} +for b in range(B_BOOT): + r = riesgo_subgrupo(rng.integers(0, N, N), MASCARAS) + if r is None: + continue + for n in MASCARAS: + boots[n].append(r[n]) + + +def graficar(nombre, mk): + sub = df[mk] + n_, ev_ = len(sub), int(sub["evento"].sum()) + if n_ == 0 or ev_ < MIN_EVENTOS: + return None + m_s, e_s = meses_int[mk], evento[mk] + d_, c_ = tabla_eventos(m_s, e_s) + w_ = ajustar_weibull(d_, c_) + ks_ = ajustar_ks(d_, c_, k_fijo=w_["k"], lam_ref=w_["lam"], max_seg=60) + Tm = int(m_s.max()) + Sk, lok, hik = km_curva(m_s, e_s, Tm) + tt = np.arange(Tm + 1) + r = 1 - puntos[nombre] + B = np.array(boots[nombre]) + ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(HORIZONTES)), np.nan) + + fig, ax = plt.subplots(figsize=(9, 5.2)) + ax.fill_between(tt, lok, hik, step="post", color="#9aa5b1", alpha=.3, lw=0) + ax.step(tt, Sk, where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)") + for ajuste, col, ls, lb in [(w_, "#1f77b4", "-", "Weibull"), (ks_, "#d1495b", "--", "Weibull fraccional")]: + t_in = np.linspace(0, Tm, 300) + t_ex = np.linspace(Tm, TOPE_MESES, 200) + ax.plot(t_in, ajuste["S"](t_in), color=col, lw=2.2, ls=ls, label=lb) + ax.plot(t_ex, ajuste["S"](t_ex), color=col, lw=1.4, ls=":") + ax.errorbar(HORIZONTES, r, yerr=[np.clip(r - ic[0], 0, None), np.clip(ic[1] - r, 0, None)], fmt=MARCA_PUNTOS, color=COLOR_PUNTOS, + ms=9, capsize=4, lw=1.8, mec="white", mew=1, label="LR + HBN combinado (IC 95 % bootstrap)", zorder=5) + x1 = TOPE_MESES + 0.8 + xs = np.linspace(0, x1, 400) + v = np.concatenate([w_["S"](xs), ks_["S"](xs), Sk[:int(min(x1, Tm)) + 1], lok[:int(min(x1, Tm)) + 1], r, ic.ravel()]) + v = v[np.isfinite(v)] + mg = (v.max() - v.min()) * .06 + ax.set_xlim(0, x1) + ax.set_ylim(max(0, v.min() - mg), min(1.005, v.max() + mg)) + ax.set_xlabel("Meses desde el diagnóstico") + ax.set_ylabel("Libre de recaída S(t)") + ax.grid(alpha=.25) + ax.set_title(f"{nombre}\n{'SCAN-B' if COHORTE == 'scanb' else 'METABRIC'} · n={n_:,}, recaídas={ev_:,}", fontsize=11) + ax.legend(frameon=False, loc="lower left", fontsize=9) + for sp in ("top", "right"): + ax.spines[sp].set_visible(False) + fig.tight_layout() + arch = re.sub(r"[^A-Za-z0-9]+", "_", nombre.replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt") + .replace("−", "neg").replace("+", "pos").replace("ñ", "n").replace("á", "a").replace("í", "i").replace("é", "e")).strip("_") + fig.savefig(f"{DIR_FIG}/subgrupo_{COHORTE}_{arch}.png", dpi=170) + plt.close(fig) + filas = [] + for j, H in enumerate(HORIZONTES): + filas.append({"cohorte": COHORTE, "subgrupo": nombre, "n": n_, "recaidas": ev_, "horizonte_meses": H, + "S_libre_LR_HBN": r[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - r[j], + "S_libre_KM": Sk[min(H, Tm)] if H <= Tm else np.nan, "replicas_bootstrap": len(B)}) + return filas + + +filas = [] +for nombre, mk in MASCARAS.items(): + f = graficar(nombre, mk) + if f: + filas += f + +nuevo = pd.DataFrame(filas) +destino = "./calculadora_recurrencia_subgrupos.csv" +if os.path.exists(destino): + previo = pd.read_csv(destino) + nuevo = pd.concat([previo[previo["cohorte"] != COHORTE], nuevo], ignore_index=True) +nuevo.round(4).to_csv(destino, index=False) + + +# ---- escenarios clinicos: factores de riesgo que incluye cada subgrupo ---- +PCT_DEFINITORIA = 0.95 +PCT_MAYORITARIA = 0.50 +PCT_PRESENTE = 0.10 + + +def nivel_presencia(p): + if p >= PCT_DEFINITORIA: + return "definitoria" + if p >= PCT_MAYORITARIA: + return "mayoritaria" + return "presente" if p >= PCT_PRESENTE else "minoritaria" + + +def definicion(cond): + return "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items()) + + +if os.path.exists("./factores_riesgo_recurrencia.csv"): + fr = pd.read_csv("./factores_riesgo_recurrencia.csv", dtype={"categoria": str}) + fr = fr[(fr["cohorte"] == COHORTE) & fr["horizonte_meses"].isin(HORIZONTES)] + fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy() + fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0]) + filas_esc, filas_res = [], [] + for nombre, mk in MASCARAS.items(): + n_sub = int(mk.sum()) + if n_sub == 0: + continue + cond = SUBGRUPOS[nombre] + pct = {} + for v, c in set(zip(fr["variable"], fr["categoria"])): + pct[(v, c)] = (float((df.loc[mk, v] == c).mean()), float((df[v] == c).mean())) + det = fr.copy() + det["pct_en_escenario"] = [pct[(v, c)][0] for v, c in zip(det["variable"], det["categoria"])] + det["pct_en_cohorte"] = [pct[(v, c)][1] for v, c in zip(det["variable"], det["categoria"])] + det["presencia"] = det["pct_en_escenario"].map(nivel_presencia) + det["en_definicion"] = [c in cond.get(v, []) for v, c in zip(det["variable"], det["categoria"])] + det.insert(0, "escenario", nombre) + det.insert(1, "definicion", definicion(cond)) + det.insert(2, "n_escenario", n_sub) + columnas = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria", + "clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte", + "presencia", "en_definicion"] + filas_esc.append(det[det["pct_en_escenario"] >= PCT_PRESENTE][columnas]) + for H in HORIZONTES: + d = det[det["horizonte_meses"] == H] + fila = {"cohorte": COHORTE, "escenario": nombre, "definicion": definicion(cond), "n_escenario": n_sub, "horizonte_meses": H} + for tipo in ("riesgo", "protector", "tratamiento"): + for nivel, etiqueta in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")): + s_ = d[(d["tipo_efecto"] == tipo) & (d["presencia"] == nivel)] + fila[f"{tipo}_{etiqueta}"] = "; ".join( + f"{v}={c} ({k.split()[-1] if tipo != 'tratamiento' else 'asociacion'}, {p:.0%})" + for v, c, k, p in zip(s_["variable"], s_["categoria"], s_["clasificacion"], s_["pct_en_escenario"])) + fila["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum()) + fila["incluye_factor_riesgo"] = fila["n_factores_riesgo_incluidos"] > 0 + filas_res.append(fila) + for archivo, filas_x in (("./escenarios_factores_riesgo_recurrencia.csv", pd.concat(filas_esc, ignore_index=True)), + ("./escenarios_resumen_recurrencia.csv", pd.DataFrame(filas_res))): + if os.path.exists(archivo): + previo = pd.read_csv(archivo) + filas_x = pd.concat([previo[previo["cohorte"] != COHORTE], filas_x], ignore_index=True) + filas_x.round(4).to_csv(archivo, index=False) diff --git a/models/cama/experiments/recurrence/ejecutar_recurrencia.py b/models/cama/experiments/recurrence/ejecutar_recurrencia.py new file mode 100644 index 0000000..5320dc9 --- /dev/null +++ b/models/cama/experiments/recurrence/ejecutar_recurrencia.py @@ -0,0 +1,33 @@ +import argparse +import csv +import subprocess +import sys +import time + + +ap = argparse.ArgumentParser() +ap.add_argument("--cohorte", choices=["metabric", "scanb"]) +ap.add_argument("--horizontes", nargs="+", default=["12", "36", "60"]) +a = ap.parse_args() +cohortes = [a.cohorte] if a.cohorte else ["metabric", "scanb"] +prep = {"metabric": "01_preparacion_metabric.py", "scanb": "02_preparacion_scanb.py"} + +pasos = [] +for c in cohortes: + pasos.append((f"preparacion_{c}", [prep[c]])) + pasos.append((f"03_modelado_{c}", ["03_modelado.py", c] + a.horizontes)) + pasos.append((f"04_factores_riesgo_{c}", ["04_factores_riesgo.py", c] + a.horizontes)) + pasos.append((f"05_calculadora_{c}", ["05_calculadora.py", c] + a.horizontes)) + +bit = [] +for nombre, cmd in pasos: + t0 = time.time() + r = subprocess.run([sys.executable, "-W", "ignore"] + cmd, capture_output=True, text=True) + bit.append([nombre, "ok" if r.returncode == 0 else "ERROR", round(time.time() - t0, 1)]) + with open("bitacora_recurrencia.csv", "w", newline="", encoding="utf8") as f: + w = csv.writer(f) + w.writerow(["paso", "estado", "segundos"]) + w.writerows(bit) + if r.returncode != 0: + sys.stderr.write(f"\n[{nombre}] fallo:\n{r.stderr[-3000:]}\n") + sys.exit(1) diff --git a/models/cama/recurrence/analysis.py b/models/cama/recurrence/analysis.py new file mode 100644 index 0000000..74783e5 --- /dev/null +++ b/models/cama/recurrence/analysis.py @@ -0,0 +1,243 @@ +"""Luis's recurrence analysis of one cohort over its frame (`cohort.recode`): the covariates that survive the +collinearity pruning, the logistic regression and the Bayesian network's outcome parents of each horizon, and the figure +of each clinical scenario (Kaplan-Meier with its Greenwood band, the Weibull and the fractional Weibull, and the +combined estimate at each horizon with its bootstrap interval). + +Every number a stage uses is the model's (`modeling`, `calculator` of `model.toml`). +""" + +import warnings + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from pgmpy.estimators import BDeu +from scipy.stats import chi2_contingency +from sklearn.model_selection import train_test_split + +from models.cama.seer_survival.fractional_weibull import ajustar_ks, ajustar_weibull, km_curva, tabla_eventos + +warnings.filterwarnings("ignore") + + +def cramer_v(a: pd.Series, b: pd.Series) -> float: + table = pd.crosstab(a, b) + chi2 = chi2_contingency(table, correction=False)[0] + k = min(table.shape) - 1 + return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0 + + +def prune_covariates(frame: pd.DataFrame, covariates: list[str], treatment: list[str], settings: dict) -> tuple[list, list]: + """Of each pair of non-treatment covariates with Cramér's V at or above the limit, the one with more unknowns goes.""" + unknown = settings["unknown_label"] + kept, dropped = list(covariates), [] + candidates = [c for c in covariates if c not in treatment] + pairs = sorted(((cramer_v(frame[a], frame[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]), + reverse=True) + for v, a, b in pairs: + if v < settings["cramer_v_max"]: + break + if a in dropped or b in dropped: + continue + out = a if (frame[a] == unknown).mean() >= (frame[b] == unknown).mean() else b + dropped.append(out) + kept.remove(out) + return kept, dropped + + +def horizon_cohort(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: + """The patients who recurred by the horizon or are free beyond it; the rest were censored before it and are left out.""" + recurred = (frame["evento"] == 1) & (frame["tiempo_meses"] <= horizon) + free = frame["tiempo_meses"] > horizon + out = frame[recurred | free].reset_index(drop=True) + out["y"] = ((out["evento"] == 1) & (out["tiempo_meses"] <= horizon)).astype(int) + return out + + +def _encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: + X = pd.get_dummies(frame[covariates], drop_first=True).astype(float) + return X.loc[:, X.nunique() > 1] + + +def _logit(y, X): + try: + return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300) + except Exception: + return None + + +def _prefilter(X: pd.DataFrame, y, alpha: float) -> list[str]: + keep = [] + for c in X.columns: + fit = _logit(y, X[[c]]) + if fit is not None and fit.pvalues[c] < alpha: + keep.append(c) + return keep + + +def _stepwise(X: pd.DataFrame, y, alpha_in: float, alpha_out: float) -> list[str]: + chosen: list[str] = [] + for _ in range(200): + changed = False + best, best_p = None, alpha_in + for c in [c for c in X.columns if c not in chosen]: + fit = _logit(y, X[chosen + [c]]) + if fit is not None and fit.pvalues[c] < best_p: + best, best_p = c, fit.pvalues[c] + if best is not None: + chosen.append(best) + changed = True + if chosen: + fit = _logit(y, X[chosen]) + if fit is not None: + p = fit.pvalues.drop("const") + if p.max() > alpha_out: + chosen.remove(p.idxmax()) + changed = True + if not changed: + break + return chosen + + +def logistic_terms(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]: + both = _encode(pd.concat([train, test]), covariates) + X = both.loc[train.index] + X = X.loc[:, X.nunique() > 1] + candidates = _prefilter(X, train["y"], settings["alpha_prefilter"]) + return _stepwise(X[candidates], train["y"], settings["alpha_in"], settings["alpha_out"]) if candidates else [] + + +def outcome_parents(frame: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]: + """The outcome's parents by greedy BDeu, at most `max_parents`.""" + table = frame[covariates].astype(str).copy() + table["outcome"] = frame["y"].astype(int).astype(str) + score = BDeu(table, equivalent_sample_size=settings["bdeu_ess"]) + parents, current = [], score.local_score("outcome", []) + while len(parents) < settings["max_parents"]: + best, gain = None, 0 + for c in covariates: + if c in parents: + continue + g = score.local_score("outcome", parents + [c]) - current + if g > gain: + best, gain = c, g + if best is None: + break + parents.append(best) + current += gain + return parents + + +def select_models(frame: pd.DataFrame, covariates: list[str], horizons: list[int], settings: dict) -> dict: + """The logistic terms and the Bayesian network's outcome parents of each horizon, selected on the 70/30 split.""" + models = {} + for horizon in horizons: + cohort = horizon_cohort(frame, horizon) + train_idx, test_idx = train_test_split(cohort.index, test_size=settings["test_share"], random_state=settings["seed"], + stratify=cohort["y"]) + train, test = cohort.loc[train_idx], cohort.loc[test_idx] + models[horizon] = {"lr_terms": logistic_terms(train, test, covariates, settings), + "hbn_parents": outcome_parents(train, covariates, settings)} + return models + + +class Calculator: + """The combined estimate (mean of the logistic regression and the Bayesian network) of a group of patients, refitting + both on any resample of the cohort with the terms and parents selected for each horizon.""" + + def __init__(self, frame: pd.DataFrame, covariates: list[str], models: dict, horizons: list[int], ess: int): + self.frame, self.horizons, self.models, self.ess = frame, horizons, models, ess + self.n = len(frame) + self.time = frame["tiempo_meses"].to_numpy() + self.event = frame["evento"].to_numpy() + self.dummies = pd.get_dummies(frame[covariates], drop_first=True).astype(float) + self.codes = {v: pd.factorize(frame[v])[0] for v in covariates} + self.levels = {v: int(self.codes[v].max()) + 1 for v in covariates} + + def _lr(self, rows, y, terms): + if not terms: + return np.full(self.n, y.mean()) + fit = _logit(y, self.dummies.iloc[rows][terms]) + if fit is None: + return None + return fit.predict(sm.add_constant(self.dummies[terms], has_constant="add")).to_numpy() + + def _key(self, parents, rows): + key = np.zeros(len(rows), dtype=np.int64) + for p in parents: + key = key * self.levels[p] + self.codes[p][rows] + return key + + def _hbn(self, rows, y, parents): + if not parents: + return np.full(self.n, y.mean()) + q = int(np.prod([self.levels[p] for p in parents])) + alpha = self.ess / (2 * q) + key = self._key(parents, rows) + n = pd.Series(1, index=key).groupby(level=0).sum() + n1 = pd.Series(y, index=key).groupby(level=0).sum() + table = (n1 + alpha) / (n + 2 * alpha) + return table.reindex(self._key(parents, np.arange(self.n))).fillna(y.mean()).to_numpy() + + def risk(self, rows: np.ndarray, masks: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None: + """For each group, its members' mean combined risk at every horizon, fitted on `rows` (a resample or all).""" + out = {name: np.full(len(self.horizons), np.nan) for name in masks} + for j, horizon in enumerate(self.horizons): + t, e = self.time[rows], self.event[rows] + recurred = (e == 1) & (t <= horizon) + fit_rows = rows[recurred | (t > horizon)] + y = recurred[recurred | (t > horizon)].astype(int) + model = self.models[horizon] + lr = self._lr(fit_rows, y, model["lr_terms"]) + if lr is None: + return None + combined = (lr + self._hbn(fit_rows, y, model["hbn_parents"])) / 2 + for name, mask in masks.items(): + chosen = mask[rows] + if chosen.any(): + out[name][j] = combined[rows][chosen].mean() + return out + + def bootstrap(self, masks: dict[str, np.ndarray], replicas: int, seed: int) -> dict[str, list]: + rng = np.random.default_rng(seed) + draws = {name: [] for name in masks} + for _ in range(replicas): + risk = self.risk(rng.integers(0, self.n, self.n), masks) + if risk is None: + continue + for name in masks: + draws[name].append(risk[name]) + return draws + + +def scenario_masks(frame: pd.DataFrame, scenarios: list[dict]) -> dict[str, np.ndarray]: + return {s["name"]: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in s["when"].items()]) for s in scenarios} + + +def scenario_figure(frame: pd.DataFrame, name: str, mask: np.ndarray, point: np.ndarray, draws: list, + horizons: list[int], settings: dict) -> dict | None: + """The figure record of a scenario, or None when it has fewer recurrences than the calculator draws.""" + members = frame[mask] + events = int(members["evento"].sum()) + if len(members) == 0 or events < settings["min_events"]: + return None + months = np.floor(members["tiempo_meses"].to_numpy()).astype(int) + event = (members["evento"] == 1).to_numpy() + d, c = tabla_eventos(months, event) + weibull = ajustar_weibull(d, c) + fractional = ajustar_ks(d, c, k_fijo=weibull["k"], lam_ref=weibull["lam"], max_seg=settings["fractional_weibull_budget_s"]) + last = int(months.max()) + survival, low, high = km_curva(months, event, last) + t = np.arange(0, settings["cap_months"] * 4 + 1) / 4 + free = 1 - point + boot = np.array(draws) + interval = 1 - np.nanpercentile(boot, [97.5, 2.5], axis=0) if len(boot) else np.full((2, len(horizons)), np.nan) + clean = lambda a: [None if not np.isfinite(x) else float(x) for x in a] + return { + "escenario": name, "n": int(len(members)), "recaidas": events, "observado_hasta": last, + "months_max": settings["cap_months"], "horizons_months": horizons, "bootstrap_replicas": len(boot), + "km": {"months": list(range(last + 1)), "S": clean(survival), "low": clean(low), "high": clean(high)}, + "weibull": {"t": t.tolist(), "S": clean(weibull["S"](t))}, + "weibull_fractional": {"t": t.tolist(), "S": clean(fractional["S"](t))}, + "points": {"COMB": {"S": clean(free), "low": clean(interval[0]), "high": clean(interval[1])}}, + } diff --git a/models/cama/recurrence/cohort.py b/models/cama/recurrence/cohort.py new file mode 100644 index 0000000..e01e360 --- /dev/null +++ b/models/cama/recurrence/cohort.py @@ -0,0 +1,83 @@ +"""One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence +event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `cohorts.toml`). + +The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from +it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to +`window_days_after_index` after the index; a category no rule gives is the variable's `missing` one. +""" + +import tomllib +from pathlib import Path + +import pandas as pd + +from models.cama.seer_survival.variables import Reader, category_of + +TOML = Path(__file__).with_name("cohorts.toml") +SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"} + + +def load(path: Path = TOML) -> dict: + return tomllib.loads(Path(path).read_text(encoding="utf-8")) + + +def _spec(dictionary: dict, name: str, cohort: str) -> dict: + spec = dictionary[name] + own = spec.get(cohort, {}) + return {**spec, "rules": own["rules"]} if "rules" in own else spec + + +def _cut(values: pd.Series, cuts: list, labels: list, missing: str) -> pd.Series: + cut = pd.cut(values, cuts, labels=labels, right=False) + return cut.astype("object").where(cut.notna(), missing).astype(str) + + +def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool = True, follow_up: bool = True) -> pd.DataFrame: + """One row per patient. `of_source` keeps only the patients whose record comes from this cohort's source (a patient of + another source is read with the same variables when it is false); `follow_up` drops those with no recurrence or + last contact, whose time is unknown.""" + dictionary = model["variables"] + index = dictionary["index"] + events = events.copy() + events["fecha"] = pd.to_datetime(events["fecha"]) + events["fecha_indice"] = pd.to_datetime(events["fecha_indice"]) + + if of_source: + source = events[events["tipo"] == "fuente"].groupby("pac_id")["valor_codigo"].last() + patients = pd.Index(sorted(source[source == SOURCE_CODE[cohort]].index), name="pac_id") + else: + patients = pd.Index(sorted(events["pac_id"].unique()), name="pac_id") + events = events[events["pac_id"].isin(patients)] + start = events.groupby("pac_id")["fecha_indice"].first().reindex(patients) + recurrence = events[events["tipo"] == index["recurrence_source"]].groupby("pac_id")["fecha"].min().reindex(patients) + contact = events[events["tipo"] == index["last_contact_source"]].groupby("pac_id")["fecha"].max().reindex(patients) + end = recurrence.fillna(contact) + birth = events[events["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients) + + window = pd.Timedelta(days=int(dictionary["window_days_after_index"])) + visible = events[events["fecha"] <= events["pac_id"].map(start) + window] + reader = Reader(visible, patients, {}) + + result = pd.DataFrame(index=patients) + result["paciente"] = patients.to_numpy() + result["tiempo_meses"] = ((end - start).dt.days / index["days_per_month"]).to_numpy() + result["evento"] = recurrence.notna().astype(int).to_numpy() + unknown = dictionary["Edad"]["missing"] + for name in model["cohorts"][cohort]["covariates"]: + spec = _spec(dictionary, name, cohort) + if name == "Edad": + age = (start - birth).dt.days / 365.25 + result[name] = _cut(age, spec["cuts"], spec["labels"], unknown).to_numpy() + elif "rules" in spec: + category = category_of(spec, reader) + labels = spec.get(cohort, {}).get("labels", {}) + result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy() + elif spec.get("terciles"): + count = reader.value(spec["source"], True) + q = count.quantile([1 / 3, 2 / 3]).to_numpy() + result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy() + else: + result[name] = _cut(reader.value(spec["source"], True), spec["cuts"], spec["labels"], spec["missing"]).to_numpy() + keep = start.notna().to_numpy() & (end.notna().to_numpy() if follow_up else True) + result = result[keep] + return result.reset_index(drop=True) diff --git a/models/cama/recurrence/cohort_import.py b/models/cama/recurrence/cohort_import.py new file mode 100644 index 0000000..3476150 --- /dev/null +++ b/models/cama/recurrence/cohort_import.py @@ -0,0 +1,158 @@ +"""METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import +schemas take, to be uploaded through the platform's import like any other source. + + python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR + +What goes where is the dictionary's (`[variables.*]` of `cohorts.toml`): each source category is stored as the catalog value +the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day +of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the +follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps +the month it falls in and its side of every horizon. +""" + +import argparse +import math +import tomllib +from pathlib import Path + +import numpy as np +import pandas as pd + +TOML = Path(__file__).with_name("cohorts.toml") +ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "NotaMedica": "notas", "TratamientoMama": "tratamientos", + "SeguimientoMama": "seguimientos"} +FEMALE = "Femenino" +UNKNOWN = {"", "NA", "nan", "NaN", "None"} + + +def load(path: Path = TOML) -> dict: + return tomllib.loads(Path(path).read_text(encoding="utf-8")) + + +def follow_up_days(months: float, horizons: list[int], days_per_month: float) -> int: + """The whole days nearest to `months` that keep floor(months) and, for each horizon, whether the follow-up is within it.""" + exact = months * days_per_month + month = math.floor(months) + low = math.ceil(month * days_per_month) + high = math.ceil((month + 1) * days_per_month) - 1 + sides = [months <= h for h in horizons] + first = int(round(exact)) + for step in range(0, high - low + 2): + for day in (first - step, first + step): + if low <= day <= high and math.floor(day / days_per_month) == month \ + and [day / days_per_month <= h for h in horizons] == sides: + return day + return first + + +def _known(raw: pd.Series) -> pd.Series: + return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN) + + +def convert(raw: pd.DataFrame, cohort: str, model: dict) -> dict[str, pd.DataFrame]: + dictionary = model["variables"] + index = dictionary["index"] + cfg = dictionary["cohorts"][cohort] + covariates = model["cohorts"][cohort]["covariates"] + horizons = model["config"]["horizons_months"] + dpm = index["days_per_month"] + + frame = raw + if cfg["sex_filter"]: + frame = frame[frame[cfg["sex_filter"]["column"]] == cfg["sex_filter"]["value"]] + frame = frame[_known(frame[cfg["months"]]) & _known(frame[cfg["event"]])].copy() + + if cohort == "scanb": + days = pd.to_numeric(frame[cfg["months"]]).round().astype(int) + event = pd.to_numeric(frame[cfg["event"]]).astype(int) + else: + months = pd.to_numeric(frame[cfg["months"]]) + days = pd.Series([follow_up_days(m, horizons, dpm) for m in months], index=frame.index) + event = frame[cfg["event"]].astype(str).str.startswith(cfg["event_prefix"]).astype(int) + + age = pd.to_numeric(frame[cfg["diagnosis_age"]], errors="coerce") + cfg.get("diagnosis_age_offset", 0) + frame, days, event, age = (x[age.notna()] for x in (frame, days, event, age)) + if "diagnosis_year_column" in cfg: + year = pd.to_numeric(frame[cfg["diagnosis_year_column"]], errors="coerce").fillna(2000).astype(int) + else: + year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index) + diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"]) + birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D") + end = diagnosis + pd.to_timedelta(days, unit="D") + ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str) + date = lambda s: s.dt.strftime("%Y-%m-%d") + + tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES} + tables["Paciente"]["pac_sexo"] = FEMALE + tables["Paciente"]["pac_fecha_nacimiento"] = date(birth) + tables["Paciente"]["pac_fuente"] = "SCANB" if cohort == "scanb" else "METABRIC" + tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis) + tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis) + + treatments = [] + for name in covariates: + spec = dictionary[name] + source = spec.get(cohort) + if not source or "column" not in source: + continue + column = frame[source["column"]] + known = _known(column) + if "treatment" in spec: + code = column.astype(str).map(source["values"]) + code = code.where(~known | code.notna(), source.get("absent")).where(known) + rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": spec["treatment"], "trat_fecha": date(diagnosis), + "trat_detalle": code})[code.notna()] + if spec["treatment"] == "cirugia": + rows["trat_lateralidad"] = None + treatments.append(rows) + continue + if "bronze" not in spec: + continue + entity, target = spec["bronze"].split(".") + if "number_values" in source: + value = column.astype(str).map(source["number_values"]) + elif "values" in source: + value = column.astype(str).map(source["values"]) + else: + value = pd.to_numeric(column.where(known), errors="coerce") + tables[entity][target] = value.where(known) + + tables["BiopsiaMama"]["bx_grado_histologico"] = "CARCINOMA_INVASOR" + if "Cirugia" in covariates and "bx_lateralidad" in tables["BiopsiaMama"]: + for rows in treatments: + if (rows["trat_tipo"] == "cirugia").any(): + rows["trat_lateralidad"] = tables["BiopsiaMama"]["bx_lateralidad"].reindex(rows.index) + tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True) + + notes = tables["NotaMedica"] + notes["nm_id_hospital"] = ident + "-dx" + notes["nm_fecha"] = date(diagnosis) + notes["nm_tipo_nota"] = "CONSULTA" + follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(end), + "nm_tipo_nota": "EGRESO"}) + tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True) + + recurred = event.eq(1) + contact = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["last_contact_source"], "seg_fecha": date(end), + "seg_detalle": "VIVA"})[~recurred] + recurrence = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["recurrence_source"], "seg_fecha": date(end), + "seg_detalle": "NO_ESPECIFICADO"})[recurred] + tables["SeguimientoMama"] = pd.concat([recurrence, contact], ignore_index=True) + return tables + + +def main(argv=None) -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("cohort", choices=["metabric", "scanb"]) + ap.add_argument("file") + ap.add_argument("out_dir") + args = ap.parse_args(argv) + raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False) + out = Path(args.out_dir) + out.mkdir(parents=True, exist_ok=True) + for entity, table in convert(raw, args.cohort, load()).items(): + table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False) + + +if __name__ == "__main__": + main() diff --git a/models/cama/recurrence/cohorts.toml b/models/cama/recurrence/cohorts.toml new file mode 100644 index 0000000..5e9ae35 --- /dev/null +++ b/models/cama/recurrence/cohorts.toml @@ -0,0 +1,402 @@ +# CaMa recurrence: the METABRIC and SCAN-B analyses of Luis as one scenario. Each cohort has its own covariates, categories and +# clinical scenarios, as in his scripts; the cohorts are not pooled. +domain = "cama" +scenario = "recurrence" +cohort = "cama/cohorte_total" +requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "mpmath"] +settings_tables = ["modeling", "calculator", "variables"] +description = """ +Recurrencia del cáncer de mama a 12, 36 y 60 meses desde el diagnóstico: regresión logística y red bayesiana, combinadas, \ +sobre las variables de las cohortes METABRIC y SCAN-B; una figura por escenario clínico.""" + +[config] +horizons_months = [12, 36, 60] + +# ---- settings of the stages (Luis's scripts 03, 04 and 05) ---- +[modeling] +seed = 42 +unknown_label = "Desconocido" +cramer_v_max = 0.80 # of a pair of non-treatment covariates with V >= this, the one with more unknowns is dropped +alpha_prefilter = 0.10 # univariate prefilter of the logistic regression +alpha_in = 0.10 # stepwise: p to enter +alpha_out = 0.15 # stepwise: p to leave +bdeu_ess = 10 +max_parents = 6 +test_share = 0.30 # the 70/30 split of the AUC + +[calculator] +min_events = 15 # a scenario is drawn only with at least this many recurrences +bootstrap_replicas = 200 +cap_months = 72 # the curves are drawn dotted past the follow-up up to here +fractional_weibull_budget_s = 60 + +# ---- the variable dictionary ---- +# `rules` read the timeline (`source` = the study of the catalog, `codes` its values; `ge`/`lt` bound a number) and give +# the category; `missing` is the category when no rule holds (the unknown is one more category, never imputed). +# `.column` is the source file's column; `.values` maps its values to the codes the loader sends; +# `.labels` renames the rules' category where the source names it differently (neutral label = source label); +# `[variables.X.]` replaces the rules for a variable whose categories differ between the cohorts. +[variables] +window_days_after_index = 365 + +[variables.index] +id_column = "paciente" +months_column = "tiempo_meses" +event_column = "evento" +death_source = "defuncion" +birth_source = "nacimiento" +recurrence_source = "recurrencia" +last_contact_source = "ultimo_contacto" +days_per_month = 30.4375 + +[variables.cohorts.metabric] +file = "brca_metabric_clinical_data.tsv" +id = "Patient ID" +months = "Relapse Free Status (Months)" +event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped +event_prefix = "1" +diagnosis_age = "Age at Diagnosis" # years +sex_filter = {} +diagnosis_month_day = "07-01" +diagnosis_year = 2000 # METABRIC records no year: a fixed one, the follow-up runs from it +# Per covariate, the source columns and category cuts as the preparation script defines them. + +[variables.cohorts.scanb] +file = "scanb_clinical_metadata.txt" +id = "PatientName" +months = "RFI_days" # days, divided by days_per_month +months_divisor = 30.4375 +event = "RFI_event" +sex_filter = { column = "Gender", value = "F" } +diagnosis_age = "Age_5year_bin" # the bin's lower edge; the age is that value minus 2, as in the script +diagnosis_age_offset = -2 +diagnosis_month_day = "07-01" +diagnosis_year_column = "dxYear" + +# Cuts shared by both cohorts (pd.cut with the right edge open). +[variables.Edad] +cuts = [0, 45, 60, 75, 200] +labels = ["<45", "45-59", "60-74", "75+"] +missing = "Desconocido" + +[variables.Tamano_tumor] +bronze = "BiopsiaMama.bx_tamano_tumor_mm" +source = "tamano_tumor_mm" +cuts = [0, 20.01, 50.01, 10000] +labels = ["<=20 mm", "21-50 mm", ">50 mm"] +missing = "Desconocido" +metabric = { column = "Tumor Size" } +scanb = { column = "TumorSize_mm" } + +[variables.Ganglios_positivos] +bronze = "BiopsiaMama.bx_ganglios_positivos" +source = "ganglios_positivos" +cuts = [0, 1, 4, 1000] +labels = ["0", "1-3", "4+"] +missing = "Desconocido" +metabric = { column = "Lymph nodes examined positive" } +scanb = { column = "NodeMetSpec", number_values = { "NodeNegative" = 0, "SubMicroMet" = 0, "1to3" = 2, "4toX" = 6 } } + +[variables.Grado_histologico] +bronze = "BiopsiaMama.bx_grado_nottingham" +rules = [ + { source = "grado_nottingham", codes = ["G1"], then = "1" }, + { source = "grado_nottingham", codes = ["G2"], then = "2" }, + { source = "grado_nottingham", codes = ["G3"], then = "3" }, +] +missing = "Desconocido" +metabric = { column = "Neoplasm Histologic Grade", values = { "1.0" = "G1", "2.0" = "G2", "3.0" = "G3" } } +scanb = { column = "NHG", values = { "Grade1" = "G1", "Grade2" = "G2", "Grade3" = "G3" } } + +[variables.Receptor_estrogeno] +bronze = "BiopsiaMama.bx_receptor_estrogeno" +rules = [ + { source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positive" }, + { source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negative" }, +] +missing = "Desconocido" +metabric = { column = "ER Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } } +scanb = { column = "ER", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } } + +[variables.Receptor_progesterona] +bronze = "BiopsiaMama.bx_receptor_progesterona" +rules = [ + { source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positive" }, + { source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negative" }, +] +missing = "Desconocido" +metabric = { column = "PR Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } } +scanb = { column = "PR", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } } + +[variables.HER2] +bronze = "BiopsiaMama.bx_her2_fish" +rules = [ + { source = "her2_fish", codes = ["POSITIVO"], then = "Positive" }, + { source = "her2_fish", codes = ["NEGATIVO"], then = "Negative" }, + { source = "her2", codes = ["H3"], then = "Positive" }, + { source = "her2", codes = ["H0", "H1"], then = "Negative" }, +] +missing = "Desconocido" +metabric = { column = "HER2 Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" } +scanb = { column = "HER2", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" } + +[variables.Tipo_histologico] +bronze = "BiopsiaMama.bx_tipo_histologico" +rules = [ + { source = "tipo_histologico", codes = ["8500/3"], then = "Breast Invasive Ductal Carcinoma" }, + { source = "tipo_histologico", codes = ["8522/3"], then = "Breast Mixed Ductal and Lobular Carcinoma" }, + { source = "tipo_histologico", codes = ["8520/3"], then = "Breast Invasive Lobular Carcinoma" }, + { source = "tipo_histologico", codes = ["8010/3"], then = "Invasive Breast Carcinoma" }, + { source = "tipo_histologico", codes = ["8480/3"], then = "Breast Invasive Mixed Mucinous Carcinoma" }, + { source = "tipo_histologico", codes = ["8000/3"], then = "Breast" }, + { source = "tipo_histologico", codes = ["9120/3"], then = "Breast Angiosarcoma" }, + { source = "tipo_histologico", codes = ["8575/3"], then = "Metaplastic Breast Cancer" }, +] +missing = "Desconocido" +metabric = { column = "Cancer Type Detailed", values = { "Breast Invasive Ductal Carcinoma" = "8500/3", "Breast Mixed Ductal and Lobular Carcinoma" = "8522/3", "Breast Invasive Lobular Carcinoma" = "8520/3", "Invasive Breast Carcinoma" = "8010/3", "Breast Invasive Mixed Mucinous Carcinoma" = "8480/3", "Breast" = "8000/3", "Breast Angiosarcoma" = "9120/3", "Metaplastic Breast Cancer" = "8575/3" } } + +[variables.Tipo_histologico.scanb] +rules = [ + { source = "tipo_histologico", codes = ["8500/3"], then = "Ductal" }, + { source = "tipo_histologico", codes = ["8520/3"], then = "Lobular" }, + { source = "tipo_histologico", codes = ["8522/3"], then = "Ductal-Lobular" }, + { source = "tipo_histologico", codes = ["8523/3"], then = "Ductal-Other" }, + { source = "tipo_histologico", codes = ["8010/3"], then = "Other" }, +] +column = "Histology" +values = { "Ductal" = "8500/3", "Lobular" = "8520/3", "Ductal-Lobular" = "8522/3", "Ductal-Other" = "8523/3", "Other" = "8010/3" } + +[variables.Estado_menopausico] +bronze = "Paciente.pac_estado_menopausico" +rules = [ + { source = "estado_menopausico", codes = ["POSMENOPAUSIA"], then = "Post" }, + { source = "estado_menopausico", codes = ["PREMENOPAUSIA"], then = "Pre" }, +] +missing = "Desconocido" +metabric = { column = "Inferred Menopausal State", values = { "Post" = "POSMENOPAUSIA", "Pre" = "PREMENOPAUSIA" } } +scanb = { column = "MenopauseStatus_bin", values = { "Postmenopausal" = "POSMENOPAUSIA", "Premenopausal" = "PREMENOPAUSIA" }, labels = { "Post" = "Postmenopausal", "Pre" = "Premenopausal" } } + +[variables.Lateralidad] +bronze = "BiopsiaMama.bx_lateralidad" +rules = [ + { source = "lateralidad", codes = ["IZQUIERDA"], then = "Left" }, + { source = "lateralidad", codes = ["DERECHA"], then = "Right" }, +] +missing = "Desconocido" +metabric = { column = "Primary Tumor Laterality", values = { "Left" = "IZQUIERDA", "Right" = "DERECHA" } } +scanb = { column = "Laterality", values = { "LEFT" = "IZQUIERDA", "RIGHT" = "DERECHA" }, labels = { "Left" = "LEFT", "Right" = "RIGHT" } } + +# Treatments. The category is the source's own, as the scenarios of each cohort name them. +[variables.Cirugia] +treatment = "cirugia" +rules = [ + { source = "cirugia", codes = ["MASTECTOMIA_TOTAL"], then = "MASTECTOMY" }, + { source = "cirugia", codes = ["SEGMENTECTOMIA"], then = "BREAST CONSERVING" }, +] +missing = "Desconocido" +metabric = { column = "Type of Breast Surgery", values = { "MASTECTOMY" = "MASTECTOMIA_TOTAL", "BREAST CONSERVING" = "SEGMENTECTOMIA" } } +scanb = { column = "SurgeryType", values = { "Mastectomy" = "MASTECTOMIA_TOTAL", "Lumpectomy" = "SEGMENTECTOMIA" }, labels = { "MASTECTOMY" = "Mastectomy", "BREAST CONSERVING" = "Lumpectomy" } } + +[variables.Quimioterapia] +treatment = "quimioterapia" +rules = [ + { source = "quimioterapia", codes = ["ADYUVANTE"], then = "YES" }, + { source = "quimioterapia", codes = ["NINGUNA"], then = "NO" }, +] +missing = "Desconocido" +metabric = { column = "Chemotherapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" } +scanb = { column = "Chemotherapy", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } } + +[variables.Radioterapia] +treatment = "radioterapia" +rules = [ + { source = "radioterapia", codes = ["ADYUVANTE"], then = "YES" }, + { source = "radioterapia", codes = ["NINGUNA"], then = "NO" }, +] +missing = "Desconocido" +metabric = { column = "Radio Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" } +scanb = { column = "Radiation", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } } + +[variables.Hormonoterapia] +treatment = "hormonoterapia" +rules = [ + { source = "hormonoterapia", codes = ["ADYUVANTE"], then = "YES" }, + { source = "hormonoterapia", codes = ["NINGUNA"], then = "NO" }, +] +missing = "Desconocido" +metabric = { column = "Hormone Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" } +scanb = { column = "Endocrine", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } } + +# ---- METABRIC only ---- +[variables.Carga_mutacional] +bronze = "Paciente.pac_carga_mutacional" +source = "carga_mutacional" +terciles = true # the cohort's own terciles of the mutation count +labels = ["baja", "media", "alta"] +missing = "Desconocido" +metabric = { column = "Mutation Count" } + +[variables.Subtipo_PAM50] +bronze = "Paciente.pac_pam50" +rules = [ + { source = "pam50", codes = ["LUMA"], then = "LumA" }, + { source = "pam50", codes = ["LUMB"], then = "LumB" }, + { source = "pam50", codes = ["HER2"], then = "Her2" }, + { source = "pam50", codes = ["BASAL"], then = "Basal" }, + { source = "pam50", codes = ["CLAUDIN_LOW"], then = "claudin-low" }, + { source = "pam50", codes = ["NORMAL"], then = "Normal" }, + { source = "pam50", codes = ["NC"], then = "NC" }, +] +missing = "Desconocido" +metabric = { column = "Pam50 + Claudin-low subtype", values = { "LumA" = "LUMA", "LumB" = "LUMB", "Her2" = "HER2", "Basal" = "BASAL", "claudin-low" = "CLAUDIN_LOW", "Normal" = "NORMAL", "NC" = "NC" } } + +[variables.Celularidad] +bronze = "Paciente.pac_celularidad" +rules = [ + { source = "celularidad", codes = ["ALTA"], then = "High" }, + { source = "celularidad", codes = ["MODERADA"], then = "Moderate" }, + { source = "celularidad", codes = ["BAJA"], then = "Low" }, +] +missing = "Desconocido" +metabric = { column = "Cellularity", values = { "High" = "ALTA", "Moderate" = "MODERADA", "Low" = "BAJA" } } + +[variables.Cluster_integrativo] +bronze = "Paciente.pac_cluster_integrativo" +rules = [ + { source = "cluster_integrativo", codes = ["IC1"], then = "1" }, + { source = "cluster_integrativo", codes = ["IC2"], then = "2" }, + { source = "cluster_integrativo", codes = ["IC3"], then = "3" }, + { source = "cluster_integrativo", codes = ["IC4ERP"], then = "4ER+" }, + { source = "cluster_integrativo", codes = ["IC4ERN"], then = "4ER-" }, + { source = "cluster_integrativo", codes = ["IC5"], then = "5" }, + { source = "cluster_integrativo", codes = ["IC6"], then = "6" }, + { source = "cluster_integrativo", codes = ["IC7"], then = "7" }, + { source = "cluster_integrativo", codes = ["IC8"], then = "8" }, + { source = "cluster_integrativo", codes = ["IC9"], then = "9" }, + { source = "cluster_integrativo", codes = ["IC10"], then = "10" }, +] +missing = "Desconocido" +metabric = { column = "Integrative Cluster", values = { "1" = "IC1", "2" = "IC2", "3" = "IC3", "4ER+" = "IC4ERP", "4ER-" = "IC4ERN", "5" = "IC5", "6" = "IC6", "7" = "IC7", "8" = "IC8", "9" = "IC9", "10" = "IC10" } } + +# ---- SCAN-B only ---- +[variables.Ki67] +bronze = "Paciente.pac_ki67_categoria" +rules = [ + { source = "ki67_categoria", codes = ["BAJO"], then = "Low" }, + { source = "ki67_categoria", codes = ["INTERMEDIO"], then = "Intermediate" }, + { source = "ki67_categoria", codes = ["ALTO"], then = "High" }, +] +missing = "Desconocido" +scanb = { column = "Ki67", values = { "Low" = "BAJO", "Intermediate" = "INTERMEDIO", "High" = "ALTO" } } + +[variables.Subtipo_clinico] +bronze = "Paciente.pac_subtipo_clinico" +rules = [ + { source = "subtipo_clinico", codes = ["LUMINAL_A"], then = "Luminal A" }, + { source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_NEG"], then = "Luminal B HER2-" }, + { source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_POS"], then = "Luminal B HER2+" }, + { source = "subtipo_clinico", codes = ["BASAL_LIKE"], then = "Basal-like" }, + { source = "subtipo_clinico", codes = ["NO_LUMINAL_HER2_POS"], then = "Non-luminal HER2+" }, + { source = "subtipo_clinico", codes = ["LUMINAL_NO_DETERMINADO"], then = "Luminal undetermined" }, + { source = "subtipo_clinico", codes = ["RE_NEG_NO_DETERMINADO"], then = "ER- undetermined" }, +] +missing = "Desconocido" +scanb = { column = "ClinicalSubtype", values = { "Luminal A" = "LUMINAL_A", "Luminal B HER2-" = "LUMINAL_B_HER2_NEG", "Luminal B HER2+" = "LUMINAL_B_HER2_POS", "Basal-like" = "BASAL_LIKE", "Non-luminal HER2+" = "NO_LUMINAL_HER2_POS", "Luminal undetermined" = "LUMINAL_NO_DETERMINADO", "ER- undetermined" = "RE_NEG_NO_DETERMINADO" } } + +[variables.Estadio_clinico] +bronze = "NotaMedica.nm_estadio_clinico" +rules = [ + { source = "estadio_clinico", codes = ["E0"], then = "0" }, + { source = "estadio_clinico", codes = ["EI"], then = "1" }, + { source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "2" }, + { source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "3" }, +] +missing = "Desconocido" +scanb = { column = "tnm_ClinicalStage", values = { "0" = "E0", "1" = "EI", "2" = "EIIA", "3" = "EIIIA" } } + +[variables.AntiHER2] +treatment = "anti_her2" +rules = [ + { source = "anti_her2", codes = ["ADYUVANTE"], then = "Yes" }, + { source = "anti_her2", codes = ["NINGUNA"], then = "No" }, +] +missing = "Desconocido" +scanb = { column = "AntiHER2", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA" } + +# ---- which variables each cohort's model is designed on (before the Cramér's-V pruning) ---- +[cohorts.metabric] +name = "METABRIC" +covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno", + "Receptor_progesterona", "HER2", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Estado_menopausico", + "Cluster_integrativo", "Lateralidad", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"] +treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"] + +[cohorts.scanb] +name = "SCAN-B" +covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Receptor_estrogeno", + "Receptor_progesterona", "HER2", "Ki67", "Subtipo_clinico", "Tipo_histologico", "Estado_menopausico", "Lateralidad", + "Estadio_clinico", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"] +treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"] + +# ---- the clinical scenarios (SUBGRUPOS of `05_calculadora.py`): a conjunction of covariate categories ---- +[[cohorts.metabric.scenarios]] +name = "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)" +when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] } +[[cohorts.metabric.scenarios]] +name = "Ganglios 4+" +when = { Ganglios_positivos = ["4+"] } +[[cohorts.metabric.scenarios]] +name = "Tumor >50 mm" +when = { Tamano_tumor = [">50 mm"] } +[[cohorts.metabric.scenarios]] +name = "< 45 años" +when = { Edad = ["<45"] } +[[cohorts.metabric.scenarios]] +name = "≥ 75 años" +when = { Edad = ["75+"] } +[[cohorts.metabric.scenarios]] +name = "Basal (PAM50)" +when = { Subtipo_PAM50 = ["Basal"] } +[[cohorts.metabric.scenarios]] +name = "HER2 (PAM50)" +when = { Subtipo_PAM50 = ["Her2"] } +[[cohorts.metabric.scenarios]] +name = "Luminal B (PAM50)" +when = { Subtipo_PAM50 = ["LumB"] } +[[cohorts.metabric.scenarios]] +name = "RE+ · 1-3 ganglios · cirugía conservadora" +when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["1-3"], Cirugia = ["BREAST CONSERVING"] } +[[cohorts.metabric.scenarios]] +name = "RE− · grado 3" +when = { Receptor_estrogeno = ["Negative"], Grado_histologico = ["3"] } + +[[cohorts.scanb.scenarios]] +name = "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)" +when = { Subtipo_clinico = ["Luminal A"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] } +[[cohorts.scanb.scenarios]] +name = "Ganglios 4+" +when = { Ganglios_positivos = ["4+"] } +[[cohorts.scanb.scenarios]] +name = "Tumor >50 mm" +when = { Tamano_tumor = [">50 mm"] } +[[cohorts.scanb.scenarios]] +name = "< 45 años" +when = { Edad = ["<45"] } +[[cohorts.scanb.scenarios]] +name = "≥ 75 años" +when = { Edad = ["75+"] } +[[cohorts.scanb.scenarios]] +name = "Basal-like" +when = { Subtipo_clinico = ["Basal-like"] } +[[cohorts.scanb.scenarios]] +name = "HER2+ (luminal B HER2+ o no luminal)" +when = { Subtipo_clinico = ["Luminal B HER2+", "Non-luminal HER2+"] } +[[cohorts.scanb.scenarios]] +name = "Luminal B HER2−" +when = { Subtipo_clinico = ["Luminal B HER2-"] } +[[cohorts.scanb.scenarios]] +name = "Luminal · 1-3 ganglios · lumpectomía" +when = { Subtipo_clinico = ["Luminal A", "Luminal B HER2-"], Ganglios_positivos = ["1-3"], Cirugia = ["Lumpectomy"] } +[[cohorts.scanb.scenarios]] +name = "Grado 3" +when = { Grado_histologico = ["3"] } diff --git a/models/cama/seer_survival/fractional_weibull.py b/models/cama/seer_survival/fractional_weibull.py index a21f519..942bcec 100644 --- a/models/cama/seer_survival/fractional_weibull.py +++ b/models/cama/seer_survival/fractional_weibull.py @@ -9,7 +9,6 @@ likelihood on monthly counts of events and censorings (`tabla_eventos`), by Neld import time from functools import lru_cache -import mpmath as mp import numpy as np from scipy.optimize import minimize from scipy.special import gammaln @@ -17,6 +16,7 @@ from scipy.special import gammaln @lru_cache(maxsize=256) def _coefs(rho, m, l, N, dps): + import mpmath as mp # imported here: a module-level mpmath can't be stored with the model mp.mp.dps = dps rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l) c = [mp.mpf(1)] @@ -37,6 +37,7 @@ def _log_terms(az, rho, m, l, N): def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000): """The Kilbas-Saigo function E_{rho,m,l}(z) at each `z`: the plain series when its terms stay small, else a polynomial in `mpmath` with as many digits as the largest term needs; NaN where even that is out of reach.""" + import mpmath as mp # imported here: a module-level mpmath can't be stored with the model z = np.atleast_1d(np.asarray(z, float)) rho, m, l = float(rho), float(m), float(l) out = np.full(z.shape, np.nan) @@ -80,6 +81,7 @@ def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000): def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None): """The fractional Weibull's survival function at `t`; NaN outside its parameter region.""" + import mpmath as mp # imported here: a module-level mpmath can't be stored with the model tau1 = lam if tau1 is None else tau1 tau2 = lam if tau2 is None else tau2 t = np.atleast_1d(np.asarray(t, float)) diff --git a/models/cama/seer_survival/model.py b/models/cama/seer_survival/model.py new file mode 100644 index 0000000..690e457 --- /dev/null +++ b/models/cama/seer_survival/model.py @@ -0,0 +1,121 @@ +"""CaMa survival as a registered scenario: from the cohort's long frame to a fitted model, its metrics and the routines' +records. The six stages of the pipeline (`run.py`) are the analysis; the scenario runs the first, the depuration, over the +members' variables and fits the interval models of the survival stage (`seer_model.fit`). + +Nodes: `recoded` (the dictionary applied to the cohort), `depurated` (stage 01), `fitted_model`, `metrics` and `routines`. +The cohort's own index, the first invasive biopsy, is `models.steps.indexing`'s (`[config.index]`). +""" + +import tempfile +from pathlib import Path + +import numpy as np +import pandas as pd + +from models.cama.seer_survival import run, variables +from models.cama.seer_survival import seer_model as sm_ +from models.cama.seer_survival import survival_curves as sc +from models.cama.seer_survival import survival_models as fits +from models.cama.seer_survival.settings import Settings, load + +RECODED_FILE = "dataframe_recodificado.csv" + + +def settings() -> Settings: + return load() + + +def dictionary() -> dict: + return variables.load() + + +def recoded(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame: + """One row per member, in the columns of the variable dictionary.""" + return variables.recode(cohort, dictionary) + + +def depurated(recoded: pd.DataFrame, settings: Settings) -> pd.DataFrame: + """Stage 01 over the members: the frame without the variables the depuration drops.""" + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) + recoded.to_csv(path / RECODED_FILE, index=False) + run.run_depuration(path / RECODED_FILE, path / "sin_mapa.json", path, settings) + return pd.read_csv(path / run.DEPURATED, dtype=str, keep_default_na=False) + + +def fitted_model(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, settings: Settings, + index: dict) -> sm_.SeerSurvivalModel: + return sm_.fit(recoded, depurated, dictionary, settings.survival, index) + + +def metrics(fitted_model: sm_.SeerSurvivalModel) -> dict: + state = fitted_model.fit_state + return {"members": state.members, "deaths": state.deaths, "covariates": len(state.design.covariates), + "replicas": len(state.replicas), + **{f"weight_lr_interval_{i + 1}": float(w) for i, w in enumerate(state.weights)}} + + +def sampling(recoded: pd.DataFrame, fitted_model: sm_.SeerSurvivalModel, index_attrition: list, prior_observation: dict, + dictionary: dict) -> dict: + """MUESTREO: who could be used (the index and each rule's attrition, their prior history), the follow-up and the + resampling.""" + s, state = fitted_model.survival, fitted_model.fit_state + return {"method": "toda la cohorte indexada en su primera biopsia invasora; sin partición: la validación es de las " + f"predicciones fuera de muestra en {s.stack_folds} pliegues y de las réplicas bootstrap", + "index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation, + "members": state.members, "deaths": state.deaths, "follow_up_cap_months": s.cap_months, + "bootstrap_replicas": len(state.replicas), "stack_folds": s.stack_folds} + + +def missing_data(recoded: pd.DataFrame, dictionary: dict) -> dict: + """DATOS_FALTANTES: how many members lack each variable (its `missing` category), and what is done about it.""" + counts = {} + for name in variables.variable_names(dictionary): + spec = dictionary[name] + if spec.get("internal"): + continue + counts[name] = int((recoded[variables.column_of(name, spec)] == spec["missing"]).sum()) + return {"method": "un dato ausente es la categoría `missing` de su variable en el diccionario; nadie se excluye", + "members": len(recoded), "missing_by_variable": counts} + + +def analytic_method(fitted_model: sm_.SeerSurvivalModel) -> dict: + """METODO_ANALITICO: the LR coefficients and the HBN's parents of each interval, and the weights that combine them.""" + s, state = fitted_model.survival, fitted_model.fit_state + design = state.design + names = [f"{c}={k}" for c in design.covariates for k in design.sorted_categories[c][1:]] + intervals = [] + for (a, b), fit, weight in zip(zip([0] + list(s.horizons[:-1]), s.horizons), state.point, state.weights): + intervals.append({"interval_months": [int(a), int(b)], "weight_lr": float(weight), + "intercept": float(fit.intercept), "coefficients": dict(zip(names, map(float, fit.coef))), + "hbn_parents": [design.covariates[j] for j in fit.parents]}) + return {"method": "regresión logística y red bayesiana con tabla de probabilidad por intervalo, combinadas con el peso " + "que maximiza la verosimilitud fuera de muestra", "covariates": design.covariates, "intervals": intervals} + + +def class_balance(fitted_model: sm_.SeerSurvivalModel, depurated: pd.DataFrame) -> dict: + """BALANCE_CLASES: the members at risk and the deaths of each interval; none is reweighted but the half weight of a + censoring inside an interval.""" + s = fitted_model.survival + frame = sc.survival_frame(depurated, s) + months, event = frame.df["meses_int"].values, frame.df["evento"].values + rows = [] + for a, b in zip([0] + list(s.horizons[:-1]), s.horizons): + at_risk = months >= a + rows.append({"interval_months": [int(a), int(b)], "at_risk": int(at_risk.sum()), + "deaths": int((event & at_risk & (months < b)).sum()), + "censored": int(((~event) & at_risk & (months < b)).sum())}) + return {"method": "las clases se usan en su proporción observada; una censura dentro de un intervalo pesa la mitad", + "intervals": rows} + + +def output_confidence(fitted_model: sm_.SeerSurvivalModel) -> dict: + """CONFIANZA_SALIDA: the survival at each horizon of the members of each decile of predicted survival, out of sample, + against the Kaplan-Meier of those members.""" + return {"method": "calibración fuera de muestra: supervivencia predicha contra Kaplan-Meier, por deciles", + "deciles": fitted_model.fit_state.calibration} + + +def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict, output_confidence: dict) -> dict: + return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method, + "BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence} diff --git a/models/cama/seer_survival/model.toml b/models/cama/seer_survival/model.toml index d7bb1af..be66687 100644 --- a/models/cama/seer_survival/model.toml +++ b/models/cama/seer_survival/model.toml @@ -1,10 +1,32 @@ # CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs. +domain = "cama" +scenario = "seer_survival" +cohort = "cama/cohorte_total" +outcome = "survival_18m" +requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "cloudpickle"] +modules = ["models.cama.seer_survival.model", "models.steps.indexing"] +# The tables whose values make a version a different one (with `[config]`): the depuration, the survival stage's settings +# and the variable dictionary. +settings_tables = ["depuration", "survival", "variables"] +description = """ +Supervivencia del cáncer de mama a 6, 12 y 18 meses desde el diagnóstico (primera biopsia con carcinoma invasor): \ +regresión logística y red bayesiana por intervalo, combinadas, sobre las variables del diccionario del modelo; \ +entrenado y validado con los datos de SEER.""" + +# The dataflow's config (`with_config`). +[config] +horizons_years = [0.5, 1.0, 1.5] + +[config.index] +kind = "primera_biopsia_invasora" +observacion_previa_minima_dias = 0 + [depuration] exclude = ["Outcome_cat"] # never analysed or touched auto_extra = ["Age_group", "Tumor_group"] # included when present extra_cols = [] -protected = [] # e.g. ["Estadio_cat"]: never dropped +protected = ["Estadio_cat", "Subtipo_molecular_cat", "Tratamiento_quirurgico_cat"] # the axes of the clinical scenarios: never dropped prefer = ["Tumor_group", "Age_group"] # on a tie or duplicate, the one listed here wins (the project's own groupings) drop_raw_sources = true # also drop the raw SEER column of a dropped variable unknown_label = "Desconocido" @@ -151,7 +173,111 @@ xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty [survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0] -# The subgroups of the survival curves, and the risk factors of each, are the clinical scenarios of `scenarios.py`. +# The clinical scenarios, in the doctors' terms: every condition must hold. A condition names a variable of the +# dictionary (`Edad`: the age in years, the start of its band) and tests `contains` (the category has this text), `in` (it +# is one of these) or, for the age, `ge` / `lt`. +[[survival.subgroups]] +name = "HER2+ · ≥60 años · estadio III–IV (Alto)" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2+" }, + { variable = "Edad", ge = 60 }, + { variable = "Estadio", in = ["III", "IV"] } +] + +[[survival.subgroups]] +name = "HER2+ · <60 años · estadio 0–II (Bajo)" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2+" }, + { variable = "Edad", lt = 60 }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] } +] + +[[survival.subgroups]] +name = "Estadio IV" +conditions = [ + { variable = "Estadio", in = ["IV"] } +] + +[[survival.subgroups]] +name = "Estadio I" +conditions = [ + { variable = "Estadio", in = ["I"] } +] + +[[survival.subgroups]] +name = "≥ 75 años" +conditions = [ + { variable = "Edad", ge = 75 } +] + +[[survival.subgroups]] +name = "< 45 años" +conditions = [ + { variable = "Edad", lt = 45 } +] + +[[survival.subgroups]] +name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2-" }, + { variable = "Edad", lt = 45 }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] }, + { variable = "Tratamiento_quirurgico", in = ["Conservadora"] } +] + +[[survival.subgroups]] +name = "HER2− · estadio 0–II · cirugía conservadora" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2-" }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] }, + { variable = "Tratamiento_quirurgico", in = ["Conservadora"] } +] + +[[survival.subgroups]] +name = "HER2+ · estadio 0–II · cirugía conservadora" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2+" }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] }, + { variable = "Tratamiento_quirurgico", in = ["Conservadora"] } +] + +[[survival.subgroups]] +name = "Jóvenes (<45) · estadio 0–II" +conditions = [ + { variable = "Edad", lt = 45 }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] } +] + +[[survival.subgroups]] +name = "Jóvenes (<45) · HER2−" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2-" }, + { variable = "Edad", lt = 45 } +] + +[[survival.subgroups]] +name = "Triple negativo (HR−/HER2−) · estadio 0–II" +conditions = [ + { variable = "Subtipo_molecular", contains = "HR-/HER2-" }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] } +] + +[[survival.subgroups]] +name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora" +conditions = [ + { variable = "Subtipo_molecular", contains = "HER2-" }, + { variable = "Edad", ge = 65 }, + { variable = "Estadio", in = ["0 (in situ)", "I", "II"] }, + { variable = "Tratamiento_quirurgico", in = ["Conservadora"] } +] + +[figure] +# The scenario figure computed on request (`SeerSurvivalModel.figure_record`): the seconds the fractional Weibull may take, +# the least members and deaths a scenario needs to be drawn, and the bootstrap replicas applied (empty: all of the model's). +ks_max_seconds = 30 +min_members = 30 +min_deaths = 5 +n_boot = 100 [risk_factors] # A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not @@ -263,3 +389,266 @@ Microcalcificaciones_cat = "Microcalcificaciones" Multifocalidad_cat = "Multifocalidad" BRCA_cat = "BRCA" HER2_IHQ_cat = "HER2_IHQ" + +# ---------------------------------------------------------------------------------------------------------------------- +# The variable dictionary. One table per variable of the model: the column it makes, how its category is read from a +# patient's timeline (`rules`, in order, the first that holds; `missing` when none does) and, for the SEER load, where the +# SEER category is stored in CaMa's bronze (`seer`). A rule is one condition or a `when` list that must all hold; a +# condition names a timeline `source` (the `tipo` of the patient's latest event of that kind) or an earlier `variable`, +# and tests `codes` (the value is one of them), `present` (there is such an event), or `ge` / `lt` (the number). +# ---------------------------------------------------------------------------------------------------------------------- +[variables] +window_days_after_index = 365 # the events from the index on that still describe the patient at diagnosis and treatment + +[variables.index] +id_column = "Patient_ID" +year_column = "Year_of_diagnosis" +age_column = "Age_recode_with_1_year_olds_and_90" +age_band_years = 5 +age_open_from = 90 +age_label = "{low}-{high} years" +age_open_label = "{low}+ years" +age_unknown = "Otros (agrupado)" +months_column = "Survival_months" +vital_column = "Vital_status_recode_study_cutoff_used" +alive = "Alive" +dead = "Dead" +days_per_month = 30.4375 +death_source = "defuncion" +birth_source = "nacimiento" +# SEER's calendar dates are not recorded: the diagnosis is the 1st of July of its year, the birth the middle of the age +# band, the death the diagnosis plus the survival months, the last contact of the living the same. +seer_diagnosis_month_day = "07-01" +seer_age_open_value = 92 + +[variables.Estadio] +rules = [ + { source = "estadio_clinico", codes = ["E0"], then = "0 (in situ)" }, + { source = "estadio_clinico", codes = ["EI"], then = "I" }, + { source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "II" }, + { source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "III" }, + { source = "estadio_clinico", codes = ["EIV"], then = "IV" }, +] +missing = "Desconocido" +seer = { bronze = "NotaMedica.nm_estadio_clinico", values = { "0 (in situ)" = "E0", "I" = "EI", "II" = "EIIA", "III" = "EIIIA", "IV" = "EIV" } } + +[variables.Grado_histologico] +rules = [ + { source = "grado_nottingham", codes = ["G1"], then = "G1" }, + { source = "grado_nottingham", codes = ["G2"], then = "G2" }, + { source = "grado_nottingham", codes = ["G3"], then = "G3" }, +] +missing = "Desconocido" +seer = { bronze = "BiopsiaMama.bx_grado_nottingham", values = { "G1" = "G1", "G2" = "G2", "G3" = "G3" } } + +[variables.Receptor_estrogeno] +rules = [ + { source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positivo" }, + { source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negativo" }, +] +missing = "Desconocido" +seer = { bronze = "BiopsiaMama.bx_receptor_estrogeno", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } } + +[variables.Receptor_progesterona] +rules = [ + { source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positivo" }, + { source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negativo" }, +] +missing = "Desconocido" +seer = { bronze = "BiopsiaMama.bx_receptor_progesterona", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } } + +# HER2 is positive or negative by the FISH when there is one, else by the immunohistochemistry (3+ positive, 0 and 1+ +# negative, 2+ equivocal). +[variables.HER2_estado] +internal = true +rules = [ + { source = "her2_fish", codes = ["POSITIVO"], then = "Positivo" }, + { source = "her2_fish", codes = ["NEGATIVO"], then = "Negativo" }, + { source = "her2", codes = ["H3"], then = "Positivo" }, + { source = "her2", codes = ["H0", "H1"], then = "Negativo" }, +] +missing = "Desconocido" +seer = { from = "Subtipo_molecular", bronze = "BiopsiaMama.bx_her2_fish", values = { "HR+/HER2+" = "POSITIVO", "HR-/HER2+" = "POSITIVO", "HR+/HER2-" = "NEGATIVO", "HR-/HER2-" = "NEGATIVO" } } + +[variables.HER2_IHQ] +rules = [ + { source = "her2", codes = ["H0"], then = "0" }, + { source = "her2", codes = ["H1"], then = "1+" }, + { source = "her2", codes = ["H2"], then = "2+" }, + { source = "her2", codes = ["H3"], then = "3+" }, +] +missing = "Sin dato" +seer = { bronze = "BiopsiaMama.bx_her2", values = { "0" = "H0", "1+" = "H1", "2+" = "H2", "3+" = "H3" } } + +[variables.HR_estado] +internal = true +rules = [ + { when = [{ variable = "Receptor_estrogeno", codes = ["Positivo"] }], then = "HR+" }, + { when = [{ variable = "Receptor_progesterona", codes = ["Positivo"] }], then = "HR+" }, + { when = [{ variable = "Receptor_estrogeno", codes = ["Negativo"] }, { variable = "Receptor_progesterona", codes = ["Negativo"] }], then = "HR-" }, +] +missing = "Desconocido" + +[variables.Subtipo_molecular] +rules = [ + { when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR+/HER2-" }, + { when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR+/HER2+" }, + { when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR-/HER2+" }, + { when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR-/HER2-" }, +] +missing = "Desconocido" + +[variables.Tipo_histologico] +rules = [ + { source = "tipo_histologico", codes = ["8500/3"], then = "Ductal (NST)" }, + { source = "tipo_histologico", codes = ["8520/3", "8521/3"], then = "Lobulillar" }, + { source = "tipo_histologico", codes = ["8522/3", "8523/3"], then = "Ductal-lobulillar mixto" }, + { source = "tipo_histologico", codes = ["8480/3"], then = "Mucinoso" }, + { source = "tipo_histologico", codes = ["8211/3", "8201/3"], then = "Tubular / cribiforme" }, + { source = "tipo_histologico", codes = ["8050/3", "8503/3", "8504/3"], then = "Papilar" }, + { source = "tipo_histologico", codes = ["8507/3"], then = "Micropapilar" }, + { source = "tipo_histologico", codes = ["8540/3", "8541/3", "8543/3"], then = "Paget" }, + { source = "tipo_histologico", codes = ["8510/3"], then = "Medular" }, + { source = "tipo_histologico", codes = ["8530/3"], then = "Inflamatorio" }, + { source = "tipo_histologico", present = true, then = "Otros" }, +] +missing = "SIN MAPEAR" +seer = { bronze = "BiopsiaMama.bx_tipo_histologico", values = { "Ductal (NST)" = "8500/3", "Lobulillar" = "8520/3", "Ductal-lobulillar mixto" = "8522/3", "Mucinoso" = "8480/3", "Tubular / cribiforme" = "8211/3", "Papilar" = "8503/3", "Micropapilar" = "8507/3", "Paget" = "8541/3", "Medular" = "8510/3", "Inflamatorio" = "8530/3", "Otros" = "8575/3" } } + +[variables.Localizacion_mama] +rules = [ + { source = "localizacion", codes = ["C500"], then = "Pezón" }, + { source = "localizacion", codes = ["C501"], then = "Porción central" }, + { source = "localizacion", codes = ["C502", "C503"], then = "Cuadrantes internos" }, + { source = "localizacion", codes = ["C504", "C505"], then = "Cuadrantes externos" }, + { source = "localizacion", codes = ["C506"], then = "Cola axilar" }, + { source = "localizacion", codes = ["C508"], then = "Lesión solapada" }, + { source = "localizacion", codes = ["C509"], then = "Mama NOS" }, +] +missing = "Mama NOS" +seer = { bronze = "BiopsiaMama.bx_localizacion", values = { "Pezón" = "C500", "Porción central" = "C501", "Cuadrantes internos" = "C502", "Cuadrantes externos" = "C504", "Cola axilar" = "C506", "Lesión solapada" = "C508", "Mama NOS" = "C509" } } + +[variables.Lateralidad] +rules = [ + { source = "lateralidad", codes = ["DERECHA"], then = "Derecha" }, + { source = "lateralidad", codes = ["IZQUIERDA"], then = "Izquierda" }, +] +missing = "Otra / no especificada" +seer = { bronze = "BiopsiaMama.bx_lateralidad", values = { "Derecha" = "DERECHA", "Izquierda" = "IZQUIERDA" } } + +[variables.Metastasis] +rules = [ + { source = "metastasis", codes = ["M1"], then = "Con metástasis" }, +] +missing = "Sin metástasis" +seer = { bronze = "NotaMedica.nm_metastasis", values = { "Con metástasis" = "M1", "Sin metástasis" = "M0" } } + +# The tumour size in millimetres: its category and the raw column the age and tumour groupings of stage 02 read. +[variables.Tamano_tumor] +source = "tamano_tumor_mm" +rules = [ + { source = "tamano_tumor_mm", lt = 21, then = "T1 (<=20 mm)" }, + { source = "tamano_tumor_mm", ge = 21, lt = 51, then = "T2 (21-50 mm)" }, + { source = "tamano_tumor_mm", ge = 51, then = "T3+ (>50 mm)" }, +] +missing = "Desconocido" +raw_column = "Tumor_Size_Over_Time_Recode_1988" +raw_format = "{:03.0f}" +raw_missing = "Unknown or size unreasonable (includes any tumor sizes 401-989)" +seer = { bronze = "BiopsiaMama.bx_tamano_tumor_mm", number = "Tumor_Size_Over_Time_Recode_1988", unknown = ["Unknown or size unreasonable (includes any tumor sizes 401-989)", "Otros (agrupado)"], microscopic = ["990 (microscopic focus)"], microscopic_mm = 1 } + +[variables.Ganglios_positivos] +rules = [ + { source = "ganglios_positivos", lt = 1, then = "0" }, + { source = "ganglios_positivos", ge = 1, lt = 4, then = "1-3" }, + { source = "ganglios_positivos", ge = 4, lt = 10, then = "4-9" }, + { source = "ganglios_positivos", ge = 10, then = "10+" }, +] +missing = "0" +seer = { bronze = "BiopsiaMama.bx_ganglios_positivos", number_values = { "0" = 0, "1-3" = 2, "4-9" = 6, "10+" = 12 } } + +[variables.Invasion_linfovascular] +rules = [{ source = "invasion_linfovascular", codes = ["PRESENTE"], then = "Si" }] +missing = "No" +seer = { bronze = "BiopsiaMama.bx_invasion_linfovascular", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } } + +[variables.Multifocalidad] +rules = [{ source = "multifocalidad", codes = ["PRESENTE"], then = "Si" }] +missing = "No" +seer = { bronze = "BiopsiaMama.bx_multifocalidad", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } } + +[variables.Margenes] +rules = [ + { source = "margenes", codes = ["LIBRES"], then = "Negativos" }, + { source = "margenes", codes = ["CERCANOS", "AFECTADOS"], then = "Positivos" }, + { source = "margenes", codes = ["SIN_CIRUGIA"], then = "Sin cirugia" }, +] +missing = "Sin dato" +seer = { bronze = "BiopsiaMama.bx_margenes", values = { "Negativos" = "LIBRES", "Positivos" = "AFECTADOS", "Sin cirugia" = "SIN_CIRUGIA" } } + +[variables.Densidad_BIRADS] +rules = [ + { source = "densidad_mamaria", codes = ["A"], then = "A" }, + { source = "densidad_mamaria", codes = ["B"], then = "B" }, + { source = "densidad_mamaria", codes = ["C"], then = "C" }, + { source = "densidad_mamaria", codes = ["D"], then = "D" }, +] +missing = "B" +seer = { bronze = "Mastografia.mast_densidad", values = { "A" = "A", "B" = "B", "C" = "C", "D" = "D" } } + +[variables.Masa_espiculada] +rules = [{ source = "margen_masa", codes = ["ESPICULADO"], then = "Si" }] +missing = "No" +seer = { bronze = "Mastografia.mast_margen_masa", values = { "Si" = "ESPICULADO" } } + +[variables.Microcalcificaciones] +rules = [{ source = "tipo_hallazgo", codes = ["CALCIFICACIONES"], then = "Si" }] +missing = "No" +seer = { bronze = "Mastografia.mast_tipo_hallazgo", values = { "Si" = "CALCIFICACIONES" } } + +[variables.BRCA] +rules = [ + { source = "brca1", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA1" }, + { source = "brca2", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA2" }, +] +missing = "Negativo" +seer = { bronze = "Paciente.pac_brca1", values = { "BRCA1" = "PATOGENICA", "Negativo" = "NEGATIVO" }, also = { bronze = "Paciente.pac_brca2", values = { "BRCA2" = "PATOGENICA", "Negativo" = "NEGATIVO" } } } + +[variables.Estado_civil] +rules = [ + { source = "estado_civil", codes = ["SOLTERA", "CASADA", "UNION_LIBRE"], then = "Con pareja" }, + { source = "estado_civil", codes = ["SEPARADA", "DIVORCIADA", "VIUDA"], then = "Sin pareja" }, +] +missing = "Desconocido" +seer = { bronze = "Paciente.pac_estado_civil", values = { "Con pareja" = "CASADA", "Sin pareja" = "DIVORCIADA" } } + +[variables.Race] +column = "Race_recode_White_Black_Other" +rules = [ + { source = "raza", codes = ["BLANCA"], then = "White" }, + { source = "raza", codes = ["NEGRA"], then = "Black" }, + { source = "raza", codes = ["OTRA"], then = "Other (American Indian/AK Native, Asian/Pacific Islander)" }, +] +missing = "Unknown" +seer = { bronze = "Paciente.pac_raza", values = { "White" = "BLANCA", "Black" = "NEGRA", "Other (American Indian/AK Native, Asian/Pacific Islander)" = "OTRA" } } + +[variables.Tratamiento_quirurgico] +rules = [ + { source = "cirugia", codes = ["ESCISIONAL", "SEGMENTECTOMIA"], then = "Conservadora" }, + { source = "cirugia", codes = ["MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"], then = "Mastectomía" }, + { source = "cirugia", codes = ["SIN_CIRUGIA"], then = "Ninguna" }, + { source = "cirugia", codes = ["DESTRUCCION_LOCAL"], then = "Destrucción local" }, + { source = "cirugia", codes = ["CIRUGIA_NO_ESPECIFICADA"], then = "Cirugía NOS" }, +] +missing = "Desconocido" +seer = { treatment = "cirugia", values = { "Conservadora" = "SEGMENTECTOMIA", "Mastectomía" = "MASTECTOMIA_TOTAL", "Ninguna" = "SIN_CIRUGIA", "Destrucción local" = "DESTRUCCION_LOCAL", "Cirugía NOS" = "CIRUGIA_NO_ESPECIFICADA" } } + +[variables.Radioterapia] +rules = [{ source = "radioterapia", present = true, then = "Sí" }] +missing = "No o desconocido" +seer = { treatment = "radioterapia", values = { "Sí" = "ADYUVANTE" } } + +[variables.Quimioterapia] +rules = [{ source = "quimioterapia", present = true, then = "Sí" }] +missing = "No o desconocido" +seer = { treatment = "quimioterapia", values = { "Sí" = "ADYUVANTE" } } diff --git a/models/cama/seer_survival/seer_import.py b/models/cama/seer_survival/seer_import.py new file mode 100644 index 0000000..3461c5d --- /dev/null +++ b/models/cama/seer_survival/seer_import.py @@ -0,0 +1,138 @@ +"""SEER's recoded file as CaMa import files: one CSV per bronze entity, named by the fields the import schemas take, to be +uploaded through the platform's import like any other source. + + python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR + +What goes where is the dictionary's (`[variables.*.seer]` of `model.toml`): each SEER category is stored as the catalog +value the dictionary names, and read back as the same category. SEER records no calendar dates: the diagnosis is a fixed +day of its year, the birth the middle of the age band, the death (or, for the living, the last contact) the diagnosis +plus the survival months; the months stay exact. +""" + +import argparse +from datetime import timedelta +from pathlib import Path + +import pandas as pd + +from models.cama.seer_survival import variables + +ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "Mastografia": "mastografias", + "NotaMedica": "notas", "TratamientoMama": "tratamientos"} +FEMALE = "Femenino" + + +def _age_years(label: str, index: dict) -> float | None: + """The middle of an age band ("60-64 years" -> 62.5); the open band's own value; None without a number.""" + head = str(label).split(" ")[0] + if head.endswith("+"): + return float(index["seer_age_open_value"]) + low, _, high = head.partition("-") + if not (low.isdigit() and high.isdigit()): + return None + return (int(low) + int(high) + 1) / 2 + + +def _number(text, spec: dict) -> float | None: + text = str(text) + if text in spec["microscopic"]: + return float(spec["microscopic_mm"]) + return float(text) if text.replace(".", "", 1).isdigit() else None + + +def convert(recoded: pd.DataFrame, dictionary: dict) -> dict[str, pd.DataFrame]: + index = dictionary["index"] + ages = recoded[index["age_column"]].map(lambda v: _age_years(v, index)) + frame = recoded[ages.notna()].copy() + ages = ages[ages.notna()] + months = pd.to_numeric(frame[index["months_column"]]).astype(int) + dead = frame[index["vital_column"]].eq(index["dead"]) + day = pd.to_timedelta(months * index["days_per_month"], unit="D").dt.round("D") + diagnosis = frame[index["year_column"]].astype(int).map(lambda y: pd.Timestamp(variables.diagnosis_date(y, dictionary))) + birth = diagnosis - pd.to_timedelta((ages * 365.25).round(), unit="D") + ident = frame[index["id_column"]].astype(str) + date = lambda s: s.dt.strftime("%Y-%m-%d") + + tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES} + tables["Paciente"]["pac_sexo"] = FEMALE + tables["Paciente"]["pac_fecha_nacimiento"] = date(birth) + tables["Paciente"]["pac_fecha_defuncion"] = date(diagnosis + day).where(dead) + tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis) + tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis) + tables["Mastografia"]["mast_fecha_toma"] = date(diagnosis) + tables["Mastografia"]["mast_fecha_reporte"] = date(diagnosis) + + for name in variables.variable_names(dictionary): + spec = dictionary[name] + seer = spec.get("seer") + if not seer or "treatment" in seer: + continue + origin = seer.get("from", name) + category = frame[variables.column_of(origin, dictionary[origin])] + for target in (seer, seer.get("also")): + if not target: + continue + entity, column = target["bronze"].split(".") + if "number" in seer: + tables[entity][column] = frame[seer["number"]].map(lambda v: _number(v, seer)) + elif "number_values" in seer: + tables[entity][column] = category.map(seer["number_values"]) + else: + tables[entity][column] = category.map(target["values"]) + + # A biopsy is invasive unless the stage says in situ. + stage = frame[variables.column_of("Estadio", dictionary["Estadio"])] + in_situ = [k for k, v in dictionary["Estadio"]["seer"]["values"].items() if v == "E0"] + tables["BiopsiaMama"]["bx_grado_histologico"] = stage.isin(in_situ).map( + {True: "CARCINOMA_IN_SITU", False: "CARCINOMA_INVASOR"}) + + # A receptor status the subtype contradicts follows the subtype (the model reads the subtype from the receptors). + subtype = frame[variables.column_of("Subtipo_molecular", dictionary["Subtipo_molecular"])] + positive_hr = subtype.str.startswith("HR+") + negative_hr = subtype.str.startswith("HR-") + bx = tables["BiopsiaMama"] + no_positive = ~((bx["bx_receptor_estrogeno"] == "POSITIVO") | (bx["bx_receptor_progesterona"] == "POSITIVO")) + bx.loc[positive_hr & no_positive, "bx_receptor_estrogeno"] = "POSITIVO" + for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"): + bx.loc[negative_hr & bx[column].isna(), column] = "NEGATIVO" + for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"): + bx.loc[negative_hr & (bx[column] == "POSITIVO"), column] = "NEGATIVO" + + notes = tables["NotaMedica"] + notes["nm_id_hospital"] = ident + "-dx" + notes["nm_fecha"] = date(diagnosis) + notes["nm_tipo_nota"] = "CONSULTA" + follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(diagnosis + day), + "nm_tipo_nota": "CONSULTA"})[~dead.to_numpy()] + tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True) + + treatments = [] + for name in variables.variable_names(dictionary): + seer = dictionary[name].get("seer", {}) + if "treatment" not in seer: + continue + category = frame[variables.column_of(name, dictionary[name])] + values = category.map(seer["values"]) + rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": seer["treatment"], "trat_fecha": date(diagnosis), + "trat_detalle": values})[values.notna()] + if seer["treatment"] == "cirugia": + rows["trat_lateralidad"] = bx["bx_lateralidad"].reindex(rows.index) + treatments.append(rows) + tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True) + return tables + + +def main(argv=None) -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("recoded") + ap.add_argument("out_dir") + args = ap.parse_args(argv) + recoded = pd.read_csv(args.recoded, dtype=str, low_memory=False) + out = Path(args.out_dir) + out.mkdir(parents=True, exist_ok=True) + for entity, table in convert(recoded, variables.load()).items(): + table.to_csv(out / f"{ENTITIES[entity]}.csv", index=False) + + +if __name__ == "__main__": + main() diff --git a/models/cama/seer_survival/seer_model.py b/models/cama/seer_survival/seer_model.py new file mode 100644 index 0000000..9413fa3 --- /dev/null +++ b/models/cama/seer_survival/seer_model.py @@ -0,0 +1,225 @@ +"""The registered CaMa survival model: the dictionary, the covariates the depuration kept, and the interval models of the +survival stage (LR and HBN per interval, the weights that combine them, and the replicas that give their intervals), fitted +on a cohort and kept. It scores any cohort's members from their timelines, and draws a clinical scenario's figure +(`figure_record`): Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the LR / HBN / combined +survival at the horizons with a bootstrap interval. + +The fitted state is plain arrays and dictionaries; `rehydrate` puts a saved model's state into the current class, so a +version trained earlier is scored by today's code. +""" + +import time +from dataclasses import dataclass, field + +import numpy as np +import pandas as pd +from sklearn.base import BaseEstimator + +from models.cama.seer_survival import fractional_weibull as fw +from models.cama.seer_survival import survival_curves as sc +from models.cama.seer_survival import survival_models as sm +from models.cama.seer_survival import variables +from models.cama.seer_survival.settings import SurvivalSettings +from models.steps import indexing + +NO_CATEGORY = "NA" + + +def figure_settings() -> dict: + """`[figure]` of `model.toml`: what `figure_record` takes besides the scenario.""" + import tomllib + + return tomllib.loads(variables.TOML.read_text(encoding="utf-8"))["figure"] + + +@dataclass(frozen=True, eq=False) +class Design: + """The covariates' coding the fits were made with: each covariate's categories sorted (the dummies drop the first) and in + order of first appearance (the HBN's integer codes), so any frame is coded as the training cohort was.""" + + covariates: list[str] + sorted_categories: dict[str, list[str]] + appearance: dict[str, list[str]] + + @classmethod + def of(cls, frame: sc.SurvivalFrame) -> "Design": + df = frame.df + return cls(list(frame.covariates), {c: sorted(df[c].unique()) for c in frame.covariates}, + {c: list(pd.factorize(df[c])[1]) for c in frame.covariates}) + + @property + def levels(self) -> np.ndarray: + return np.array([len(self.appearance[c]) for c in self.covariates]) + + def encode(self, df: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + """(dummies, integer codes); a category the training cohort never had is coded as its reference.""" + dummies, codes = [], [] + for c in self.covariates: + values = df[c].fillna(NO_CATEGORY).astype(str).str.strip() + dummies += [(values == k).to_numpy(np.float32) for k in self.sorted_categories[c][1:]] + position = {k: i for i, k in enumerate(self.appearance[c])} + codes.append(values.map(position).fillna(0).astype(int).to_numpy()) + return np.column_stack(dummies), np.column_stack(codes) + + +@dataclass +class Fit: + """What `fit` leaves: the point fits, the bootstrap replicas' fits, the weights of the combination (the cohort's and each + configured scenario's) and what the cohort was.""" + + point: list + replicas: list + weights: np.ndarray + scenario_weights: dict + design: Design + members: int + deaths: int + calibration: list = field(default_factory=list) + + +class SeerSurvivalModel(BaseEstimator): + """Scores a cohort's long frame (`predict_proba`: per member, in `pac_id` order, the risk of dying by each horizon).""" + + def __init__(self, dictionary=None, survival=None, index=None, fit_state=None, kept=None, horizons_years=None): + self.dictionary = dictionary + self.survival = survival + self.index = index + self.fit_state = fit_state + self.kept = kept + self.horizons_years = horizons_years + + @classmethod + def rehydrate(cls, saved) -> "SeerSurvivalModel": + """The current class holding a saved model's state.""" + model = cls.__new__(cls) + model.__dict__.update(saved.__dict__) + return model + + # ------------------------------------------------------------------ from the timeline to the design + + def recode(self, cohort: pd.DataFrame, *, indexed: bool = False) -> pd.DataFrame: + """One row per member in the columns the dictionary makes; the cohort is re-indexed at the first invasive biopsy + unless it already is.""" + if not indexed and self.index: + cohort = indexing.cohort(cohort, {}, self.index) + return variables.recode(cohort, self.dictionary) + + def frame(self, recoded: pd.DataFrame) -> sc.SurvivalFrame: + """The recoded members as the survival stage reads them, restricted to the covariates the depuration kept.""" + columns = [c for c in recoded.columns if c in self.kept or not c.endswith("_cat")] + frame = sc.survival_frame(recoded[columns], self.survival) + covariates = [c for c in self.fit_state.design.covariates] + for c in covariates: + if c not in frame.df.columns: + frame.df[c] = NO_CATEGORY + return sc.SurvivalFrame(frame.df, covariates, frame.age_col, frame.numeric_cols) + + def _survival(self, frame: sc.SurvivalFrame, weights=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + design = self.fit_state.design + X_dum, X_int = design.encode(frame.df) + P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels) + W = self.fit_state.weights if weights is None else weights + return np.cumprod(P_lr, axis=1), np.cumprod(P_hb, axis=1), sm.mix(P_lr, P_hb, W) + + def predict_proba(self, cohort: pd.DataFrame) -> np.ndarray: + recoded = self.recode(cohort) + frame = self.frame(recoded) + combined = self._survival(frame)[2] + order = np.argsort(recoded[self.dictionary["index"]["id_column"]].to_numpy()) + return 1 - combined[order] + + def predict(self, cohort: pd.DataFrame) -> np.ndarray: + return self.predict_proba(cohort) + + # ------------------------------------------------------------------ a scenario's figure + + def scenario_names(self) -> list[str]: + return [spec["name"] for spec in self.survival.subgroups] + + def scenario_masks(self, frame: sc.SurvivalFrame) -> dict[str, np.ndarray]: + return sc.sv_masks(frame, self.survival, self.dictionary) + + def figure_record(self, frame: sc.SurvivalFrame, scenario: str, *, ks_max_seconds: float = 30.0, n_boot: int | None = None, + min_members: int = 30, min_deaths: int = 5, extrapolate_months: int | None = None) -> dict: + """The figure of one scenario over the members of `frame`; `None` for the parts a scenario with too few members or + deaths cannot support. The interval of each point is the percentile of the replicas' mean survival over members + resampled with replacement.""" + s = self.survival + masks = self.scenario_masks(frame) + mask = masks[scenario] + df = frame.df[mask] + deaths = int(df["evento"].sum()) + record = {"scenario": scenario, "members": int(len(df)), "deaths": deaths, "horizons": list(s.horizons), "points": []} + if len(df) < min_members or deaths < min_deaths: + return {**record, "drawable": False} + months, events = df["meses_int"].values, df["evento"].values + horizon = max(s.months_max, max(s.horizons)) + S, lo, hi = fw.km_curva(months, events, horizon) + d, c = fw.tabla_eventos(months, events) + weibull = fw.ajustar_weibull(d, c) + fractional = fw.ajustar_ks(d, c, k_fijo=sc._fixed_k(weibull, s), lam_ref=weibull["lam"], max_seg=ks_max_seconds) + reach = extrapolate_months or s.months_extrapolated + grid = np.arange(0, reach + 1, dtype=float) + record.update(drawable=True, months=list(range(horizon + 1)), km={"S": S.tolist(), "lo": lo.tolist(), "hi": hi.tolist()}, + curve_months=grid.tolist(), + weibull={"k": float(weibull["k"]), "S": np.asarray(weibull["S"](grid)).tolist()}, + fractional={"k": float(fractional["k"]), "alpha": float(fractional["alpha"]), "beta": float(fractional["beta"]), + "S": np.asarray(fractional["S"](grid)).tolist()}) + + weights = self.fit_state.scenario_weights.get(scenario, self.fit_state.weights) + design = self.fit_state.design + X_dum, X_int = design.encode(df) + rng = np.random.default_rng(s.seed + 1) + replicas = self.fit_state.replicas[: n_boot if n_boot is not None else len(self.fit_state.replicas)] + started, boots = time.monotonic(), [] + P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels) + point = [np.cumprod(P_lr, axis=1).mean(0), np.cumprod(P_hb, axis=1).mean(0), sm.mix(P_lr, P_hb, weights).mean(0)] + for fits in replicas: + pick = rng.integers(0, len(df), len(df)) + Pl, Ph = sm.apply_intervals(fits, X_dum[pick], X_int[pick], design.levels) + boots.append(np.concatenate([np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0), + sm.mix(Pl, Ph, weights).mean(0)])) + ic = np.percentile(np.array(boots), [2.5, 97.5], axis=0) if boots else np.full((2, 3 * len(s.horizons)), np.nan) + for j, name in enumerate(("LR", "HBN", "COMB")): + for i, h in enumerate(s.horizons): + k = j * len(s.horizons) + i + record["points"].append({"model": name, "months": int(h), "S": float(point[j][i]), + "low": float(ic[0, k]), "high": float(ic[1, k])}) + record["seconds"] = round(time.monotonic() - started, 2) + return record + + +def fit(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, survival: SurvivalSettings, index: dict | None, + n_boot: int | None = None, on_progress=None) -> SeerSurvivalModel: + """The model fitted on `recoded` members (all the dictionary's columns) whose covariates are those of `depurated`.""" + s = survival + kept = [c for c in depurated.columns if c.endswith("_cat")] + frame = sc.survival_frame(depurated, s) + cohort = sc.sv_cohort(frame, s) + N = len(cohort.months) + everyone = np.arange(N) + oof_lr, oof_hb = sm.out_of_fold(cohort, s, N) + weights = sm.stacking_weights(cohort, s, np.ones(N, bool), oof_lr, oof_hb)["w_LR"].values + point = sm.fit_kept_intervals(cohort, s, everyone) + reference = [f.parents for f in point] if s.hbn_parents == "fijos" else None + masks = sc.sv_masks(frame, s, dictionary) + scenario_weights = {name: sm.stacking_weights(cohort, s, mask, oof_lr, oof_hb)["w_LR"].values for name, mask in masks.items()} + rng = np.random.default_rng(s.seed) + replicas = [] + for r in range(s.n_boot if n_boot is None else n_boot): + replicas.append(sm.fit_kept_intervals(cohort, s, rng.integers(0, N, N), reference)) + if on_progress: + on_progress(r + 1) + out_of_sample = sm.mix(oof_lr, oof_hb, weights) + horizon = len(s.horizons) - 1 + deciles = pd.qcut(pd.Series(out_of_sample[:, horizon]).rank(method="first"), 10, labels=False) + calibration = [] + for q in range(10): + pick = (deciles == q).to_numpy() + curve, _, _ = fw.km_curva(cohort.months[pick], cohort.event[pick], int(s.horizons[-1])) + calibration.append({"decile": q + 1, "members": int(pick.sum()), + "predicted": {str(h): float(out_of_sample[pick, i].mean()) for i, h in enumerate(s.horizons)}, + "observed": {str(h): float(curve[int(h)]) for h in s.horizons}}) + state = Fit(point, replicas, weights, scenario_weights, Design.of(frame), N, int(frame.df["evento"].sum()), calibration) + horizons = [h / 12 for h in s.horizons] + return SeerSurvivalModel(dictionary, s, index, state, kept, horizons) diff --git a/models/cama/seer_survival/settings.py b/models/cama/seer_survival/settings.py index 226b281..22259bc 100644 --- a/models/cama/seer_survival/settings.py +++ b/models/cama/seer_survival/settings.py @@ -148,6 +148,7 @@ class SurvivalSettings: ks_sub_max_seconds: int xlim_sub: tuple[float, ...] ylim_sub: dict + subgroups: tuple[dict, ...] = () @property def file_suffix(self) -> str: @@ -211,5 +212,6 @@ def load(path: Path = TOML) -> Settings: categorization=_group(CategorizationSettings, raw["categorization"]), bootstrap=_group(BootstrapSettings, raw["bootstrap"]), modeling=_group(ModelingSettings, raw["modeling"]), - survival=_group(SurvivalSettings, raw["survival"]), + survival=_group(SurvivalSettings, {**raw["survival"], + "subgroups": tuple(raw["survival"].get("subgroups", ()))}), risk_factors=_group(RiskFactorSettings, raw["risk_factors"])) diff --git a/models/cama/seer_survival/survival_curves.py b/models/cama/seer_survival/survival_curves.py index ac7bd3b..f9217d1 100644 --- a/models/cama/seer_survival/survival_curves.py +++ b/models/cama/seer_survival/survival_curves.py @@ -18,6 +18,7 @@ from sklearn.linear_model import LogisticRegression from models.cama.seer_survival import fractional_weibull as fw from models.cama.seer_survival import scenarios from models.cama.seer_survival import survival_models as sm +from models.cama.seer_survival import variables from models.cama.seer_survival.settings import SurvivalSettings STYLE = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")} @@ -82,10 +83,14 @@ def _age_midpoint(v): # ---------------------------------------------------------------- the cohort def sv_frame(depurated_csv: str, survival: SurvivalSettings) -> SurvivalFrame: + return survival_frame(pd.read_csv(depurated_csv, dtype=str), survival) + + +def survival_frame(df: pd.DataFrame, survival: SurvivalSettings) -> SurvivalFrame: """The cohort with follow-up truncated at `cap_months` (later deaths count as alive), its covariates and, when no categorical age column exists, the grouped age `Edad_cat`.""" s = survival - df = pd.read_csv(depurated_csv, dtype=str) + df = df.copy() col_months, col_vital = _find_col(df, ["survival months"]), _find_col(df, ["vital status"]) assert col_months and col_vital, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV." df["meses"] = pd.to_numeric(df[col_months], errors="coerce") @@ -323,9 +328,31 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np. # ---------------------------------------------------------------- subgroups -def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]: - """Each clinical scenario's mask over the cohort (`scenarios.masks`): every condition of the scenario must hold.""" - return scenarios.masks(sv_frame.df) +def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings, dictionary: dict | None = None) -> dict[str, np.ndarray]: + """Each clinical scenario's mask over the cohort: the `subgroups` of the settings over the variable dictionary when + both are given, else `scenarios.masks`. Every condition of a scenario must hold.""" + if not (survival.subgroups and dictionary): + return scenarios.masks(sv_frame.df) + df = sv_frame.df + masks = {} + for spec in survival.subgroups: + mask = np.ones(len(df), bool) + for condition in spec["conditions"]: + name = condition["variable"] + if name == "Edad": + values = df["_edad"].astype(float) + else: + values = df[variables.column_of(name, dictionary[name])].astype(str) + if "contains" in condition: + mask &= values.str.contains(condition["contains"], regex=False).to_numpy() + if "in" in condition: + mask &= values.isin(condition["in"]).to_numpy() + if "ge" in condition: + mask &= (values >= condition["ge"]).to_numpy() + if "lt" in condition: + mask &= (values < condition["lt"]).to_numpy() + masks[spec["name"]] = mask + return masks def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None, diff --git a/models/cama/seer_survival/survival_models.py b/models/cama/seer_survival/survival_models.py index 62a4053..0cfaa69 100644 --- a/models/cama/seer_survival/survival_models.py +++ b/models/cama/seer_survival/survival_models.py @@ -279,3 +279,42 @@ def adjusted_curve(c: Cohort, idx, T: int, step: int) -> np.ndarray: S_b.append(S_i.mean()) S_b = np.minimum.accumulate(np.array(S_b)) return np.exp(np.interp(np.arange(T + 1), borders, np.log(np.maximum(S_b, 1e-12)))) + + +# ---------------------------------------------------------------- fitted models that can be kept and applied later + +@dataclass(frozen=True, eq=False) +class IntervalFit: + """One interval's fitted LR (coefficients, intercept) and HBN (parents and the table of P(survives | parents)).""" + + coef: np.ndarray + intercept: float + parents: list[int] + cpt: np.ndarray + + +def fit_kept_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None) -> list[IntervalFit]: + """The per-interval LR and HBN `interval_predictions` fits on the patients of `idx`, kept instead of applied.""" + m, e = c.months[idx], c.event[idx] + fits = [] + for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])): + sel = np.where(m >= a)[0] + y = np.where(e[sel] & (m[sel] < b), 0, 1) + w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) + lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w) + chosen, cpt = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i]) + fits.append(IntervalFit(lr.coef_[0].copy(), float(lr.intercept_[0]), list(chosen), cpt)) + return fits + + +def apply_intervals(fits: list[IntervalFit], X_dum: np.ndarray, X_int: np.ndarray, levels) -> tuple[np.ndarray, np.ndarray]: + """(LR, HBN): each patient's probability of surviving each interval.""" + P_lr = np.column_stack([1 / (1 + np.exp(-(X_dum @ f.coef + f.intercept))) for f in fits]) + P_hb = np.column_stack([predict_hbn((f.parents, f.cpt), X_int, levels) for f in fits]) + return P_lr, P_hb + + +def mix(P_lr: np.ndarray, P_hb: np.ndarray, weights) -> np.ndarray: + """The combined survival at each horizon: each interval's LR and HBN probabilities mixed by `weights`, accumulated.""" + W = np.asarray(weights)[None, :] + return np.cumprod(W * P_lr + (1 - W) * P_hb, axis=1) diff --git a/models/cama/seer_survival/variables.py b/models/cama/seer_survival/variables.py new file mode 100644 index 0000000..44e31c9 --- /dev/null +++ b/models/cama/seer_survival/variables.py @@ -0,0 +1,167 @@ +"""The variable dictionary (`[variables]` of `model.toml`) applied to a cohort's events: one row per patient with the +columns the six stages read (the `_cat` columns, the age band, the tumour size, the diagnosis year, the follow-up and the +vital status). Nothing about a variable is written here: its rules, categories and the columns it makes are the +dictionary's. + +A cohort is the long frame of `COHORT_SCHEMA`: one row per member and event, with the member's `fecha_indice`. A +variable reads the latest event of each `source` (`tipo`) up to `window_days_after_index` after the index; its rules +are tried in order and the first that holds gives the category, `missing` when none does. +""" + +import tomllib +from datetime import date, timedelta +from pathlib import Path + +import numpy as np +import pandas as pd + +TOML = Path(__file__).with_name("model.toml") + + +def load(path: Path = TOML) -> dict: + return tomllib.loads(Path(path).read_text(encoding="utf-8"))["variables"] + + +def variable_names(dictionary: dict) -> list[str]: + return [n for n, v in dictionary.items() if isinstance(v, dict) and "rules" in v] + + +def output_columns(dictionary: dict) -> list[str]: + """The columns the dictionary makes, in its order: every variable that is not internal, the tumour's raw size, the + age band and the follow-up columns.""" + index = dictionary["index"] + columns = [index["id_column"], index["year_column"], index["age_column"]] + for name in variable_names(dictionary): + spec = dictionary[name] + if spec.get("internal"): + continue + columns.append(column_of(name, spec)) + if "raw_column" in spec: + columns.append(spec["raw_column"]) + return columns + [index["months_column"], index["vital_column"]] + + +def column_of(name: str, spec: dict) -> str: + return spec.get("column", f"{name}_cat") + + +def _latest(events: pd.DataFrame, source: str, numeric: bool) -> pd.Series: + """Each patient's latest event of this kind (by date, then source id): its value, indexed by `pac_id`.""" + rows = events[events["tipo"] == source] + if numeric: + rows = rows[rows["valor_numerico"].notna()] + column = "valor_numerico" + else: + rows = rows[rows["valor_codigo"].notna()] + column = "valor_codigo" + rows = rows.sort_values(["fecha", "fuente_id"], kind="stable") + return rows.groupby("pac_id")[column].last() + + +def _present(events: pd.DataFrame, source: str) -> pd.Series: + return pd.Series(True, index=events.loc[events["tipo"] == source, "pac_id"].unique()) + + +class Reader: + """Evaluates conditions over the patients' events, caching each source's per-patient value.""" + + def __init__(self, events: pd.DataFrame, patients: pd.Index, made: dict[str, pd.Series]): + self.events, self.patients, self.made = events, patients, made + self._cache: dict[tuple, pd.Series] = {} + + def value(self, source: str, numeric: bool) -> pd.Series: + key = (source, numeric) + if key not in self._cache: + self._cache[key] = _latest(self.events, source, numeric).reindex(self.patients) + return self._cache[key] + + def present(self, source: str) -> pd.Series: + key = (source, "present") + if key not in self._cache: + self._cache[key] = _present(self.events, source).reindex(self.patients, fill_value=False).astype(bool) + return self._cache[key] + + def holds(self, condition: dict) -> np.ndarray: + if "variable" in condition: + return self.made[condition["variable"]].isin(condition["codes"]).to_numpy() + source = condition["source"] + if condition.get("present"): + return self.present(source).to_numpy() + if "codes" in condition: + return self.value(source, False).isin(condition["codes"]).to_numpy() + number = self.value(source, True) + ok = number.notna() + if "ge" in condition: + ok &= number >= condition["ge"] + if "lt" in condition: + ok &= number < condition["lt"] + return ok.to_numpy() + + +def category_of(spec: dict, reader: Reader) -> pd.Series: + out = pd.Series(spec["missing"], index=reader.patients, dtype=object) + decided = np.zeros(len(reader.patients), bool) + for rule in spec["rules"]: + conditions = rule["when"] if "when" in rule else [rule] + holds = np.ones(len(reader.patients), bool) + for condition in conditions: + holds &= reader.holds(condition) + take = holds & ~decided + out[take] = rule["then"] + decided |= take + return out + + +def _band(age: pd.Series, index: dict) -> pd.Series: + width, open_from = index["age_band_years"], index["age_open_from"] + low = (np.floor(age / width) * width).clip(lower=0) + closed = [index["age_label"].format(low=int(a), high=int(a) + width - 1) if pd.notna(a) else None for a in low] + opened = index["age_open_label"].format(low=open_from) + label = pd.Series(closed, index=age.index, dtype=object) + label[age >= open_from] = opened + return label.fillna(index["age_unknown"]) + + +def recode(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame: + """One row per patient of the cohort, in the columns of `output_columns`.""" + index = dictionary["index"] + window = timedelta(days=int(dictionary["window_days_after_index"])) + frame = cohort.copy() + frame["fecha"] = pd.to_datetime(frame["fecha"]) + frame["fecha_indice"] = pd.to_datetime(frame["fecha_indice"]) + patients = pd.Index(sorted(frame["pac_id"].unique()), name="pac_id") + start = frame.groupby("pac_id")["fecha_indice"].first().reindex(patients) + visible = frame[frame["fecha"] <= frame["pac_id"].map(start) + window] + + reader = Reader(visible, patients, {}) + for name in variable_names(dictionary): + reader.made[name] = category_of(dictionary[name], reader) + + birth = frame[frame["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients) + death = frame[frame["tipo"] == index["death_source"]].groupby("pac_id")["fecha"].min().reindex(patients) + last = frame.groupby("pac_id")["fecha"].max().reindex(patients) + end = death.fillna(last) + days = (end - start).dt.days + age = (start - birth).dt.days / 365.25 + + result = pd.DataFrame(index=patients) + result[index["id_column"]] = patients.to_numpy() + result[index["year_column"]] = start.dt.year.astype(str) + result[index["age_column"]] = _band(age, index) + for name in variable_names(dictionary): + spec = dictionary[name] + if spec.get("internal"): + continue + result[column_of(name, spec)] = reader.made[name] + if "raw_column" in spec: + size = reader.value(spec["source"], True) + result[spec["raw_column"]] = [spec["raw_format"].format(v) if pd.notna(v) else spec["raw_missing"] + for v in size] + result[index["months_column"]] = (days / index["days_per_month"]).round().astype(int).astype(str) + result[index["vital_column"]] = np.where(death.notna(), index["dead"], index["alive"]) + return result[output_columns(dictionary)].reset_index(drop=True) + + +def diagnosis_date(year: int, dictionary: dict) -> date: + month, day = dictionary["index"]["seer_diagnosis_month_day"].split("-") + return date(int(year), int(month), int(day)) diff --git a/models/dags/training.py b/models/dags/training.py index b098336..dd8bf9e 100644 --- a/models/dags/training.py +++ b/models/dags/training.py @@ -47,6 +47,8 @@ class Scenario: config: dict folder: Path requirements: tuple[str, ...] = () + # Tables of `model.toml` outside `[config]` that still make a version a different one (`settings_tables`). + tables: dict | None = None @classmethod def from_toml(cls, path: str | Path) -> "Scenario": @@ -55,7 +57,8 @@ class Scenario: return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"], outcome=found["outcome"], description=found.get("description", ""), modules=tuple(import_module(name) for name in found["modules"]), config=found["config"], - folder=path.parent, requirements=tuple(found.get("requirements", ()))) + folder=path.parent, requirements=tuple(found.get("requirements", ())), + tables={name: found[name] for name in found.get("settings_tables", ())} or None) @classmethod def load(cls, domain: str, scenario: str) -> "Scenario": @@ -67,7 +70,8 @@ class Scenario: return cls.from_toml(Path(package.__file__).parent / "model.toml") def config_sha256(self) -> str: - return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest() + content = self.config if not self.tables else {"config": self.config, **self.tables} + return hashlib.sha256(json.dumps(content, sort_keys=True, default=str).encode()).hexdigest() def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver: diff --git a/models/steps/indexing.py b/models/steps/indexing.py index 46d2c62..9447af1 100644 --- a/models/steps/indexing.py +++ b/models/steps/indexing.py @@ -28,6 +28,9 @@ earlier events ("no CIN2+ before the index", "first colposcopy", the referral ye with enough history makes them valid without changing code. Observation starts, for now, at the patient's first event in the frame (the platform's `periodo_observacion` doesn't reach the pipeline). +- `primera_biopsia_invasora` (CaMa): the first biopsy reported as invasive carcinoma, if it falls in the window; no + rules. The cohort is read whole, not patient by patient (`VECTORIZED`). + A scenario without `[config.index]` keeps its cohort's own index. """ @@ -146,6 +149,24 @@ KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposc "primera_biopsia_invasora": _first_invasive_biopsy} +def _first_invasive_biopsy(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]: + """(members, attrition) of the kind `primera_biopsia_invasora`, from the whole frame.""" + biopsies = cohort[(cohort["tipo"] == "biopsia") & (cohort["valor_codigo"] == index.get("invasive_code", "CARCINOMA_INVASOR"))] + first = pd.to_datetime(biopsies["fecha"]).groupby(biopsies["pac_id"]).min() + start, end = index.get("recruitment_start"), index.get("recruitment_end") + inside = pd.Series(True, index=first.index) + if start is not None: + inside &= first >= pd.Timestamp(start) + if end is not None: + inside &= first < pd.Timestamp(end) + members = first[inside].rename("fecha_indice").dt.date.rename_axis("pac_id").reset_index() + return members, [("pacientes", int(cohort["pac_id"].nunique())), ("indexed", len(members))] + + +# Kinds read from the whole frame: (cohort, index) -> (members, attrition), for cohorts too large to take apart by patient. +VECTORIZED = {"primera_biopsia_invasora": _first_invasive_biopsy} + + def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]: events = defaultdict(list) for e in cohort.to_dict("records"): @@ -161,6 +182,8 @@ def _prior_days(rows: list[dict], fecha: date) -> int: def _indexed_members(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]: """(members, attrition): one row per member (`pac_id`, `fecha_indice`), and how many are left after the index and after each rule, in order; each rule is charged only for those it removes from what it receives.""" + if index["kind"] in VECTORIZED: + return VECTORIZED[index["kind"]](cohort, index) rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0)) events = _events(cohort) found = {} @@ -207,6 +230,12 @@ def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index: if not index: return {} members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index)) + if index["kind"] in VECTORIZED: + first = pd.to_datetime(source_cohort["fecha"]).groupby(source_cohort["pac_id"]).min() + days = (pd.to_datetime(members["fecha_indice"]) - first.reindex(members["pac_id"]).to_numpy()).dt.days.astype(float) + return {"members": len(days), "under_365_days": int((days < 365).sum()), + "median_days": None if days.empty else float(days.median()), + "threshold_days": int(index.get("observacion_previa_minima_dias", 0))} events = _events(source_cohort) days = pd.Series([_prior_days(events[int(p)], f) for p, f in members.itertuples(index=False)], dtype=float) return {"members": len(days), "under_365_days": int((days < 365).sum()),