Merge pull request 'CaCu models: survival interval, yearly PIM horizons, registry listing of production scenarios' (#14) from integration/cacu-indicadores into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/14
This commit was merged in pull request #14.
This commit is contained in:
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user