Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5cc6bee168 | |||
| f9d97f4d12 | |||
| 674bdc4bb2 |
@@ -11,6 +11,8 @@ Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36
|
||||
regresión logística y una red bayesiana por horizonte, entrenadas con las pacientes cargadas de dos cohortes externas (METABRIC y SCAN-B). Pendiente \
|
||||
de validación clínica."""
|
||||
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
|
||||
# Its figures are answered per clinical scenario (`/cama/modelo/recurrencia`); the cycle does not score each member.
|
||||
batch_estimates = false
|
||||
|
||||
[config.recurrence]
|
||||
horizons = [12, 36, 60] # months
|
||||
|
||||
@@ -29,10 +29,13 @@ TABLES = {
|
||||
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
|
||||
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
|
||||
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
|
||||
"curva_supervivencia_puntos_LR_HBN.csv": "cohorte_puntos",
|
||||
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
|
||||
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
|
||||
}
|
||||
MAX_ROWS = 60
|
||||
# The name the whole cohort's points go by among the subgroups' (`subgroup_points`).
|
||||
WHOLE_COHORT = "Toda la cohorte"
|
||||
MAX_FIGURE_BYTES = 400_000
|
||||
|
||||
|
||||
@@ -122,8 +125,9 @@ def population(population_curves: dict, development: dict) -> dict:
|
||||
|
||||
def subgroup_points(labelled_members: pd.DataFrame, desarrollo: dict) -> list[dict]:
|
||||
"""The pipeline's stages 01 and 05 over the members as they are now: the depuration, then the LR and HBN fitted on them with
|
||||
each clinical scenario's survival at the horizons and its bootstrap interval (`subgrupos_puntos`), one row per model,
|
||||
horizon and scenario. What the dashboard draws as a scenario's points between trainings."""
|
||||
each clinical scenario's survival at the horizons and its bootstrap interval (`subgrupos_puntos`), and the whole cohort's
|
||||
(`cohorte_puntos`, as subgroup `WHOLE_COHORT`), one row per model, horizon and scenario. What the dashboard draws as a
|
||||
scenario's points between trainings."""
|
||||
from models.cama.seer_survival import pipeline
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -131,5 +135,8 @@ def subgroup_points(labelled_members: pd.DataFrame, desarrollo: dict) -> list[di
|
||||
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
|
||||
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
|
||||
pipeline.run_pipeline(out, only=["01", "05"], everything=True, settings=_seer_settings(desarrollo))
|
||||
table = pd.read_csv(out / "subgrupos_puntos_LR_HBN.csv").replace([np.inf, -np.inf], np.nan).astype(object)
|
||||
cohort = pd.read_csv(out / "curva_supervivencia_puntos_LR_HBN.csv").assign(subgrupo=WHOLE_COHORT)
|
||||
table = pd.concat([pd.read_csv(out / "subgrupos_puntos_LR_HBN.csv"), cohort[["modelo", "meses", "S", "IC_inf", "IC_sup", "subgrupo"]]],
|
||||
ignore_index=True)
|
||||
table = table.replace([np.inf, -np.inf], np.nan).astype(object)
|
||||
return table.where(table.notna(), None).to_dict("records")
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far.
|
||||
"""The survival figure of a clinical scenario over the data ingested so far, as the SEER pipeline's survival stage draws a subgroup.
|
||||
|
||||
Training and tuning happen in governance; here the production version is only applied. The scenarios are the subgroups of
|
||||
the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
|
||||
share a figure, and a patient sees the figure of each scenario she belongs to. The record is the one the training run
|
||||
publishes for the whole cohort (`population`), for the scenario's members: the Kaplan-Meier curve of what happened to them
|
||||
with its Greenwood band, the survival the model predicts for them (their mean at each horizon by the logistic regression, the
|
||||
Bayesian network and their combination, with a 95 % interval from resampling the members), and the Weibull fits the SEER
|
||||
pipeline makes to that prediction. Nothing is fitted on the scenario and nothing is stored.
|
||||
Training and tuning happen in governance; here the production version's results are only shown. The scenarios are the subgroups
|
||||
of the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
|
||||
share a figure, and a patient sees the figure of each scenario she belongs to, or the whole cohort's when she is in none. The
|
||||
record has the Kaplan-Meier curve of what happened to the scenario's members with its Greenwood band, the classic and fractional
|
||||
Weibull fitted to their deaths, and the pipeline's LR, HBN and combined survival at each horizon with their bootstrap intervals:
|
||||
the survival stage's points for the scenario (`development.subgroup_points`), never a model of this module's.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
@@ -17,14 +16,13 @@ import pandas as pd
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival import survival_curves as luis
|
||||
from models.cama.survival import population
|
||||
from models.cama.survival.estimator import FEATURES, IntervalSurvival, molecular_subtype, survival_settings
|
||||
from models.cama.survival.development import WHOLE_COHORT
|
||||
from models.cama.survival.estimator import IntervalSurvival, molecular_subtype, survival_settings
|
||||
from models.dags.training import Scenario, dataflow
|
||||
|
||||
MIN_MEMBERS = 30
|
||||
MIN_EVENTS = 5
|
||||
REPLICAS = 200
|
||||
SEED = 42
|
||||
WHOLE = "Toda la cohorte"
|
||||
WHOLE = WHOLE_COHORT
|
||||
|
||||
|
||||
class QueryError(ValueError):
|
||||
@@ -67,23 +65,10 @@ def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
|
||||
return found or [WHOLE]
|
||||
|
||||
|
||||
def monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarray:
|
||||
"""Each member's survival month by month from 0 to `months`: log-linear between the horizons, which is a constant hazard
|
||||
in each interval, and past the last one with the hazard of the last interval."""
|
||||
borders = np.array([0, *horizons], float)
|
||||
log = np.log(np.clip(np.column_stack([np.ones(len(survival)), survival]), 1e-12, 1.0))
|
||||
grid = np.arange(months + 1, dtype=float)
|
||||
out = np.empty((len(survival), len(grid)))
|
||||
slope = (log[:, -1] - log[:, -2]) / (borders[-1] - borders[-2])
|
||||
for i in range(len(survival)):
|
||||
out[i] = np.where(grid > borders[-1], log[i, -1] + slope[i] * (grid - borders[-1]), np.interp(grid, borders, log[i]))
|
||||
return np.minimum.accumulate(np.exp(out), axis=1)
|
||||
|
||||
|
||||
def published_points(rows: list[dict], name: str) -> dict | None:
|
||||
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`: its model with the stage and the
|
||||
treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
|
||||
found = [r for r in rows if r.get("subgrupo") == name]
|
||||
def published_points(rows: list[dict], name: str | None) -> dict | None:
|
||||
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`, or `cohorte_puntos` for `WHOLE`:
|
||||
its model with the stage and the treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
|
||||
found = [r for r in rows if r.get("subgrupo") == (name or WHOLE)]
|
||||
if not found:
|
||||
return None
|
||||
out = {}
|
||||
@@ -96,11 +81,11 @@ def published_points(rows: list[dict], name: str) -> dict | None:
|
||||
return out
|
||||
|
||||
|
||||
def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None, points: dict | None = None) -> dict:
|
||||
def curves(scenario: Scenario, labelled: pd.DataFrame, name: str | None, points: dict | None) -> dict:
|
||||
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone), as the pipeline's survival stage
|
||||
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths. The points
|
||||
are `points` when the version published them for the subgroup (`published_points`), else the members scored with `model`
|
||||
(the fitted `IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything."""
|
||||
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths, with the
|
||||
stage's `points` for it (`published_points`). `QueryError` for an unknown scenario, one with too few members to say
|
||||
anything, or one the stage has no points for yet."""
|
||||
if name in (None, WHOLE):
|
||||
mask = np.ones(len(labelled), bool)
|
||||
else:
|
||||
@@ -111,29 +96,22 @@ def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None,
|
||||
if not answerable(labelled, mask):
|
||||
raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; "
|
||||
f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.")
|
||||
if points is None:
|
||||
raise QueryError("El modelo todavía no tiene la supervivencia de este escenario; se calcula en el siguiente recálculo de indicadores.")
|
||||
selected = labelled[mask].reset_index(drop=True)
|
||||
s = survival_settings(scenario.config["survival"])
|
||||
horizons, cap = list(s.horizons), max(s.cap_months, max(s.horizons))
|
||||
predicted = model.component_survival(selected[FEATURES])
|
||||
if points is None:
|
||||
resample = np.random.default_rng(SEED).integers(0, len(selected), (REPLICAS, len(selected)))
|
||||
points = {}
|
||||
for series in population.SERIES:
|
||||
low, high = np.percentile(predicted[series][resample].mean(axis=1), [2.5, 97.5], axis=0)
|
||||
points[series] = {"S": predicted[series].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()}
|
||||
followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool)
|
||||
months, ended = np.minimum(followed, cap), died & (followed < cap)
|
||||
S, low, high = luis.fw.km_curva(months, ended, cap)
|
||||
adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0)
|
||||
d, c = luis.fw.tabla_eventos(months, ended)
|
||||
classic = luis.fw.ajustar_weibull(d, c)
|
||||
fractional = luis.fw.ajustar_ks(d, c, k_fijo=luis._fixed_k(classic, s), lam_ref=classic["lam"], max_seg=s.ks_sub_max_seconds)
|
||||
grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP)
|
||||
return {"version": population.RECORD_VERSION, "escenario": name or WHOLE, "n": int(len(selected)),
|
||||
"events": int((died & (followed < cap)).sum()), "median_follow_up_months": float(np.median(followed)),
|
||||
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": REPLICAS,
|
||||
"events": int(ended.sum()), "median_follow_up_months": float(np.median(followed)),
|
||||
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": int(s.n_boot if name in (None, WHOLE) else s.n_boot_sub),
|
||||
"km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
|
||||
"km_adjusted": {"months": list(range(len(adjusted))), "S": adjusted.tolist()},
|
||||
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
|
||||
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
|
||||
"points": points, "etiquetas": scenario.config.get("etiquetas", {})}
|
||||
|
||||
@@ -52,6 +52,9 @@ class Scenario:
|
||||
# What the model's number is (`[estimand]`): `quantity`, `description`, `outcome`, `index_date`, `horizons_unit`;
|
||||
# what a screen shows next to each risk. How its interval is computed is the version's report's, not the screen's.
|
||||
estimand: dict = field(default_factory=dict)
|
||||
# Whether the cycle scores every member of the cohort with the version in production (`batch_estimates`); off for a
|
||||
# model whose answers are per clinical scenario, not a risk per member.
|
||||
batch_estimates: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, path: str | Path) -> "Scenario":
|
||||
@@ -62,7 +65,7 @@ class Scenario:
|
||||
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
|
||||
folder=path.parent, requirements=tuple(found.get("requirements", ())),
|
||||
tables={name: found[name] for name in found.get("settings_tables", ())} or None,
|
||||
estimand=dict(found.get("estimand", {})))
|
||||
estimand=dict(found.get("estimand", {})), batch_estimates=bool(found.get("batch_estimates", True)))
|
||||
|
||||
@classmethod
|
||||
def load(cls, domain: str, scenario: str) -> "Scenario":
|
||||
|
||||
@@ -150,17 +150,30 @@ KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposc
|
||||
|
||||
|
||||
def _first_invasive_biopsy(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
|
||||
"""(members, attrition) of the kind `primera_biopsia_invasora`, from the whole frame."""
|
||||
biopsies = cohort[(cohort["tipo"] == "biopsia") & (cohort["valor_codigo"] == index.get("invasive_code", "CARCINOMA_INVASOR"))]
|
||||
first = pd.to_datetime(biopsies["fecha"]).groupby(biopsies["pac_id"]).min()
|
||||
"""(members, attrition) of the kind `primera_biopsia_invasora`, from the whole frame: the first biopsy reported with
|
||||
one of the scenario's `event_grades`, if it falls in the window, then the rules of the per-patient version."""
|
||||
grades = set(index.get("event_grades") or [index.get("invasive_code", "CARCINOMA_INVASOR")])
|
||||
dated = cohort.assign(fecha=pd.to_datetime(cohort["fecha"]))
|
||||
biopsies = dated[(dated["tipo"] == "biopsia") & (dated["valor_codigo"].isin(grades))]
|
||||
first = biopsies.groupby("pac_id")["fecha"].min()
|
||||
start, end = index.get("recruitment_start"), index.get("recruitment_end")
|
||||
inside = pd.Series(True, index=first.index)
|
||||
if start is not None:
|
||||
inside &= first >= pd.Timestamp(start)
|
||||
if end is not None:
|
||||
inside &= first < pd.Timestamp(end)
|
||||
members = first[inside].rename("fecha_indice").dt.date.rename_axis("pac_id").reset_index()
|
||||
return members, [("pacientes", int(cohort["pac_id"].nunique())), ("indexed", len(members))]
|
||||
first = first[inside]
|
||||
attrition = [("pacientes", int(cohort["pac_id"].nunique())), ("indexed", len(first))]
|
||||
first = first[first.index.isin(dated.loc[dated["tipo"] == "nacimiento", "pac_id"])]
|
||||
attrition.append(("sin_nacimiento", len(first)))
|
||||
death = dated[dated["tipo"] == "defuncion"].groupby("pac_id")["fecha"].min().reindex(first.index)
|
||||
first = first[~death.le(first).to_numpy()]
|
||||
attrition.append(("defuncion_hasta_el_indice", len(first)))
|
||||
prior_days = (first - dated.groupby("pac_id")["fecha"].min().reindex(first.index)).dt.days
|
||||
first = first[(prior_days >= int(index.get("observacion_previa_minima_dias", 0))).to_numpy()]
|
||||
attrition.append(("observacion_previa_insuficiente", len(first)))
|
||||
members = first.rename("fecha_indice").dt.date.rename_axis("pac_id").reset_index()
|
||||
return members, attrition
|
||||
|
||||
|
||||
# Kinds read from the whole frame: (cohort, index) -> (members, attrition), for cohorts too large to take apart by patient.
|
||||
|
||||
@@ -170,6 +170,31 @@ def test_the_node_reindexes_the_frame_with_the_source_cohorts_window():
|
||||
assert closed.empty and indexing.cohort(source, lineage, None) is source
|
||||
|
||||
|
||||
def test_the_first_invasive_biopsy_index_reads_the_scenarios_event_grades_and_applies_its_rules():
|
||||
"""Pins down `primera_biopsia_invasora` over the whole frame: the index is the first biopsy reported with one of the
|
||||
scenario's `event_grades` (CaCu's CIS and carcinoma, CaMa's invasive carcinoma), a grade of another scenario does
|
||||
not index, and without `event_grades` the CaMa code is the default; then, in order, the patient with no birth date
|
||||
and the one who died on or before the biopsy are out, each charged in the attrition. Fails if the index looks for
|
||||
one fixed code, so that CaCu's survival has no members, if a grade outside the list indexes, or if a rule stops
|
||||
applying."""
|
||||
birth = [_row(pac, "nacimiento", date(1980, 1, 1)) for pac in (1, 2, 3, 5)]
|
||||
rows = [*birth, _row(1, "biopsia", date(2025, 3, 1), "CIS"), _row(1, "biopsia", date(2025, 1, 1), "LIEAG"),
|
||||
_row(2, "biopsia", date(2025, 6, 1), "CARCINOMA"), _row(3, "biopsia", date(2025, 7, 1), "CARCINOMA_INVASOR"),
|
||||
_row(4, "biopsia", date(2025, 8, 1), "CARCINOMA"),
|
||||
_row(5, "biopsia", date(2025, 9, 1), "CIS"), _row(5, "defuncion", date(2025, 9, 1))]
|
||||
|
||||
def indexed(**index):
|
||||
members, attrition = indexing._indexed_members(_frame(rows), {"kind": "primera_biopsia_invasora", **index})
|
||||
return members.values.tolist(), attrition
|
||||
|
||||
members, attrition = indexed(event_grades=["CIS", "CARCINOMA"])
|
||||
assert members == [[1, date(2025, 3, 1)], [2, date(2025, 6, 1)]]
|
||||
assert attrition == [("pacientes", 5), ("indexed", 4), ("sin_nacimiento", 3), ("defuncion_hasta_el_indice", 2),
|
||||
("observacion_previa_insuficiente", 2)]
|
||||
assert indexed(event_grades=["CARCINOMA_INVASOR"])[0] == [[3, date(2025, 7, 1)]]
|
||||
assert indexed()[0] == [[3, date(2025, 7, 1)]]
|
||||
|
||||
|
||||
def test_prior_observation_is_a_threshold_on_the_days_before_the_index():
|
||||
"""Pins down the left-truncation rule: with the default 0 nobody is out; with 230 days, patient 1 (first event 30
|
||||
days before her colposcopy, visit 1 at 200 days: 230 days observed) stays and with 231 she is out; the summary
|
||||
|
||||
Reference in New Issue
Block a user