From 2457859a09d77f74cacfb5b36124c86cdf252d5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Sun, 29 Nov 2026 21:30:26 -0600 Subject: [PATCH] ISSSTELEON models 2ff634c --- models/cama/recurrence/__init__.py | 18 ++---- models/cama/recurrence/calculator.py | 52 +-------------- models/cama/recurrence/cohorts.py | 96 ++-------------------------- models/cama/recurrence/factors.py | 4 +- models/cama/recurrence/modeling.py | 5 +- models/cama/recurrence/reports.py | 12 +--- models/cama/recurrence/site.py | 40 +++++++++++- models/cama/specs.py | 9 ++- models/jobs.py | 8 +-- models/tea/eeg/data/hk1k_state.json | 11 ---- 10 files changed, 63 insertions(+), 192 deletions(-) delete mode 100644 models/tea/eeg/data/hk1k_state.json diff --git a/models/cama/recurrence/__init__.py b/models/cama/recurrence/__init__.py index 166a492..4f62444 100644 --- a/models/cama/recurrence/__init__.py +++ b/models/cama/recurrence/__init__.py @@ -4,13 +4,7 @@ import numpy as np import pandas as pd from models.cama.recurrence import calculator, cohorts, factors, modeling, reports -SOURCES = ("metabric", "scanb") HORIZONS = modeling.HORIZONS -SAVED = "metabric" - - -def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame: - return cohorts.prepare(source, rows).frame @dataclass @@ -40,22 +34,18 @@ class Recurrence: return pd.DataFrame(out, index=X.index) -def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: - found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES} - return fit(found, SAVED, "metabric+scanb", bootstrap) - - def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: from models.cama.recurrence import site - return fit({"site": site.prepare(rows)}, "site", "site", bootstrap) + return fit( + {"site": site.prepare(rows)}, "site", "site", modeling.N_BOOTSTRAP if bootstrap else {} + ) def fit( - found: dict, saved: str, label: str, bootstrap: bool = True + found: dict, saved: str, label: str, n_bootstrap: dict[str, int] ) -> tuple[Recurrence, dict, dict]: sources = list(found) - n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {} try: fits = modeling.fit(found, n_bootstrap) drawn = {s: calculator.calculator(fits[s]) for s in sources} diff --git a/models/cama/recurrence/calculator.py b/models/cama/recurrence/calculator.py index 8349240..7854d8a 100644 --- a/models/cama/recurrence/calculator.py +++ b/models/cama/recurrence/calculator.py @@ -10,52 +10,6 @@ RESAMPLES = 200 MIN_EVENTS = 15 CAP_MONTHS = 72 GRID_POINTS = 289 -LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"} -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"]}, - }, -} -SCENARIOS["site"] = SCENARIOS["scanb"] def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: @@ -134,9 +88,9 @@ 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]]: 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) @@ -159,7 +113,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 aaab7dd..e792641 100644 --- a/models/cama/recurrence/cohorts.py +++ b/models/cama/recurrence/cohorts.py @@ -5,53 +5,11 @@ from scipy.stats.contingency import association UNKNOWN = "Desconocido" V_MAX = 0.8 DAYS_PER_MONTH = 30.4375 +HORIZONS = (12, 36, 60) AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) SIZE = ([0, 20.01, 50.01, 10000.0], ["<=20 mm", "21-50 mm", ">50 mm"]) NODES = ([0, 1, 4, 1000.0], ["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"], -} -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", - }, -} -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: @@ -66,46 +24,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)) - load = _number(d["mutation_count"]) - q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() - edges = [-1, q1 + 1e-09, q2 + 1e-09, 1000000.0] - 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) - 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 @@ -137,21 +55,15 @@ class Cohort: covariates: list[str] treatment: list[str] eliminated: list[str] + label: str + scenarios: dict + sampling: dict @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: t, event = (frame["tiempo_meses"], frame["evento"] == 1) found = frame[event & (t <= horizon) | (t > horizon)].reset_index(drop=True) diff --git a/models/cama/recurrence/factors.py b/models/cama/recurrence/factors.py index cd97e85..2f0eab9 100644 --- a/models/cama/recurrence/factors.py +++ b/models/cama/recurrence/factors.py @@ -2,7 +2,7 @@ import warnings import numpy as np import pandas as pd from models import factors as rated -from models.cama.recurrence.calculator import SCENARIOS, masks +from models.cama.recurrence.calculator import masks from models.cama.recurrence.cohorts import UNKNOWN, at_horizon from models.cama.recurrence.modeling import CohortFit from models.factors import FREQ_MIN, ORDER @@ -92,7 +92,7 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: frame, source = (fitted.cohort.frame, fitted.cohort.source) - scenarios = SCENARIOS[source] + scenarios = fitted.cohort.scenarios found = rated.classified(factors[factors["cohorte"] == source]) rows = [] for name, mask in masks(frame, scenarios).items(): diff --git a/models/cama/recurrence/modeling.py b/models/cama/recurrence/modeling.py index e67127d..ceb4114 100644 --- a/models/cama/recurrence/modeling.py +++ b/models/cama/recurrence/modeling.py @@ -9,10 +9,9 @@ from lifelines.utils import concordance_index 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) SEED = 42 TEST_SIZE = 0.3 ESS = 10 @@ -21,7 +20,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = (0.1, 0.1, 0.15) MAX_STEPS = 200 COX_PENALIZER = 0.05 COX_MIN_COUNT = 10 -N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40} +N_BOOTSTRAP = {"site": 40} def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: diff --git a/models/cama/recurrence/reports.py b/models/cama/recurrence/reports.py index 8486a69..b21690a 100644 --- a/models/cama/recurrence/reports.py +++ b/models/cama/recurrence/reports.py @@ -84,16 +84,6 @@ def metrics(auc: list[dict]) -> dict[str, float]: return found -REFERENCE_SAMPLING = { - "criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", - "origen": "METABRIC y SCAN-B (externas)", -} -SITE_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 routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: return { "MUESTREO": { @@ -106,7 +96,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: } for s, c in cohorts.items() }, - **(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING), + **next(iter(cohorts.values())).sampling, }, "DATOS_FALTANTES": { "criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); no se imputa ni se descarta", diff --git a/models/cama/recurrence/site.py b/models/cama/recurrence/site.py index 9033d93..ea05f6e 100644 --- a/models/cama/recurrence/site.py +++ b/models/cama/recurrence/site.py @@ -30,6 +30,33 @@ TREATMENTS = { } FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] TREATMENT = ["Cirugia", *TREATMENTS] +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"]}, +} +MIN_PER_CLASS = 10 +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: @@ -97,9 +124,20 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame: return out.reset_index(drop=True) +def scarce(rows: pd.DataFrame) -> str | 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, {MIN_PER_CLASS} of each needed" + return None + + def prepare(rows: pd.DataFrame) -> Cohort: 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) + return Cohort( + "site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio", SCENARIOS, SAMPLING + ) diff --git a/models/cama/specs.py b/models/cama/specs.py index 5a8e10f..73142fe 100644 --- a/models/cama/specs.py +++ b/models/cama/specs.py @@ -92,15 +92,18 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: class SiteRecurrence: name: str cohort: str = "cama_cohort_recurrence" - slow: bool = True reports: bool = True 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 - return recurrence.train_site(site.frame(events, as_of or date.today())) + 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: from models.cama.recurrence import calculator, site @@ -108,7 +111,7 @@ class SiteRecurrence: members = site.frame(events, date.today()) found = model.predict(members) index = events.groupby("person_id")["index_date"].first() - masks = calculator.masks(members, calculator.SCENARIOS["site"]) + 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)) diff --git a/models/jobs.py b/models/jobs.py index 7fb62c7..b5eeb98 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -31,7 +31,7 @@ class Jobs: return f"{self.domain}_events" def routine(self) -> list[str]: - return [n for n, s in self.models.items() if not getattr(s, "slow", False)] + return list(self.models) def scored(self) -> list[str]: return list(self.models) @@ -41,9 +41,7 @@ class Jobs: def train(self, name: str, as_of: date | None = None) -> int: spec, as_of = (self.models[name], as_of or date.today()) - if spec.cohort is None: - fitted, metrics, found = spec.train(None, as_of) - elif getattr(spec, "reports", False): + if getattr(spec, "reports", False): events = gold.timelines(self.events, spec.cohort, as_of) if events.empty: raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") @@ -63,8 +61,6 @@ class Jobs: return registry.register(self.registered(name), model, params, metrics, found) def score(self, name: str) -> int | None: - if self.models[name].cohort is None: - return None found = registry.champion(self.registered(name)) if found is None: return None diff --git a/models/tea/eeg/data/hk1k_state.json b/models/tea/eeg/data/hk1k_state.json deleted file mode 100644 index 3eca189..0000000 --- a/models/tea/eeg/data/hk1k_state.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "source": "HK1K reference of the sleep-depth index (223 studies, 16-36 months): each window feature standardised by its median and dispersion, the posterior rhythm's median a line on log10 age; signs and weights of the weighted mean; cut-offs wake < -1.2327 <= drowsy < -0.3032 <= sleep", - "features": { - "delta_beta": {"median": 1.6117037688126001, "dispersion": 0.3097998485854789, "sign": 1, "weight": 1.0}, - "posterior_rhythm": {"slope": 4.934510806157707, "intercept": 0.999676072265559, "median": 7.765061458878031, "dispersion": 1.021788597296859, "sign": -1, "weight": 1.0}, - "sigma": {"median": 0.019957376774209706, "dispersion": 0.012167857665235331, "sign": 1, "weight": 0.7}, - "muscle": {"median": 0.0742822337558628, "dispersion": 0.056777351044491706, "sign": -1, "weight": 0.7}, - "alpha": {"median": 0.03498707283228359, "dispersion": 0.016352123389996105, "sign": -1, "weight": 0.6} - }, - "cuts": [-1.2326590642152986, -0.3031551001049524] -}