diff --git a/models/cacu/cancer_pim/model.toml b/models/cacu/cancer_pim/model.toml index 86ac9c1..5591444 100644 --- a/models/cacu/cancer_pim/model.toml +++ b/models/cacu/cancer_pim/model.toml @@ -16,14 +16,15 @@ corrección del sesgo de verificación ni validación clínica.""" # The dataflow's config (`with_config`); each key is an input of the nodes that name it. # What the model's number is, as the patient's screen and the governance pages show it. [estimand] -quantity = "Riesgo acumulado" +quantity = "Probabilidad" description = "Probabilidad de que la paciente tenga cáncer cervicouterino en la fecha índice o lo desarrolle antes de cada horizonte." outcome = "Cáncer: biopsia de carcinoma" -index_date = "la última citología con resultado de citología y de VPH, en pacientes sin colposcopía; cada citología nueva es una nueva fecha índice. Sin la historia de visitas previas (aproximación hasta reproducir la tabla 4 de KPNC)" +index_date = "la última citología con resultado de citología y de VPH" horizons_unit = "años" +covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC" [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] # The level of each risk's interval (delta method), given with the estimate; none gives no interval. risk_interval_level = 0.95 # From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results) diff --git a/models/cacu/cin2_pim/model.toml b/models/cacu/cin2_pim/model.toml index d2fbce9..1febbc9 100644 --- a/models/cacu/cin2_pim/model.toml +++ b/models/cacu/cin2_pim/model.toml @@ -15,14 +15,15 @@ corrección del sesgo de verificación ni validación clínica.""" # The dataflow's config (`with_config`); each key is an input of the nodes that name it. # What the model's number is, as the patient's screen and the governance pages show it. [estimand] -quantity = "Riesgo acumulado" +quantity = "Probabilidad" description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte." outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma" -index_date = "la última citología con resultado de citología y de VPH, en pacientes sin colposcopía; cada citología nueva es una nueva fecha índice. Sin la historia de visitas previas (aproximación hasta reproducir la tabla 4 de KPNC)" +index_date = "la última citología con resultado de citología y de VPH" horizons_unit = "años" +covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC" [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] # The level of each risk's interval (delta method), given with the estimate; none gives no interval. risk_interval_level = 0.95 # From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results) diff --git a/models/cacu/cin2_pim_post_colposcopy/model.toml b/models/cacu/cin2_pim_post_colposcopy/model.toml index 5250f82..f0acde0 100644 --- a/models/cacu/cin2_pim_post_colposcopy/model.toml +++ b/models/cacu/cin2_pim_post_colposcopy/model.toml @@ -14,14 +14,15 @@ sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+. # What the model's number is, as the patient's screen and the governance pages show it. [estimand] -quantity = "Riesgo acumulado" +quantity = "Probabilidad" description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte." outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma" index_date = "la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+" horizons_unit = "años" +covariates = "grado de la citología que la refirió a colposcopía (un ajuste por grado), VPH y citología de la visita índice en tres categorías de KPNC" [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] # The level of each risk's interval (delta method), given with the estimate; none gives no interval. risk_interval_level = 0.95 event_grades = ["LIEAG", "CIS", "CARCINOMA"] diff --git a/models/cacu/cin2_pim_post_treatment/model.toml b/models/cacu/cin2_pim_post_treatment/model.toml index de33468..6264b97 100644 --- a/models/cacu/cin2_pim_post_treatment/model.toml +++ b/models/cacu/cin2_pim_post_treatment/model.toml @@ -14,14 +14,15 @@ la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. S # What the model's number is, as the patient's screen and the governance pages show it. [estimand] -quantity = "Riesgo acumulado" +quantity = "Probabilidad" description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte." outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma" index_date = "la primera citología después del tratamiento" horizons_unit = "años" +covariates = "VPH y citología de la citología índice en tres categorías de KPNC" [config] -horizons_years = [0.0, 1.0, 3.0, 5.0] +horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] # The level of each risk's interval (delta method), given with the estimate; none gives no interval. risk_interval_level = 0.95 event_grades = ["LIEAG", "CIS", "CARCINOMA"] diff --git a/models/cacu/survival/estimator.py b/models/cacu/survival/estimator.py index 4468266..d028a39 100644 --- a/models/cacu/survival/estimator.py +++ b/models/cacu/survival/estimator.py @@ -105,16 +105,35 @@ class MemberFeatures(TransformerMixin, BaseEstimator): return table[[*FEATURES, INDEX_COLUMN]] +def _combinations(X: pd.DataFrame) -> pd.DataFrame: + """Each member's combination of the covariates, as `encode` reads them (a missing value is `UNKNOWN`).""" + return X[FEATURES].astype(object).where(X[FEATURES].notna(), UNKNOWN).astype(str).reset_index(drop=True) + + +def _frame(combinations: pd.DataFrame) -> pd.DataFrame: + return combinations.replace(UNKNOWN, None) + + class IntervalSurvival(BaseEstimator): """CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked; the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with `months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With `INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member - without one) and her mortality is empty too.""" + without one) and her mortality is empty too. - def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0)): + With `interval_level`, two more blocks follow the mortality: its interval's lower and upper ends. The covariates + are categorical, so every member of a combination gets the same mortality, and so the same interval: `fit` keeps + one per combination of the training members (`interval_table_`), the percentiles of the mortality of + `interval_replicas` refits of this same model on bootstrap resamples of them (seeded by `seed`). A combination the + training never saw has no interval.""" + + def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0), interval_level=None, interval_replicas=100, + seed=0): self.survival = survival self.horizons_years = horizons_years + self.interval_level = interval_level + self.interval_replicas = interval_replicas + self.seed = seed def fit(self, X: pd.DataFrame, y: pd.DataFrame): s = survival_settings(self.survival) @@ -130,8 +149,30 @@ class IntervalSurvival(BaseEstimator): self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), [] self.fitted_ = sm.fit_intervals(cohort, s, everyone, None) self.levels_ = cohort.levels + self.interval_table_ = self._interval_table(X, y) if self.interval_level else {} return self + def _interval_table(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[tuple, tuple[list, list]]: + combinations = _combinations(X).drop_duplicates() + rng = np.random.default_rng(self.seed) + replicas = [] + for _ in range(int(self.interval_replicas)): + rows = rng.integers(0, len(X), len(X)) + refit = IntervalSurvival(self.survival, self.horizons_years) + refit.fit(X.iloc[rows].reset_index(drop=True), y.iloc[rows].reset_index(drop=True)) + replicas.append(1.0 - refit.survival_proba(_frame(combinations))) + tail = 50 * (1 - self.interval_level) + low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0) + rows = combinations.itertuples(index=False) + return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)} + + def mortality_interval(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + """Each member's interval ends at each horizon: her combination's, empty for one the training never saw.""" + empty = ([np.nan] * len(self.horizons_years),) * 2 + ends = [self.interval_table_.get(tuple(c), empty) for c in _combinations(X).itertuples(index=False)] + return (np.array([e[0] for e in ends], dtype=float).reshape(len(X), -1), + np.array([e[1] for e in ends], dtype=float).reshape(len(X), -1)) + def interval_proba(self, X: pd.DataFrame) -> np.ndarray: """Each member's probability of surviving each interval, given she is alive at its start.""" X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_) @@ -144,6 +185,8 @@ class IntervalSurvival(BaseEstimator): def predict_proba(self, X: pd.DataFrame) -> np.ndarray: mortality = 1.0 - self.survival_proba(X) + if self.interval_level: + mortality = np.column_stack([mortality, *self.mortality_interval(X)]) if INDEX_COLUMN not in X.columns: return mortality dates = pd.to_datetime(X[INDEX_COLUMN]) diff --git a/models/cacu/survival/model.py b/models/cacu/survival/model.py index 1ec213e..03c1acb 100644 --- a/models/cacu/survival/model.py +++ b/models/cacu/survival/model.py @@ -75,9 +75,12 @@ def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> d return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event") -def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival: - """The interval survival fitted on the training members.""" - return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]]) +def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float], + risk_interval_level: float | None = None, risk_interval_replicas: int = 100) -> IntervalSurvival: + """The interval survival fitted on the training members, with each combination's bootstrap interval at + `risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run).""" + return IntervalSurvival(survival, tuple(horizons_years), risk_interval_level, risk_interval_replicas).fit( + train_set[FEATURES], train_set[["months", "event"]]) def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray: @@ -87,7 +90,7 @@ def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataF def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray: """The training members' mortality at each horizon (apparent performance).""" - return fitted_survival.predict_proba(train_set[FEATURES]) + return 1.0 - fitted_survival.survival_proba(train_set[FEATURES]) def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray, diff --git a/models/cacu/survival/model.toml b/models/cacu/survival/model.toml index f75b63d..7dd689d 100644 --- a/models/cacu/survival/model.toml +++ b/models/cacu/survival/model.toml @@ -9,25 +9,40 @@ 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.""" +# What the model's number is, as the patient's screen shows it. The model gives the probability of dying; the screen +# shows its complement, the probability of surviving, with the interval's ends swapped. +[estimand] +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 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" + [config] train_fraction = 0.7 # The model's horizons, in years; `survival.horizons` are the same in months. horizons_years = [1.0, 3.0, 5.0] +# The level of each risk's interval: per combination of the covariates, the percentiles of `risk_interval_replicas` +# refits on bootstrap resamples of the training members. None gives no interval. +risk_interval_level = 0.95 +risk_interval_replicas = 100 # The age at the index in bands, in years. The cytology and HPV are the most recent up to the index, at any distance. 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 @@ -68,7 +83,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)" diff --git a/models/io/registry.py b/models/io/registry.py index 72bd4b9..4a29b21 100644 --- a/models/io/registry.py +++ b/models/io/registry.py @@ -125,6 +125,14 @@ class ModelRegistry: def status(self, domain: str, scenario: str, version: str) -> str: return self._status(self.get(domain, scenario, version)) + def in_production(self, domain: str) -> list[str]: + """The scenarios of `domain` with a version holding the `produccion` alias, by name.""" + if domain not in DOMAINS: + raise ValueError(f"dominio desconocido: {domain!r}") + prefix = registered_name(domain, "") + models = self.client.search_registered_models(filter_string=f"name LIKE '{prefix}%'") + return sorted(m.name.removeprefix(prefix) for m in models if PRODUCTION_ALIAS in (m.aliases or {})) + def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion: """With no `version`, the one holding the `produccion` alias; with a version, that one, whatever its status (to test or compare a candidate). The status travels with it: confirming risks only diff --git a/tests/cacu/test_cacu_survival.py b/tests/cacu/test_cacu_survival.py index a210e1e..93572b3 100644 --- a/tests/cacu/test_cacu_survival.py +++ b/tests/cacu/test_cacu_survival.py @@ -37,7 +37,7 @@ CONFIG = SCENARIO.config WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()} LINEAGE = {"url": "cacu/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)} N = 240 -QUICK = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}} +QUICK = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}, "risk_interval_replicas": 20} def _row(pac_id, when, tipo, valor=None, source="t", source_id=None, first=None): @@ -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): @@ -129,22 +130,33 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort(): assert required == {"source_cohort", "cohort_lineage", "age_cuts", "cytology", "etiquetas", "horizons_years", "index", "survival", "train_fraction"} # `index` is required: the registered model re-indexes a build with it. - assert optional == {"calibration_bins", "report_panels"} + assert optional == {"calibration_bins", "report_panels", "risk_interval_level", "risk_interval_replicas"} + + +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): @@ -207,8 +219,9 @@ def test_the_dataflow_reaches_its_metrics_routines_and_population_record_without def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking, tmp_path): """Pins down: training on a build's file registers a version with its population record; estimating with it writes - one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with the members the - scenario leaves out absent. Fails if the version cannot score a build or the estimate keeps the cohort's index.""" + one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with its combination's + bootstrap interval holding it, and with the members the scenario leaves out absent. Fails if the version cannot + score a build, the estimate keeps the cohort's index, or the risks lose their interval.""" version = train(dataclasses.replace(SCENARIO, config=QUICK), CohortFile(cohort_file)) output = tmp_path / "estimate.parquet" @@ -219,7 +232,12 @@ 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 risks[["ic_bajo", "ic_alto"]].notna().all().all() + assert ((risks["ic_bajo"] <= risks["probabilidad"]) & (risks["probabilidad"] <= risks["ic_alto"])).mean() > 0.9 + 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] @@ -281,3 +299,19 @@ def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch): found = _run_notebook(path, cohort_file, "cacu", "survival", monkeypatch) assert sum(r["n"] for r in found["survival"]) == N + + +def test_the_survival_scenario_shows_the_probability_of_surviving(): + """Pins down: the scenario's estimand names the probability of surviving and marks it as the complement of the + model's number (the probability of dying), so the patient's record shows survival, with its covariates. Fails if + `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 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"] diff --git a/tests/cacu/test_cin2_pim.py b/tests/cacu/test_cin2_pim.py index ddc7cb1..901c0d3 100644 --- a/tests/cacu/test_cin2_pim.py +++ b/tests/cacu/test_cin2_pim.py @@ -270,7 +270,8 @@ def test_the_interval_brackets_the_same_risk(cohort_frame): def test_the_scenario_says_what_its_number_is(): """Pins down: `[estimand]` reaches the scenario with what the screens show next to each risk. Fails if the key is renamed or `Scenario.from_toml` stops reading it.""" - assert SCENARIO.estimand["quantity"] == "Riesgo acumulado" and SCENARIO.estimand["horizons_unit"] == "años" + assert SCENARIO.estimand["quantity"] == "Probabilidad" and SCENARIO.estimand["horizons_unit"] == "años" + assert "KPNC" in SCENARIO.estimand["covariates"] assert {"description", "outcome", "index_date"} <= set(SCENARIO.estimand) and "interval" not in SCENARIO.estimand diff --git a/tests/io/test_registry.py b/tests/io/test_registry.py index 535490c..d870f37 100644 --- a/tests/io/test_registry.py +++ b/tests/io/test_registry.py @@ -1,4 +1,4 @@ -"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and +"""What this module covers: the registry's promotion checks, promotion and retirement, the scenarios in production, the lineage of a version, and what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`). Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model; @@ -108,6 +108,19 @@ def test_retire_and_lineage(production_ready): registry.retire(domain, scenario, second) +def test_in_production_lists_the_scenarios_holding_the_alias(production_ready): + """Only scenarios of the domain with a version in production are listed; a candidate or a retired one is not. + Fails if `in_production` stops reading the `produccion` alias or leaks another domain's models.""" + domain, scenario, version = production_ready("v1") + production_ready("v1-dx", scenario="diagnostico") + assert registry.in_production(domain) == [] + registry.promote(domain, scenario, version) + assert registry.in_production(domain) == [scenario] + assert registry.in_production("cama") == [] + registry.retire(domain, scenario, version) + assert registry.in_production(domain) == [] + + @pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")]) def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario): with pytest.raises(ValueError):