CaCu survival: a case is a carcinoma, invasive or in situ

The scenario's diagnosis is the first biopsy reported as CIS or invasive carcinoma (`event_grades`), so in situ cases
are followed too and a CIS before an invasive carcinoma is the index date.
This commit is contained in:
2026-11-22 19:16:05 -06:00
parent 34b26d8c85
commit c676dde0d0
2 changed files with 39 additions and 17 deletions
+5 -5
View File
@@ -9,7 +9,7 @@ modules = ["models.cacu.survival.model", "models.cacu.survival.population", "mod
"models.steps.indexing"]
description = """
Prototipo: mortalidad por cualquier causa a 1, 3 y 5 años del diagnóstico de cáncer (provisional: la primera biopsia \
con carcinoma invasor), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \
con carcinoma invasor o in situ), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \
recientes hasta él. Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana combinadas), \
como la de CaMa. Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la \
registra."""
@@ -20,7 +20,7 @@ registra."""
quantity = "Probabilidad de supervivencia"
description = "Probabilidad de que la paciente siga viva a cada horizonte desde el diagnóstico de cáncer."
outcome = "Muerte por cualquier causa"
index_date = "la primera biopsia con carcinoma invasor"
index_date = "la primera biopsia con carcinoma invasor o in situ"
horizons_unit = "años"
covariates = "grupo de edad al diagnóstico, citología (categorías de KPNC) y VPH más recientes hasta él"
complement = "supervivencia"
@@ -33,12 +33,12 @@ horizons_years = [1.0, 3.0, 5.0]
age_cuts = [35, 45, 55]
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). PROVISIONAL: the diagnosis is the
# first biopsy reported as invasive carcinoma (`CARCINOMA`; in situ is not), which is both the inclusion criterion and
# first biopsy reported as carcinoma, invasive or in situ (`CARCINOMA`, `CIS`), which is both the inclusion criterion and
# the index date; out: no birth date (no age), a death on or before the biopsy. The recruitment window is the source
# cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA"]
event_grades = ["CIS", "CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
@@ -79,7 +79,7 @@ ylim_sub = {}
# What the dashboard's survival chart says (provisional: to be defined with the clinicians).
[config.etiquetas]
titulo = "Supervivencia después de la biopsia con carcinoma invasor"
titulo = "Supervivencia después de la biopsia con carcinoma invasor o in situ"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
+34 -12
View File
@@ -71,8 +71,9 @@ def cohort_frame():
"""240 members, each with her birth, an old normal cotest, a latest cytology 1-6 months before her diagnosis (NILM,
LSIL or HSIL+; HPV positive or not), a CIS biopsy before the diagnosis for some, the diagnosis (a biopsy reported
as invasive carcinoma) in 2018-2020 and, if she dies by the cut-off, her death: exponential in months, faster with
HSIL+ and with a positive HPV. Members 241 to 244 must be left out: a CIS biopsy only (no index), no birth date
(`sin_nacimiento`), a death before the diagnosis (`defuncion_hasta_el_indice`), a diagnosis before the window."""
HSIL+ and with a positive HPV. Member 241 has a CIS biopsy only, which is her diagnosis (in situ counts); members
242 to 244 must be left out: no birth date (`sin_nacimiento`), a death before the diagnosis
(`defuncion_hasta_el_indice`), a diagnosis before the window."""
rng = np.random.default_rng(5)
rows = []
for pac_id in range(1, N + 1):
@@ -132,19 +133,30 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort():
assert optional == {"calibration_bins", "report_panels"}
def _primer_carcinoma(frame: pd.DataFrame) -> pd.Series:
"""Each member's first biopsy reported as carcinoma, in situ or invasive: the survival scenario's diagnosis."""
biopsias = frame[(frame["tipo"] == "biopsia") & frame["valor_codigo"].isin(["CIS", "CARCINOMA"])]
return biopsias.groupby("pac_id")["fecha"].min()
def test_the_index_is_the_first_carcinoma_biopsy_and_its_rules_leave_out_who_they_should(cohort_frame):
"""Pins down the provisional index: members 1 to 240 are indexed at their biopsy reported as invasive carcinoma, not
at an earlier CIS biopsy nor at their first observation; a CIS biopsy only (241), no birth date (242), a death
before the diagnosis (243) and a diagnosis before the window (244) leave the cohort. Fails if the scenario stops
taking `[config.index]`, counts in situ as the diagnosis, or takes the window from elsewhere than the lineage."""
"""Pins down the provisional index: each member is indexed at her first biopsy reported as carcinoma, in situ or
invasive, not at her first observation: an earlier CIS biopsy is the diagnosis (member 5), and a CIS biopsy only
(241) is a case too; no birth date (242), a death before the diagnosis (243) and a diagnosis before the window
(244) leave the cohort. Fails if the scenario stops taking `[config.index]`, drops in situ from the diagnosis, or
takes the window from elsewhere than the lineage."""
attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"]))
indexed = _indexed(cohort_frame)
assert set(indexed["pac_id"].unique()) == set(range(1, N + 1))
assert attrition["sin_nacimiento"] == N + 1 and attrition["defuncion_hasta_el_indice"] == N
# a CIS 20 days before a diagnosis at the window's start puts that member's diagnosis before the window
inicio = date.fromisoformat(WINDOW["recruitment_start"])
antes = set(_primer_carcinoma(cohort_frame)[lambda d: d < inicio].index) & set(range(1, N + 1))
assert set(indexed["pac_id"].unique()) == (set(range(1, N + 1)) | {241}) - antes
assert attrition["sin_nacimiento"] == N + 2 - len(antes)
assert attrition["defuncion_hasta_el_indice"] == N + 1 - len(antes)
five = cohort_frame[cohort_frame["pac_id"] == 5]
diagnosis = five[(five["tipo"] == "biopsia") & (five["valor_codigo"] == "CARCINOMA")]["fecha"].iloc[0]
assert indexed[indexed["pac_id"] == 5]["fecha_indice"].iloc[0] == diagnosis
in_situ = five[(five["tipo"] == "biopsia") & (five["valor_codigo"] == "CIS")]["fecha"].iloc[0]
assert indexed[indexed["pac_id"] == 5]["fecha_indice"].iloc[0] == in_situ
def test_the_covariates_are_the_most_recent_observations_up_to_the_diagnosis(cohort_frame):
@@ -219,7 +231,10 @@ def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_mode
assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html", "diagramas/pipeline.dot",
"diagramas/pipeline.svg"} <= set(files)
risks = pq.read_table(output).to_pandas()
assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} and set(risks["pac_id"]) == set(range(1, N + 1))
inicio = date.fromisoformat(WINDOW["recruitment_start"])
antes = set(_primer_carcinoma(read_cohort(cohort_file))[lambda d: d < inicio].index)
assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0}
assert set(risks["pac_id"]) == (set(range(1, N + 1)) | {241}) - antes
frame = read_cohort(cohort_file)
diagnosis = frame[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "CARCINOMA") & (frame["pac_id"] == 1)]
assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == diagnosis["fecha"].iloc[0]
@@ -289,4 +304,11 @@ def test_the_survival_scenario_shows_the_probability_of_surviving():
`complement` is dropped: the record would show a death probability labelled as survival."""
estimand = Scenario.load("cacu", "survival").estimand
assert estimand["quantity"] == "Probabilidad de supervivencia" and estimand["complement"] == "supervivencia"
assert estimand["index_date"] == "la primera biopsia con carcinoma invasor" and "VPH" in estimand["covariates"]
assert estimand["index_date"] == "la primera biopsia con carcinoma invasor o in situ"
assert "VPH" in estimand["covariates"]
def test_a_survival_case_is_a_carcinoma_invasive_or_in_situ():
"""Pins down: the survival scenario's index is the first biopsy of CIS or invasive carcinoma, so in situ cases are
followed too. Fails if CIS drops out of the index, which would leave its patients without a survival estimate."""
assert Scenario.load("cacu", "survival").config["index"]["event_grades"] == ["CIS", "CARCINOMA"]