diff --git a/models/cama/recurrence/__init__.py b/models/cama/recurrence/__init__.py index df4db1f..6a62d7d 100644 --- a/models/cama/recurrence/__init__.py +++ b/models/cama/recurrence/__init__.py @@ -1,11 +1,9 @@ -"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months, -learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their -published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic -regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated -(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios -with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by -four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's, -refitted on each whole horizon cohort.""" +"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned +from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian +network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator +gives the recurrence-free probability of clinical scenarios with bootstrap intervals and +survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports +gives the tables and figures.""" from dataclasses import dataclass @@ -15,15 +13,7 @@ import pandas as pd from models.cama.recurrence import calculator, cohorts, factors, modeling, reports -SOURCES = ("metabric", "scanb") HORIZONS = modeling.HORIZONS # months -SAVED = "metabric" - - -def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame: - """The source's cohort table, from its dataset's rows: fixed columns, then its - covariates as categories.""" - return cohorts.prepare(source, rows).frame @dataclass @@ -59,27 +49,35 @@ class Recurrence: return pd.DataFrame(out, index=X.index) -def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: - """Both cohorts' models, validation, calculator and risk factors, from their datasets' - rows. - Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors' - stability criterion, are then missing).""" - found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES} - n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {} +def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: + """The model of the site's own cohort (models.cama.recurrence.site), its metrics and its + reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk + factors' stability criterion, are then missing).""" + from models.cama.recurrence import site + + return fit({"site": site.prepare(rows)}, "site", "site", + modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip + + +def fit(found: dict, saved: str, label: str, + n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip + """The models of each prepared cohort, their validation, calculator and risk factors; + the `saved` cohort's is the model kept.""" + sources = list(found) try: fits = modeling.fit(found, n_bootstrap) - drawn = {s: calculator.calculator(fits[s]) for s in SOURCES} + drawn = {s: calculator.calculator(fits[s]) for s in sources} finally: joblib.externals.loky.get_reusable_executor().shutdown(wait=True) - table = pd.concat([factors.risk_factors(fits[s]) for s in SOURCES], ignore_index=True) - summary = [row for s in SOURCES for row in factors.scenario_summary(fits[s], table)] - auc = [row for s in SOURCES for row in reports.auc_rows(fits[s])] - points = [row for s in SOURCES for row in drawn[s][1]] - saved = fits[SAVED] - model = Recurrence(SAVED, HORIZONS, saved.cohort.covariates, modeling.tables(saved)) + table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True) + summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)] + auc = [row for s in sources for row in reports.auc_rows(fits[s])] + points = [row for s in sources for row in drawn[s][1]] + kept = fits[saved] + model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept)) technical = { "model": "recurrence", - "cohort": "metabric+scanb", + "cohort": label, "method": "stepwise logistic regression + Bayesian network (BDeu), averaged", "rutinas": reports.routines(found, n_bootstrap), "recurrencia_desarrollo": reports.development(auc, table, points, summary), @@ -87,7 +85,7 @@ def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurr interpretability = { "model": "recurrence", "kind": "scenarios", - "recurrencia": reports.figures([r for s in SOURCES for r in drawn[s][0]]), + "recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]), } reports_ = {"technical_validation": technical, "interpretability": interpretability} return model, reports.metrics(auc), reports_ diff --git a/models/cama/recurrence/calculator.py b/models/cama/recurrence/calculator.py index 506d93a..2a69a06 100644 --- a/models/cama/recurrence/calculator.py +++ b/models/cama/recurrence/calculator.py @@ -21,44 +21,6 @@ RESAMPLES = 200 MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences CAP_MONTHS = 72 # the Weibull curves' extent GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months -LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"} - -# Each scenario: covariate -> the categories it takes (AND across covariates). -SCENARIOS = { - "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"]}, - }, -} # fmt: skip def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: @@ -142,10 +104,10 @@ def _curves(months, event, observed): } -def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]: +def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]: """The figure record of each scenario with enough recurrences, and its table rows.""" source = fitted.cohort.source - scenarios = SCENARIOS[source] if scenarios is None else scenarios + scenarios = fitted.cohort.scenarios risk = Risk(fitted) found = masks(fitted.cohort.frame, scenarios) rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel @@ -168,7 +130,7 @@ def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[d records.append( { "cohorte": source, - "cohorte_nombre": LABELS[source], + "cohorte_nombre": fitted.cohort.label, "escenario": name, "condiciones": scenarios[name], "n": n, diff --git a/models/cama/recurrence/cohorts.py b/models/cama/recurrence/cohorts.py index 21cffda..082a7b6 100644 --- a/models/cama/recurrence/cohorts.py +++ b/models/cama/recurrence/cohorts.py @@ -1,10 +1,8 @@ -"""Each reference cohort as one table of categories, from its dataset as the platform loaded -it (the `cama_reference` pipeline: every value as written, column names as dlt names them, -`line` the order the file is published in): the patients with a known recurrence time and -status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their -covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN); -nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's -V >= V_MAX), the one with more unknowns is dropped.""" +"""A cohort as one table of categories: the patients with a known recurrence time and status, +their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their covariates +as text. A missing or out-of-range value is a category of its own (UNKNOWN); nothing is imputed +or dropped for it. Of each pair of nearly redundant covariates (Cramér's V >= V_MAX), the one +with more unknowns is dropped.""" from dataclasses import dataclass @@ -14,6 +12,7 @@ from scipy.stats.contingency import association UNKNOWN = "Desconocido" V_MAX = 0.80 DAYS_PER_MONTH = 30.4375 +HORIZONS = (12, 36, 60) # months # Bands, closed on the left: [a, b). AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) @@ -21,37 +20,6 @@ SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]) NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"]) GRADES = {"1": "1", "2": "2", "3": "3"} -FIXED = { - "metabric": ["paciente", "tiempo_meses", "evento"], - "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], -} -TREATMENT = { - "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], - "scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], -} -# Covariates taken as they come (our name: the dataset's column). -PASSTHROUGH = { - "metabric": { - "Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status", - "HER2": "her2_status", "Subtipo_PAM50": "pam50_x_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", - }, - "scanb": { - "Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2", - "Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology", - "Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality", - "Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type", - "Quimioterapia": "chemotherapy", "Radioterapia": "radiation", - "Hormonoterapia": "endocrine", "AntiHER2": "anti_her2", - }, -} # fmt: skip -SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} -SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} - def _number(s: pd.Series) -> pd.Series: return pd.to_numeric(s, errors="coerce") @@ -66,47 +34,6 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series: return _text(pd.cut(s, edges, labels=labels, right=False).astype(object)) -def _in_order(rows: pd.DataFrame) -> pd.DataFrame: - return rows.sort_values("line", kind="stable").reset_index(drop=True) - - -def _metabric(rows: pd.DataFrame) -> pd.DataFrame: - d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"]) - d = d.reset_index(drop=True) - out = pd.DataFrame({"paciente": d["patient_id"]}) - out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"]) - out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int) - out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE) - out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE) - out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES) - out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES)) - # Mutational load in tertiles of this cohort; a value on a cut falls in the lower band. - load = _number(d["mutation_count"]) - q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() - edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6] - out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"]) - for name, column in PASSTHROUGH["metabric"].items(): - out[name] = _text(d[column]) - return out - - -def _scanb(rows: pd.DataFrame) -> pd.DataFrame: - d = _in_order(rows) - d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True) - rfi, died = _number(d["rfi_event"]), _number(d["os_event"]) - out = pd.DataFrame({"paciente": d["patient_name"]}) - out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH - out["evento"] = rfi.astype(int) - out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int) - out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle - out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE) - out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES)) - out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES)) - for name, column in PASSTHROUGH["scanb"].items(): - out[name] = _text(d[column]) - return out - - def cramers_v(a: pd.Series, b: pd.Series) -> float: table = pd.crosstab(a, b).to_numpy() return association(table, method="cramer") if min(table.shape) > 1 else 0.0 @@ -143,21 +70,15 @@ class Cohort: covariates: list[str] treatment: list[str] eliminated: list[str] + label: str # as the reports name it + scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories + sampling: dict # how its patients were chosen (the MUESTREO record) @property def intrinsic(self) -> list[str]: return [c for c in self.covariates if c not in self.treatment] -def prepare(source: str, raw: pd.DataFrame) -> Cohort: - full = {"metabric": _metabric, "scanb": _scanb}[source](raw) - fixed, treatment = FIXED[source], TREATMENT[source] - covariates = [c for c in full.columns if c not in fixed] - dropped = collinear(full, [c for c in covariates if c not in treatment]) - kept = [c for c in covariates if c not in dropped] - return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped) - - def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: """The patients whose status at `horizon` months is known (a recurrence by then, or followed past it), with `y` = recurred by then.""" diff --git a/models/cama/recurrence/factors.py b/models/cama/recurrence/factors.py index 3b07781..2d6201d 100644 --- a/models/cama/recurrence/factors.py +++ b/models/cama/recurrence/factors.py @@ -1,35 +1,20 @@ -"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has. - -Each category of an intrinsic covariate (not a treatment) is rated against its covariate's -most frequent category by four criteria: (1) its adjusted odds ratio's 95 % CI excludes 1 and -its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least FREQ_MIN of -the time; (3) its covariate is a parent of the HBN; (4) its Kaplan-Meier recurrence-free -survival at the horizon differs from the reference's (95 % CI) in the odds ratio's direction. -"Robusto" needs (1) and three criteria, "sugerente" two. Treatments get their odds ratios, -adjusted for the intrinsic covariates, but no class: they are associations, not effects.""" +"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has +(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2), +the horizon's HBN parents give (3)).""" import warnings import numpy as np import pandas as pd -import statsmodels.api as sm -from scipy.stats import false_discovery_control -from models.cama.recurrence.calculator import SCENARIOS, masks +from models import factors as rated +from models.cama.recurrence.calculator import masks from models.cama.recurrence.cohorts import UNKNOWN, at_horizon -from models.cama.recurrence.modeling import CohortFit, variable_of -from models.curves import life_table +from models.cama.recurrence.modeling import CohortFit +from models.factors import FREQ_MIN, ORDER -ALPHA = 0.05 -FREQ_MIN = 0.80 -Z = 1.96 -ORDER = { - "riesgo robusto": 0, - "protector robusto": 1, - "riesgo sugerente": 2, - "protector sugerente": 3, - "no concluyente": 4, -} +OR = "OR_recurrencia" +SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S") TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" COLUMNS = [ "cohorte", @@ -39,16 +24,14 @@ COLUMNS = [ "categoria", "referencia", "n_categoria", - "OR_recurrencia", + OR, "IC95_inf", "IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", - "S_libre_categoria", - "S_libre_referencia", - "delta_S", + *SURVIVAL, "delta_IC95_inf", "delta_IC95_sup", "c1_or", @@ -58,39 +41,7 @@ COLUMNS = [ "criterios_cumplidos", "clasificacion", ] -# Scenario presence: the share of the scenario's patients in the category. -DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10 -DESCRIBING = ("definitoria", "mayoritaria") - - -def km_at(months, event, horizon) -> tuple[float, float]: - """Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE.""" - d, _, n = life_table(months, event) - q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) - v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0) - last = min(horizon, len(d) - 1) + 1 - S = float(np.prod(q[:last])) - return S, S * float(np.sqrt(np.sum(v[:last]))) - - -def _odds_ratios(data: pd.DataFrame, y, variables, reference) -> pd.DataFrame: - """Logistic GLM on every category but each covariate's reference (constant and - duplicated dummies dropped): odds ratios with Wald 95 % CI and p.""" - X = pd.get_dummies(data[variables]).astype(float) - X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables]) - X = X.loc[:, X.nunique() > 1] - X = X.loc[:, ~X.T.duplicated()] - m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit() - ci = np.exp(m.conf_int().loc[X.columns]) - return pd.DataFrame( - { - "termino": X.columns, - "OR_recurrencia": np.exp(m.params[X.columns].to_numpy()), - "IC95_inf": ci[0].to_numpy(), - "IC95_sup": ci[1].to_numpy(), - "p": m.pvalues[X.columns].to_numpy(), - } - ) +DESCRIBING = rated.DESCRIBING def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame: @@ -103,72 +54,23 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy() def complete(table, variables): - """Each term's covariate, category, BH p and survival difference to its reference.""" - table = table.reset_index(drop=True) - table["variable"] = [variable_of(x, variables) for x in table["termino"]] - table["categoria"] = [ - x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True) - ] - table["referencia"] = table["variable"].map(reference) - table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else [] - rows = [] - for v, cat, ref in zip( - table["variable"], table["categoria"], table["referencia"], strict=True - ): - a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == ref).to_numpy() - (sa, ea), (sb, eb) = ( - km_at(months[a], event[a], horizon), - km_at(months[b], event[b], horizon), - ) - delta, se = sa - sb, np.sqrt(ea**2 + eb**2) - rows.append( - { - "n_categoria": int(a.sum()), - "S_libre_categoria": sa, - "S_libre_referencia": sb, - "delta_S": delta, - "delta_IC95_inf": delta - Z * se, - "delta_IC95_sup": delta + Z * se, - } - ) - return pd.concat([table, pd.DataFrame(rows)], axis=1) + return rated.complete(table, variables, reference, everyone, months, event, horizon, + SURVIVAL) # fmt: skip intrinsic, treatment = cohort.intrinsic, cohort.treatment - tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic) - risk = tab["OR_recurrencia"] > 1 - tab["direccion"] = np.where(risk, "riesgo", "protector") - tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA) - excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0) - tab["c4_supervivencia"] = excludes_zero & (np.sign(tab["delta_S"]) == np.where(risk, -1, 1)) + tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic) hz = fitted.horizons[horizon] tab["freq_seleccion_bootstrap"] = tab["variable"].map( lambda v: np.nan if selection is None else selection.get(v, 0.0) ) tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents) - criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"] - tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1) - tab["clasificacion"] = [ - "no aplica (categoria desconocida)" - if cat == UNKNOWN - else f"{d} robusto" - if c1 and k >= 3 - else f"{d} sugerente" - if k >= 2 - else "no concluyente" - for cat, d, c1, k in zip( - tab["categoria"], - tab["direccion"], - tab["c1_or"], - tab["criterios_cumplidos"], - strict=True, - ) - ] + tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN) tab["tipo"] = "factor de riesgo" if treatment: both = intrinsic + treatment - tr = _odds_ratios(data, y, both, reference) - of = tr["termino"].map(lambda x: variable_of(x, both)) + tr = rated.odds_ratios(data, y, both, reference, OR) + of = tr["termino"].map(lambda x: rated.variable_of(x, both)) tr = complete( tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment ) @@ -191,72 +93,26 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra tab = pd.concat(found, ignore_index=True) tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5) - keys = ["horizonte_meses", "_kind", "_order", "OR_recurrencia"] + keys = ["horizonte_meses", "_kind", "_order", OR] tab = tab.sort_values(keys, ascending=[True, True, True, False]) return tab[COLUMNS].round(4) -def _presence(share: float) -> str: - if share >= DEFINING: - return "definitoria" - return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria" - - -def _listing(part: pd.DataFrame) -> str: - """`variable=category (strength, share)`, `;`-separated; a treatment's strength is - `asociacion`.""" - strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion", - part["clasificacion"].str.split().str[-1]) # fmt: skip - return "; ".join( - f"{v}={c} ({s}, {p:.0%})" - for v, c, s, p in zip( - part["variable"], part["categoria"], strength, part["share"], strict=True - ) - ) - - def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: """Per scenario and horizon, the classified factors and treatments nearly all of its patients have (definitorios) or most have (mayoritarios).""" frame, source = fitted.cohort.frame, fitted.cohort.source - scenarios = SCENARIOS[source] - found = factors[ - (factors["cohorte"] == source) - & factors["clasificacion"].str.contains("robusto|sugerente|tratamiento") - ] - kind = np.where( - found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0] - ) - found = found.assign(tipo_efecto=kind) + scenarios = fitted.cohort.scenarios + found = rated.classified(factors[factors["cohorte"] == source]) rows = [] for name, mask in masks(frame, scenarios).items(): if not mask.any() or found.empty: continue - share = [ - float((frame.loc[mask, v] == c).mean()) - for v, c in zip(found["variable"], found["categoria"], strict=True) - ] - detail = found.assign(share=share, presence=[_presence(s) for s in share]) definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items()) for h in fitted.horizons: - d = detail[detail["horizonte_meses"] == h] - row = { - "cohorte": source, - "escenario": name, - "definicion": definition, - "n_escenario": int(mask.sum()), - "horizonte_meses": h, - } - for k in ("riesgo", "protector", "tratamiento"): - for level, label in ( - ("definitoria", "definitorios"), - ("mayoritaria", "mayoritarios"), - ): - row[f"{k}_{label}"] = _listing( - d[(d["tipo_efecto"] == k) & (d["presence"] == level)] - ) - included = (d["tipo_efecto"] == "riesgo") & d["presence"].isin(DESCRIBING) - row["n_factores_riesgo_incluidos"] = int(included.sum()) - row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0 - rows.append(row) + rows.append({ + "cohorte": source, "escenario": name, "definicion": definition, + "n_escenario": int(mask.sum()), "horizonte_meses": h, + **rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]), + }) # fmt: skip return rows diff --git a/models/cama/recurrence/modeling.py b/models/cama/recurrence/modeling.py index c668c44..8ee2915 100644 --- a/models/cama/recurrence/modeling.py +++ b/models/cama/recurrence/modeling.py @@ -20,9 +20,9 @@ from pgmpy.structure_score import BDeu from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split -from models.cama.recurrence.cohorts import Cohort, at_horizon +from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon +from models.factors import variable_of -HORIZONS = (12, 36, 60) # months SEED = 42 TEST_SIZE = 0.3 ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count @@ -31,7 +31,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15 MAX_STEPS = 200 COX_PENALIZER = 0.05 COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side -N_BOOTSTRAP = {"metabric": 100, "scanb": 40} +N_BOOTSTRAP = {"site": 40} # ---------------------------------------------------------------- logistic regression @@ -203,12 +203,6 @@ def c_index(cohort: Cohort) -> float: return float(concordance_index(test["tiempo_meses"], -risk, test["evento"])) -def variable_of(term: str, covariates: list[str]) -> str: - """The covariate a dummy belongs to (the longest name it starts with).""" - found = [c for c in covariates if term.startswith(c + "_")] - return max(found, key=len) if found else term - - @dataclass class Horizon: """A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each diff --git a/models/cama/recurrence/reports.py b/models/cama/recurrence/reports.py index 8d38f40..389631d 100644 --- a/models/cama/recurrence/reports.py +++ b/models/cama/recurrence/reports.py @@ -15,7 +15,6 @@ from models.cama.recurrence.modeling import ( ESS, HORIZONS, MAX_PARENTS, - N_BOOTSTRAP, CohortFit, ) @@ -109,8 +108,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: } for s, c in cohorts.items() }, - "criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", - "origen": "METABRIC y SCAN-B (externas)", + **next(iter(cohorts.values())).sampling, }, "DATOS_FALTANTES": { "criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); " @@ -137,7 +135,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: "salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por " "bootstrap", "replicas": { - **{s: n_bootstrap.get(s, 0) for s in N_BOOTSTRAP}, + **{s: n_bootstrap.get(s, 0) for s in cohorts}, "calculadora": RESAMPLES, }, "eventos_minimos_por_escenario": MIN_EVENTS, diff --git a/models/cama/recurrence/site.py b/models/cama/recurrence/site.py new file mode 100644 index 0000000..0bca330 --- /dev/null +++ b/models/cama/recurrence/site.py @@ -0,0 +1,146 @@ +"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa +timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy +report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned +from), so the same fits, calculator and risk factors run on it. + +- Time and event: months from the index to her first recurrence (any site) after it, else to + her death, else to the cut-off (the site records its recurrences: a patient without one is + taken as free of it up to then); `muerte_sin_recaida` when she died without one. +- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the + first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN): + age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or + more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate: + Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+, + Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them.""" + +import numpy as np +import pandas as pd + +from models.cama.recurrence import cohorts +from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear + +RESULT_DAYS = 30 +TREATMENT_DAYS = 365 +KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B +STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II", + "III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip +RECEPTOR = {"positive": "Positive", "negative": "Negative"} +SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"} +TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy", + "Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip +FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] +TREATMENT = ["Cirugia", *TREATMENTS] +# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates). +SCENARIOS = { + "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"]}, +} # fmt: skip +MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted +SAMPLING = { + "criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, " + "libre de ella hasta su defunción o la fecha de corte", + "origen": "la sede (sus propias pacientes)", +} + + +def subtype(er, pr, her2, ki67) -> str: + """The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it.""" + hormone = "positive" in (er, pr) + if her2 == "positive": + return "Luminal B HER2+" if hormone else "Non-luminal HER2+" + if her2 != "negative": + return UNKNOWN + if not hormone: + return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN + if ki67 is None or ki67 != ki67: + return UNKNOWN + return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-" + + +def frame(events: pd.DataFrame, as_of) -> pd.DataFrame: + """One row per member: her time, event and covariates, as `cohorts.prepare` gives a + reference cohort's.""" + events = events.assign(date=pd.to_datetime(events["date"]), + index_date=pd.to_datetime(events["index_date"])) # fmt: skip + members = events.groupby("person_id")["index_date"].first() + days = (events["date"] - events["index_date"]).dt.days + cut = pd.Timestamp(as_of) + after = events[(days > 0) & (events["date"] <= cut)] + first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min() + death = events[(events["type"] == "death") & (events["date"] <= cut)] + death = death.groupby("person_id")["date"].min().reindex(members.index) + end = first_recurrence.reindex(members.index).fillna(death).fillna(cut) + out = pd.DataFrame(index=members.index) + out["paciente"] = members.index + out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH + out["evento"] = first_recurrence.reindex(members.index).notna().astype(int) + out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int) + + near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"]) + code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731 + number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731 + birth = events[events["type"] == "birth"].groupby("person_id")["date"].min() + age = (members - birth.reindex(members.index)).dt.days / 365.25 + out["Edad"] = _band(age, *cohorts.AGE) + out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE) + out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index), + *cohorts.NODES) # fmt: skip + out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES)) + receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")} + ki67 = number("ki67_pct").reindex(members.index) + out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR)) + out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR)) + out["HER2"] = _text(receptors["her2"].map(RECEPTOR)) + high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%") + out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index)) + out["Subtipo_clinico"] = [subtype(*a) for a in zip( + receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip + out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index)) + out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP)) + course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)] + given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index) + given = given.apply(lambda g: g if isinstance(g, set) else set()) + out["Cirugia"] = given.apply( + lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None") + ) + for name, kind in TREATMENTS.items(): + out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No") + return out.reset_index(drop=True) + + +def scarce(rows: pd.DataFrame) -> str | None: + """Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS + patients recurred by it, or known free of it), or None.""" + for h in cohorts.HORIZONS: + y = cohorts.at_horizon(rows, h)["y"] + fewest = min(int(y.sum()), int((y == 0).sum())) + if fewest < MIN_PER_CLASS: + return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, " + f"{MIN_PER_CLASS} of each needed") # fmt: skip + return None + + +def prepare(rows: pd.DataFrame) -> Cohort: + """The site's cohort as a reference cohort is prepared: the nearly redundant covariates + dropped (cohorts.collinear) from the model, though kept in the table, since the clinical + scenarios name patients by them (the subtype, built from the receptors and Ki-67, is + redundant by construction).""" + covariates = [c for c in rows.columns if c not in FIXED] + dropped = collinear(rows, [c for c in covariates if c not in TREATMENT]) + kept = [c for c in covariates if c not in dropped] + treatment = [c for c in TREATMENT if c in kept] + return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio", + SCENARIOS, SAMPLING) # fmt: skip diff --git a/models/cama/specs.py b/models/cama/specs.py index 27d097f..b1e65b5 100644 --- a/models/cama/specs.py +++ b/models/cama/specs.py @@ -7,17 +7,16 @@ known at it. A patient who dies before her treatment counts as untreated (immortal-time bias), which the technical report states. Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`. -- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on two public reference - cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the - `cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a - quarter of an hour), so it trains only when asked for by name.""" +- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients + (`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math + (proved on METABRIC and SCAN-B by models/tests/test_recurrence.py).""" from dataclasses import dataclass, field +from datetime import date import pandas as pd -from models.survival import DAYS_PER_YEAR, Spec, age_group, band -from persistance import nodes +from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band # The index report's results (timeline types), read from a week before to RESULT_DAYS after. RESULTS = ("histologic_type", "grade", "er", "pr", "her2") @@ -89,33 +88,43 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: @dataclass(frozen=True) -class ReferenceRecurrence: - """The recurrence model over the reference cohorts the `pipeline` loaded: one source node - per cohort, named as the cohort.""" +class SiteRecurrence: + """The recurrence model on the site's own patients (models.cama.recurrence.site): the + cohort's timelines in, its fits, calculator and risk factors out, with its own reports; + each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in.""" name: str - pipeline: str = "cama_reference" - cohort: None = None # trains on no gold cohort, and scores no patient - slow: bool = True + cohort: str = "cama_cohort_recurrence" + reports: bool = True # it writes its own reports (models.jobs) method: str = field(default="stepwise logistic regression + Bayesian network", init=False) def train(self, events, as_of=None) -> tuple: from models.cama import recurrence + from models.cama.recurrence import site + from models.jobs import EmptyCohort - model, metrics, reports = recurrence.train(self.datasets()) - return model, metrics, reports - - def datasets(self) -> dict[str, pd.DataFrame]: - """Each reference cohort's rows, as the pipeline loaded them.""" - from models.cama import recurrence - - found = {s: pd.DataFrame(nodes.rows(self.pipeline, s)) for s in recurrence.SOURCES} - if any(r.empty for r in found.values()): - raise LookupError(f"load the reference cohorts first (pipeline {self.pipeline})") - return found + rows = site.frame(events, as_of or date.today()) + if reason := site.scarce(rows): + raise EmptyCohort(f"cama.recurrence: {reason}") + return recurrence.train_site(rows) def predict(self, model, events) -> pd.DataFrame: - return model.predict(events) + from models.cama.recurrence import calculator, site + + members = site.frame(events, date.today()) + found = model.predict(members) + index = events.groupby("person_id")["index_date"].first() + masks = calculator.masks(members, site.SCENARIOS) + named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None + for i in range(len(members))] # fmt: skip + rows = [] + for i, person in enumerate(members["paciente"]): + for h in model.horizons: + rows.append({"person_id": person, + "index_date": pd.Timestamp(index[person]).date(), + "horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i], + "ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip + return pd.DataFrame(rows, columns=OUTPUT) MODELS = { @@ -146,6 +155,7 @@ MODELS = { cap_months=24, scenarios=SCENARIOS, scenario_columns=("age",), + treatments=("surgery", "chemotherapy", "radiotherapy"), notes=( f"Tratamiento: el primer curso (convención de SEER), lo recibido en los " f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere " @@ -153,5 +163,5 @@ MODELS = { "efecto protector del tratamiento aparece mayor de lo que es.", ), ), - "recurrence": ReferenceRecurrence("recurrence"), + "recurrence": SiteRecurrence("recurrence"), } diff --git a/models/definitions.py b/models/definitions.py index fc7aedc..70109bc 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -5,6 +5,7 @@ import importlib import inspect import io import json +import os import zipfile from collections.abc import Callable from datetime import date @@ -16,6 +17,7 @@ from models import execution, graph from models.jobs import EmptyCohort from models.tea import jobs as tea_jobs from models.tea import preview as tea_preview_analysis +from persistance import backup as backups from persistance import bundle, cluster, config_log, eeg, previews, silver WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite) @@ -75,7 +77,7 @@ class ReferenceConfig(dg.Config): class Training(dg.Config): domain: str - models: list[str] = [] # default: every model of the domain but the slow ones + models: list[str] = [] # default: every model of the domain as_of: str | None = None # the date the data are taken up to (default: today) execution: ExecutionConfig = ExecutionConfig() reference: ReferenceConfig | None = None @@ -286,7 +288,30 @@ def import_bundle(): import_bundle_files() -defs = dg.Definitions( - jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle], - sensors=[tea_eeg_after_ingest], +@dg.op +def make_backup(context: dg.OpExecutionContext) -> str: + folder = backups.create() + context.log.info(f"backup {folder}") + return str(folder) + + +@dg.job(tags=WRITES) +def backup(): + make_backup() + + +nightly = ( + [ + dg.ScheduleDefinition( + job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING + ) + ] # fmt: skip + if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *")) + else [] +) + +defs = dg.Definitions( + jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle, backup], + sensors=[tea_eeg_after_ingest], + schedules=nightly, ) diff --git a/models/factors.py b/models/factors.py new file mode 100644 index 0000000..455cca5 --- /dev/null +++ b/models/factors.py @@ -0,0 +1,178 @@ +"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models. + +Each category of an intrinsic covariate (not a treatment) is rated against its covariate's +most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes +1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least +FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its +Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's +direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three +criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get +their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations, +not effects. Each clinical scenario then lists the classified factors nearly all of its +patients have (definitorios) or most have (mayoritarios).""" + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.stats import false_discovery_control + +from models.curves import life_table + +ALPHA = 0.05 +FREQ_MIN = 0.80 +Z = 1.96 +CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia") +ORDER = { + "riesgo robusto": 0, + "protector robusto": 1, + "riesgo sugerente": 2, + "protector sugerente": 3, + "no concluyente": 4, +} +UNKNOWN_CLASS = "no aplica (categoria desconocida)" +# Scenario presence: the share of the scenario's patients in the category. +DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10 +DESCRIBING = ("definitoria", "mayoritaria") + + +def variable_of(term: str, covariates: list[str]) -> str: + """The covariate a dummy belongs to (the longest name it starts with).""" + found = [c for c in covariates if term.startswith(c + "_")] + return max(found, key=len) if found else term + + +def km_at(months, event, horizon) -> tuple[float, float]: + """Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE.""" + d, _, n = life_table(months, event) + q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) + v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0) + last = min(horizon, len(d) - 1) + 1 + S = float(np.prod(q[:last])) + return S, S * float(np.sqrt(np.sum(v[:last]))) + + +def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame: + """Logistic GLM on every category but each covariate's reference (constant and + duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p.""" + X = pd.get_dummies(data[variables]).astype(float) + X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables]) + X = X.loc[:, X.nunique() > 1] + X = X.loc[:, ~X.T.duplicated()] + m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit() + ci = np.exp(m.conf_int().loc[X.columns]) + return pd.DataFrame( + { + "termino": X.columns, + name: np.exp(m.params[X.columns].to_numpy()), + "IC95_inf": ci[0].to_numpy(), + "IC95_sup": ci[1].to_numpy(), + "p": m.pvalues[X.columns].to_numpy(), + } + ) + + +def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame, + months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip + """Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at + `horizon` over `everyone` (`names`: the category's, the reference's and the difference's + survival columns).""" + table = table.reset_index(drop=True) + table["variable"] = [variable_of(x, variables) for x in table["termino"]] + table["categoria"] = [ + x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True) + ] + table["referencia"] = table["variable"].map(reference) + table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else [] + category, ref, delta_name = names + rows = [] + for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True): + a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy() + sa, ea = km_at(months[a], event[a], horizon) + sb, eb = km_at(months[b], event[b], horizon) + delta, se = sa - sb, np.sqrt(ea**2 + eb**2) + rows.append({ + "n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta, + "delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se, + }) # fmt: skip + return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name, + "delta_IC95_inf", "delta_IC95_sup"])], + axis=1) # fmt: skip + + +def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str, + evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip + """c1 and c4 from the table, then each category's class; c2 and c3 must already be set + for the criteria `evaluated`.""" + risk = tab[or_name] > 1 + tab["direccion"] = np.where(risk, "riesgo", "protector") + tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA) + excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0) + tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1)) + tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1) + robust = min(3, len(evaluated)) + tab["clasificacion"] = [ + UNKNOWN_CLASS + if cat == unknown + else f"{d} robusto" + if c1 and k >= robust + else f"{d} sugerente" + if k >= 2 + else "no concluyente" + for cat, d, c1, k in zip( + tab["categoria"], + tab["direccion"], + tab["c1_or"], + tab["criterios_cumplidos"], + strict=True, + ) + ] + return tab + + +def presence(share: float) -> str: + if share >= DEFINING: + return "definitoria" + return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria" + + +def listing(part: pd.DataFrame) -> str: + """`variable=category (strength, share)`, `;`-separated; a treatment's strength is + `asociacion`.""" + strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion", + part["clasificacion"].str.split().str[-1]) # fmt: skip + return "; ".join( + f"{v}={c} ({s}, {p:.0%})" + for v, c, s, p in zip( + part["variable"], part["categoria"], strength, part["share"], strict=True + ) + ) + + +def classified(factors: pd.DataFrame) -> pd.DataFrame: + """The factors a scenario can list (classified ones and treatments), with `tipo_efecto`: + riesgo, protector or tratamiento.""" + found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")] + kind = np.where( + found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0] + ) + return found.assign(tipo_efecto=kind) + + +def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict: + """What one scenario's patients (`mask` over `frame`) have of the `classified` factors: + the listings by kind and presence, and how many risk factors describe it.""" + share = [ + float((frame.loc[mask, v] == c).mean()) + for v, c in zip(found["variable"], found["categoria"], strict=True) + ] + detail = found.assign(share=share, presence=[presence(s) for s in share]) + row = {} + for k in ("riesgo", "protector", "tratamiento"): + for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")): + row[f"{k}_{label}"] = listing( + detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)] + ) + included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING) + row["n_factores_riesgo_incluidos"] = int(included.sum()) + row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0 + return row diff --git a/models/graph.py b/models/graph.py index 62817c1..1a5c5f7 100644 --- a/models/graph.py +++ b/models/graph.py @@ -10,9 +10,11 @@ from collections.abc import Callable from concurrent.futures import ProcessPoolExecutor from functools import cache +import duckdb import ocrmypdf import pandas as pd import pdfplumber +import pikepdf import splink.comparison_library as cl from markitdown import MarkItDown from openai import OpenAI, OpenAIError @@ -47,11 +49,13 @@ from core.pipeline import ( from models.tea.eeg import read from persistance import config_log, files, nodes, silver -MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer +MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer +READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done) READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` "text": {"data_type": "text", "nullable": True}, "ocr": {"data_type": "bool"}, "error": {"data_type": "text", "nullable": True}, + "format": {"data_type": "text", "nullable": True}, } @@ -61,6 +65,15 @@ EDF_COLUMNS = {f"edf_{name}": {"data_type": kind, "nullable": True} for name, ki )} # fmt: skip +def file_format(content: bytes) -> str: + if content.startswith(b"%PDF"): + return "pdf" + head = content[:256] + if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit(): + return "edf" + return "other" + + @cache def _reader() -> MarkItDown: return MarkItDown() @@ -72,44 +85,82 @@ def _lines(text: str) -> str: def _text(content: bytes) -> str: - """PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each - (spacing within a line collapsed); every other format through MarkItDown.""" - if content.startswith(b"%PDF"): - with pdfplumber.open(io.BytesIO(content)) as pdf: - return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages)) + """Files other than PDFs, through MarkItDown.""" return _reader().convert_stream(io.BytesIO(content)).text_content +def _pdf_pages(content: bytes) -> list[str]: + """Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows + on one line each (spacing within a line collapsed).""" + with pdfplumber.open(io.BytesIO(content)) as pdf: + return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages] + + +def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]: + """Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only, + copied into a PDF of their own: a typed page keeps its own text layer.""" + source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new() + for n in numbers: + scans.pages.append(source.pages[n]) + pages, sidecar = io.BytesIO(), io.BytesIO() + scans.save(pages) + pages.seek(0) + ocrmypdf.ocr( + pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0, + progress_bar=False, jobs=1, deskew=True, sidecar=sidecar, + ) # fmt: skip + found = sidecar.getvalue().decode().split("\f") + return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))] + + def read_file(content: bytes) -> dict: - """Text of one file, and whether OCR was needed. An unreadable file keeps its error.""" + """Text of one file, its format, and whether OCR was needed. An unreadable file keeps + its error; a signal recording (EDF) has no text to read.""" + kind = file_format(content) + if kind == "edf": + return {"text": None, "ocr": False, "error": None, "format": kind} + return {**_read_text(content), "format": kind} + + +def _read_text(content: bytes) -> dict: + """The file's text; a PDF page by page, OCR only on the pages without a text layer (a + typed form whose second page is a scan, say).""" try: - found = _text(content) - ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS - if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page - text = io.BytesIO() - ocrmypdf.ocr( - io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True, - output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True, - sidecar=text, - ) # fmt: skip - found = _lines(text.getvalue().decode()) - return {"text": found, "ocr": ocr, "error": None} + if not content.startswith(b"%PDF"): + return {"text": _text(content), "ocr": False, "error": None} + pages = _pdf_pages(content) + scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS] + if scanned: + for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True): + pages[i] = page + return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None} except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} def run_read(p: str, node: Read): - """The input's rows with the file column replaced by its text; each file read once.""" + """The input's rows with their file's text and format beside the file column (which + keeps the file, for a study that takes the file itself: an EEG's recording); each file + read once.""" rows = list(nodes.rows(p, node.inputs[0])) for row in rows: # the source kept the file; the row carries its hash - row["key"] = row.pop(node.column) or None + row["key"] = row.get(node.column) or None keys = {r["key"] for r in rows} - {None} found = nodes.cached("read_cache", keys) - new = {k: files.content(k) for k in keys - set(found)} - with ProcessPoolExecutor() as pool: - read = dict(zip(new, pool.map(read_file, new.values()), strict=True)) - nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS) - found |= read + legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats + for k in legacy: + found[k]["format"] = file_format(files.content(k) or b"") + nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} + for k in legacy], READ_COLUMNS) # fmt: skip + new = sorted(keys - set(found)) + with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept + for start in range(0, len(new), READ_BATCH): + batch = new[start : start + READ_BATCH] + read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)), + strict=True)) # fmt: skip + nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], + READ_COLUMNS) # fmt: skip + found |= read for row in rows: result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"}) row |= {k: result[k] for k in READ_COLUMNS} @@ -145,8 +196,10 @@ def run_edf(p: str, node: Edf): return nodes.write(p, node.id, rows, EDF_COLUMNS) -def run_route(p: str, node: Route): - return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)]) +def run_route(p: str, node: Route, others: list[Route] = ()): + rows = nodes.rows(p, node.inputs[0]) + taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)] + return nodes.write(p, node.id, taken) def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: @@ -228,8 +281,9 @@ def run_extract(p: str, node: Extract): found = apply_patterns(node, text, codes) else: found = [({}, {}, ["no LLM answering and no patterns set"])] + taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None} for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]): - out.append({**values, RECORD: row[RECORD], "_index": index, + out.append({**values, **taken, RECORD: row[RECORD], "_index": index, QUOTES: json.dumps(quotes, ensure_ascii=False), HELD: json.dumps(held) if held else None}) # fmt: skip return nodes.write(p, node.id, out) @@ -293,6 +347,28 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[ return frame[["unique_id", *present]], sources, written +def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series: + """Each record's stand-in: one record per identity that the rules join to itself (a + patient's 24 reports carrying one record number are one row to compare, not 24² pairs). + A record a reviewer judged stands for itself, and so does one the rules would not join + to an identical record (nothing compared was read, say).""" + fields = [c for c in records.columns if c != "unique_id"] + key = records[fields].astype(object).where(records[fields].notna(), None) + same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index) + stand_in = records.groupby(same, sort=False)["unique_id"].transform("first") + stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"]) + joined = set() + if rules: + con = duckdb.connect() + con.register("candidates", records[records["unique_id"].isin(set(stand_in))]) + joins = " or ".join(f"({r})" for r in rules) + joined = set(con.sql( + f"select l.unique_id from candidates l join candidates r" + f" on l.unique_id = r.unique_id where {joins}" + ).df()["unique_id"]) # fmt: skip + return stand_in.where(stand_in.isin(joined), records["unique_id"]) + + def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame: clusters = cluster_pairwise_predictions_at_threshold( records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r" @@ -311,22 +387,25 @@ def run_link(p: str, node: Link): rules = [r for r in node.rules or node.default_rules() if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip comparisons = [_comparison(f) for f in fields] + decided = nodes.person_decisions() + stand_in = _distinct(records, rules, set().union(*decided)) + distinct = records[records["unique_id"].isin(set(stand_in))] db = DuckDBAPI() linker = Linker( - db.register(records), + db.register(distinct), SettingsCreator(link_type="dedupe_only", comparisons=comparisons, blocking_rules_to_generate_predictions=rules), log_level=None, ) # fmt: skip - decided = nodes.person_decisions() sure = linker.inference.deterministic_link().as_pandas_dataframe() pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)} pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same} - known = set(records.unique_id) + known = set(distinct.unique_id) edges = pd.DataFrame( [sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"] ) - persons = _persons(records, edges, db) + cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"] + persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy()) facts = [f for f in ("birth_date", "sex") if f in fields] spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame() @@ -379,6 +458,9 @@ def run_link(p: str, node: Link): orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set() # no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex) undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set() + # Answers are kept by record; a person is known by any of hers, whatever joined since. + whose = persons.set_index("unique_id")["cluster_id"].to_dict() + answered = {frozenset(whose.get(r, r) for r in e) for e in decided} lone = set() # persons whose identifier is carried by one record only for f in ids: carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size() @@ -393,7 +475,7 @@ def run_link(p: str, node: Link): very same identifier on a record that says nothing else (a scan read only in part).""" a, b = r.unique_id_l, r.unique_id_r sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known] - if frozenset((a, b)) in decided or any( + if frozenset((a, b)) in answered or any( pd.notna(x) and pd.notna(y) and x != y for x, y in sides ): return None @@ -476,6 +558,10 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print for node in pipeline.order(): if node.kind == "target": run_target(pipeline_id, node, kinds) + elif node.kind == "route" and node.otherwise: + others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id + and n.inputs == node.inputs and not n.otherwise] # fmt: skip + run_route(pipeline_id, node, others) else: RUNNERS[node.kind](pipeline_id, node) log(f"{node.id} ({node.kind}) done") diff --git a/models/jobs.py b/models/jobs.py index 2995acd..fb002e7 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -41,8 +41,7 @@ class Jobs: return f"{self.domain}_events" def routine(self) -> list[str]: - """The models a train or score run takes when none is named: all but the slow ones.""" - return [n for n, s in self.models.items() if not getattr(s, "slow", False)] + return list(self.models) def registered(self, name: str) -> str: return f"{self.domain}.{name}" @@ -51,8 +50,11 @@ class Jobs: """A new registered version of the model, trained on its cohort's timelines up to `as_of` (default: today), with its metrics and its two generated reports.""" spec, as_of = self.models[name], as_of or date.today() - if spec.cohort is None: # trained on reference data: it writes its own reports - fitted, metrics, found = spec.train(None, as_of) + if getattr(spec, "reports", False): # trained on its cohort, with its own reports + events = gold.timelines(self.events, spec.cohort, as_of) + if events.empty: + raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") + fitted, metrics, found = spec.train(events, as_of) else: events = gold.timelines(self.events, spec.cohort, as_of) if events.empty: @@ -72,8 +74,6 @@ class Jobs: def score(self, name: str) -> int | None: """The champion's risks for today's members of the model's cohort, saved as its risk batch; None when the model has no champion yet.""" - if self.models[name].cohort is None: # scores no patient - return None found = registry.champion(self.registered(name)) if found is None: return None diff --git a/models/survival.py b/models/survival.py index 3f9dabc..8588e79 100644 --- a/models/survival.py +++ b/models/survival.py @@ -9,6 +9,8 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi category of its own (UNKNOWN). """ +import json +import warnings from dataclasses import dataclass, field from itertools import pairwise @@ -220,7 +222,9 @@ class IntervalSurvival(BaseEstimator): # ---------------------------------------------------------------- a model over gold timelines TRAIN_FRACTION = 0.7 -OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"] +OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high", + "scenarios"] # fmt: skip +SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: @@ -265,6 +269,8 @@ class Spec: # "in", value) on the members' covariates and `scenario_columns` (kept for them only). scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict) scenario_columns: tuple[str, ...] = () + # Features that are treatments: their odds ratios are reported as associations, unclassified. + treatments: tuple[str, ...] = () @property def horizons(self) -> tuple[float, ...]: @@ -324,13 +330,17 @@ class Spec: return model, metrics, {"train": train, "test": test} def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame: - """One row per member and horizon: her mortality by it, and its interval when kept.""" + """One row per member and horizon: her mortality by it, its interval when kept, and + the clinical scenarios of the report she falls in (the curves her record draws).""" members = self.members(events) mortality = 1.0 - model.survival(members) n, h = len(members), len(self.horizons) empty = ([np.nan] * h, [np.nan] * h) ends = [model.intervals_.get(tuple(c), empty) for c in self._combinations(members).itertuples(index=False)] # fmt: skip + masks = scenario_masks(members, self.scenarios) + scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None + for i in range(n)] # fmt: skip return pd.DataFrame({ "person_id": np.repeat(members["person_id"].to_numpy(), h), "index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h), @@ -338,6 +348,7 @@ class Spec: "probability": mortality.ravel(), "ci_low": np.array([e[0] for e in ends], dtype=float).ravel(), "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(), + "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h), })[OUTPUT] # fmt: skip @@ -496,4 +507,102 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: "escenarios": scenarios, "escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths "min_fallecidos_escenario": MIN_SCENARIO_EVENTS, + **risk_factor_report(spec, model, members), + } + + +# ---------------------------------------------------------------- risk factors + +FACTOR_COLUMNS = ( + "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", + "IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia", + "delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov", + "c4_supervivencia", "criterios_cumplidos", "clasificacion", +) # fmt: skip +SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S") +TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" +# The model has no variable selection to resample, so stability (2) is not evaluated. +EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia") + + +def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame: + """The members' risk factors of death by the last horizon (`models.factors`, as the + SEER-trained original rates them): odds ratios of dying before it, among those dead before + it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at + `cap_months`); the Markov blanket is the HBN's parents in any interval.""" + from models import factors as rated + + horizon = spec.borders[-1] + months, event = members["months"].to_numpy(), members["event"].to_numpy(bool) + died = event & (months < horizon) + known = died | (months >= horizon) + data = spec._combinations(members)[known].reset_index(drop=True) + y, months, event = died[known].astype(int), months[known], event[known] + empty = pd.DataFrame(columns=list(FACTOR_COLUMNS)) + if len(data) == 0 or y.min() == y.max(): + return empty + features = list(spec.features) + treatment = [f for f in features if f in spec.treatments] + intrinsic = [f for f in features if f not in spec.treatments] + reference = {v: data[v].value_counts().idxmax() for v in features} + blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents} + + def complete(table, variables): + return rated.complete(table, variables, reference, data, months, event, horizon, + SURVIVAL_COLUMNS) # fmt: skip + + with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"): + warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios + try: + tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"), + intrinsic) # fmt: skip + except (np.linalg.LinAlgError, ValueError): + return empty + tab["c2_estabilidad"] = np.nan + tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket) + tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED) + tab["tipo"] = "factor de riesgo" + if treatment: + both = intrinsic + treatment + try: + tr = rated.odds_ratios(data, y, both, reference, "OR_muerte") + except (np.linalg.LinAlgError, ValueError): + tr = None + if tr is not None: + of = tr["termino"].map(lambda x: rated.variable_of(x, both)) + tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], + treatment) # fmt: skip + tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS + tab = pd.concat([tab, tr], ignore_index=True) + tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) + tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5) + tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False]) + return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True) + + +def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]: + """Per clinical scenario, the classified factors and treatments nearly all of its + members have (definitorios) or most have (mayoritarios).""" + from models import factors as rated + + found = rated.classified(table) if len(table) else table + data = spec._combinations(members) + rows = [] + for name, mask in scenario_masks(members, spec.scenarios).items(): + if not mask.any() or found.empty: + continue + rows.append({ + "escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]], + "n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found), + }) # fmt: skip + return rows + + +def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict: + """The interpretability report's risk factors: the table and each scenario's summary.""" + table = risk_factors(spec, model, members) + rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON + return { + "factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows}, + "factores_escenarios": scenario_factors(spec, members, table), } diff --git a/pyproject.toml b/pyproject.toml index 744a4ea..a9f0a1a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,8 +11,10 @@ dependencies = [ "mlflow-skinny", "openai>=3.59.0", "splink>=5.0.0", + "duckdb>=2.0.1", "markitdown[docx,xlsx]>=0.1.9", "ocrmypdf>=17.14.2", + "pikepdf>=10.0", "pdfplumber>=0.11.11", "scikit-learn>=1.9.1", "scipy>=1.18.1", diff --git a/tests/recurrence_reference.py b/tests/recurrence_reference.py new file mode 100644 index 0000000..21035dc --- /dev/null +++ b/tests/recurrence_reference.py @@ -0,0 +1,135 @@ +"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a +`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written, +column names as dlt names them, `line` the order the file is published in).""" + +import pandas as pd + +from models.cama import recurrence +from models.cama.recurrence import site +from models.cama.recurrence.cohorts import ( + AGE, + DAYS_PER_MONTH, + GRADES, + NODES, + SIZE, + Cohort, + _band, + _number, + _text, + collinear, +) + +SOURCES = ("metabric", "scanb") +SAVED = "metabric" +N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40} +LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"} +SAMPLING = { + "criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", + "origen": "METABRIC y SCAN-B (externas)", +} +SCENARIOS = { + "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": site.SCENARIOS, +} # fmt: skip +FIXED = { + "metabric": ["paciente", "tiempo_meses", "evento"], + "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], +} +TREATMENT = { + "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], + "scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], +} +# Covariates taken as they come (our name: the dataset's column). +PASSTHROUGH = { + "metabric": { + "Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status", + "HER2": "her2_status", "Subtipo_PAM50": "pam50_x_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", + }, + "scanb": { + "Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2", + "Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology", + "Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality", + "Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type", + "Quimioterapia": "chemotherapy", "Radioterapia": "radiation", + "Hormonoterapia": "endocrine", "AntiHER2": "anti_her2", + }, +} # fmt: skip +SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} +SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} + + +def _in_order(rows: pd.DataFrame) -> pd.DataFrame: + return rows.sort_values("line", kind="stable").reset_index(drop=True) + + +def _metabric(rows: pd.DataFrame) -> pd.DataFrame: + d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"]) + d = d.reset_index(drop=True) + out = pd.DataFrame({"paciente": d["patient_id"]}) + out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"]) + out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int) + out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE) + out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE) + out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES) + out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES)) + # Mutational load in tertiles of this cohort; a value on a cut falls in the lower band. + load = _number(d["mutation_count"]) + q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() + edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6] + out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"]) + for name, column in PASSTHROUGH["metabric"].items(): + out[name] = _text(d[column]) + return out + + +def _scanb(rows: pd.DataFrame) -> pd.DataFrame: + d = _in_order(rows) + d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True) + rfi, died = _number(d["rfi_event"]), _number(d["os_event"]) + out = pd.DataFrame({"paciente": d["patient_name"]}) + out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH + out["evento"] = rfi.astype(int) + out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int) + out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle + out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE) + out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES)) + out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES)) + for name, column in PASSTHROUGH["scanb"].items(): + out[name] = _text(d[column]) + return out + + +def prepare(source: str, raw: pd.DataFrame) -> Cohort: + full = {"metabric": _metabric, "scanb": _scanb}[source](raw) + fixed, treatment = FIXED[source], TREATMENT[source] + covariates = [c for c in full.columns if c not in fixed] + dropped = collinear(full, [c for c in covariates if c not in treatment]) + kept = [c for c in covariates if c not in dropped] + return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped, + LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip + + +def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple: + """Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept.""" + found = {s: prepare(s, raws[s]) for s in SOURCES} + return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {}) diff --git a/tests/test_link_answers.py b/tests/test_link_answers.py new file mode 100644 index 0000000..55da30f --- /dev/null +++ b/tests/test_link_answers.py @@ -0,0 +1,51 @@ +"""A reviewer's "they are different people" is about the persons: it holds when more records +join one of them, whichever record the person is known by afterwards.""" + +import json +import sqlite3 + +PEOPLE = [("1001", "ANA LOPEZ RUIZ", "1980-01-01"), ("2002", "BEATRIZ MORA DIAZ", "1980-01-01")] +PEOPLE += [(f"9{k:03d}", f"PERSONA {k} DE RELLENO", f"19{50 + k}-0{1 + k % 9}-11") + for k in range(30)] # fmt: skip + + +def graph(db) -> dict: + fields = {"record_number": "num", "full_name": "nombre", "birth_date": "nac", "nss": "nss"} + return {"nodes": [ + {"id": "people", "kind": "source", "source": "dlt.sources.sql_database:sql_table", + "args": {"credentials": f"sqlite:///{db}", "table": "people"}}, + {"id": "identity", "kind": "map", "inputs": ["people"], "fields": fields}, + {"id": "persons", "kind": "link", "inputs": ["identity"], "fields": list(fields)}, + ]} # fmt: skip + + +def insert(db, rows) -> None: + with sqlite3.connect(db) as con: + con.execute( + "create table if not exists people " + "(id integer primary key, num text, nombre text, nac text, nss text)" + ) + con.executemany("insert into people (num, nombre, nac, nss) values (?, ?, ?, ?)", rows) + + +def test_an_answer_outlives_the_record_a_person_was_known_by(platform, tmp_path): + db, drawn = tmp_path / "people.db", tmp_path / "pipeline.json" + insert(db, [(*p, None) for p in PEOPLE]) + drawn.write_text(json.dumps(graph(db))) + platform.save("pipelines", "site", drawn) + platform.ingest() + queue = "select person, candidate from bronze.n__site__persons__review" + ((a, b),) = platform.query(queue) + platform.run("python", "-c", "from persistance import nodes; " + f"nodes.decide_persons({a!r}, {b!r}, False, 'reviewer')") # fmt: skip + platform.ingest() + assert platform.query(queue) == [] + + # Forty more documents of each woman: whichever of her records her person was known by, + # one of these is (almost surely) it now. + insert(db, [(num, None, None, f"{num}{k:07d}") for num in ("1001", "2002") for k in range(40)]) + platform.ingest() + lowest = "select min(_record) from bronze.n__site__persons where record_number = '{}'" + known = {platform.query(lowest.format(n))[0][0] for n in ("1001", "2002")} + assert known != {a, b} + assert platform.query(queue) == []