Files
edgar f00dd31450 CaCu PIM estimands: a probability, its covariates, and the surveillance index in short
The quantity is "Probabilidad"; each scenario names the covariates it uses, which the patient's record writes under
the table; the surveillance and cancer scenarios name their index as the latest cytology with cytology and HPV
results.
2026-11-22 15:04:03 -06:00

464 lines
27 KiB
Python

"""What this module covers: `models.cacu.cin2_pim`: how a member's screening visits and biopsies become a code and an
interval (one test per worked example of `docs/codificacion_pim.md`), the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
driver, with every member scored at every horizon, also outside this repository.
Fixtures: `cohort_frame`, a long frame of 300 simulated members (a quarter with an abnormal index sample, some with a
prevalent or a later CIN2+ biopsy, the normal ones with a later negative cotest); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
`predict_without_repository` (conftest).
"""
import json
from datetime import date, datetime, timedelta, timezone
import mlflow.pyfunc
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cacu.cin2_pim import model
from models.dags import training
from models.dags.estimation import estimate
from models.io.contracts import COHORT_SCHEMA
from models.io.registry import PRODUCTION_ALIAS, registry
from models.io.storage import CohortFile
CUTOFF = date(2027, 6, 30)
SCENARIO = training.Scenario.load("cacu", "cin2_pim")
CONFIG = SCENARIO.config
def _row(pac_id, index, days, tipo, valor=None, sample=None):
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo,
"codigo": tipo, "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "t",
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
def _visit(pac_id, index, day, bethesda, vph, sample=None):
return [_row(pac_id, index, day, "bethesda", bethesda, sample), _row(pac_id, index, day, "vph", vph, sample)]
def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
"""The index sample (its Bethesda and HPV results share its source row, as in the timeline), later visits and
biopsies."""
sample = f"S{pac_id}"
rows = [_row(pac_id, index, 0, "citologia", sample=sample), *_visit(pac_id, index, 7, bethesda, vph, sample)]
rows += [row for day, b, v in visits for row in _visit(pac_id, index, day, b, v)]
return rows + [_row(pac_id, index, day, "biopsia", grade) for day, grade in biopsies]
def _coded(rows):
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
coded = model.interval_coded_members(frame, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
CONFIG["index_sample_days"], CONFIG["known_negative"], CONFIG["cytology"],
CONFIG["history"])
return tuple(coded.iloc[0][["c", "l", "r"]])
INDEX = date(2025, 1, 1)
ASCUS_HPV = ("ASC-US", "POSITIVO")
COTEST_NEGATIVE = ("NORMAL", "NEGATIVO")
@pytest.fixture
def cohort_frame():
"""Abnormal members (every fourth) are biopsied within 2 months, CIN2+ for a third of them; a tenth of the normal
ones has a CIN2+ biopsy between 1 and 2 years later. Index dates rise with `pac_id` over 2023-2024."""
rng = np.random.default_rng(0)
rows = []
for pac_id in range(1, 301):
index = date(2023, 1, 1) + timedelta(days=2 * pac_id)
if pac_id % 4 == 0:
grade = "LIEAG" if rng.random() < 0.35 else "NEGATIVO"
rows += _member(pac_id, index, "LIEBG", "POSITIVO", [(45, grade)])
elif rng.random() < 0.1:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")],
[(365, *COTEST_NEGATIVE)])
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", visits=[(int(rng.integers(300, 900)), *COTEST_NEGATIVE)])
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
table = pa.Table.from_pandas(cohort_frame, schema=COHORT_SCHEMA, preserve_index=False)
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), "armado_id": "3"}
path = tmp_path / "3.parquet"
pq.write_table(table.replace_schema_metadata(lineage), path)
return path
def test_patient_1_a_cin2_biopsy_at_the_referral_colposcopy_is_prevalent():
"""Patient 1: ASC-US/HPV+ at T0, colposcopy a month later finds CIN3. Pins down `(1, 0, 0)`: she counts as a case
in the prevalence and adds nothing to the incidence. Fails if a CIN2+ within the window stops being prevalent."""
assert _coded(_member(1, INDEX, *ASCUS_HPV, [(30, "LIEAG")])) == (1, 0.0, 0.0)
def test_patient_2_the_interval_opens_at_the_last_negative_not_at_the_index():
"""Patient 2: ASC-US/HPV+ at T0, negative biopsies at T1 (a month), negative cotest at T2 (a year), ASC-US/HPV+ at
T3 (two years), CIN3 at T4. Pins down `(0, T2, T4]`: the negative colposcopy makes her a control in the prevalence,
T2 is the last time she was free, and T3's abnormal result isn't a negative. Fails if `l` goes back to 0 or an
abnormal visit is taken for a negative."""
c, l, r = _coded(_member(2, INDEX, *ASCUS_HPV, [(30, "NEGATIVO"), (760, "LIEAG")],
[(365, *COTEST_NEGATIVE), (730, *ASCUS_HPV)]))
assert (c, l, r) == (0, pytest.approx(365 / 365.25), pytest.approx(760 / 365.25))
def test_patient_3_a_case_never_found_free_has_an_unknown_baseline():
"""Patient 3: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US/HPV+ again at T1, CIN3 at T2. Pins down
`(-999, 0, T2]`: she may have been prevalent or incident, the likelihood weighs both, and onset is anywhere up to
T2 (not exactly at T2). Fails if a repeated abnormal result is taken for a known baseline."""
c, l, r = _coded(_member(3, INDEX, *ASCUS_HPV, [(395, "LIEAG")], [(365, *ASCUS_HPV)]))
assert (c, l, r) == (-999, 0.0, pytest.approx(395 / 365.25))
def test_patient_4_a_later_negative_cotest_settles_an_unknown_baseline():
"""Patient 4: ASC-US/HPV+ at T0, colposcopy skipped, negative cotest at T1 (a year). Pins down `(0, T1, inf)`: CIN2+
being absorbing, free at T1 means free at T0, so she's a control in the prevalence and right-censored at T1. Fails
if she's left unknown, which throws her away, or censored at the cut-off."""
c, l, r = _coded(_member(4, INDEX, *ASCUS_HPV, visits=[(365, *COTEST_NEGATIVE)]))
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
def test_an_hpv_negative_ascus_is_a_negative_visit():
"""KPNC's second negative without histology: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US with HPV negative at T1
(a year). Pins down `(0, T1, inf)`, as for patient 4's negative cotest. Fails if `known_negative` goes back to NILM
only, which leaves her unknown."""
c, l, r = _coded(_member(7, INDEX, *ASCUS_HPV, visits=[(365, "ASC-US", "NEGATIVO")]))
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
def test_an_hpv_positive_nilm_is_not_a_negative_visit():
"""The other side of the criterion: ASC-US/HPV+ at T0, colposcopy skipped, NILM with HPV positive at T1. Pins down
`(-999, 0, inf)`: a positive test without histology leaves the status unknown. Fails if a NILM alone counts."""
assert _coded(_member(8, INDEX, *ASCUS_HPV, visits=[(365, "NORMAL", "POSITIVO")])) == (-999, 0.0, np.inf)
def test_patient_5_a_negative_colposcopy_without_follow_up_counts_only_for_the_prevalence():
"""Patient 5: ASC-US/HPV+ at T0, negative biopsies a month later, no further visit. Pins down `(0, 0, inf)`: a
control in the prevalence whose factor holds no survival (S(0) = 1). Fails if she's credited follow-up up to the
cut-off that no test checked."""
assert _coded(_member(5, INDEX, *ASCUS_HPV, [(30, "NEGATIVO")])) == (0, 0.0, np.inf)
def test_patient_6_referred_and_lost_carries_no_information():
"""Patient 6: ASC-US/HPV+ at T0, colposcopy skipped, never seen again. Pins down `(-999, 0, inf)`, whose factor
is 1. Fails if she's given a code that adds a term."""
assert _coded(_member(6, INDEX, *ASCUS_HPV)) == (-999, 0.0, np.inf)
def test_the_graph_takes_exactly_its_config_and_the_cohort():
"""Pins down the driver's external inputs: the loaders' `source_cohort` and `cohort_lineage` (the scenario's index
re-indexes the first into `cohort`) and the config's keys, and nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
or a module added to the driver rewires a parameter."""
required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG))
assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence",
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
"train_fraction"}
# `index` from the config (a scenario without one keeps its cohort's index); the report's settings have defaults.
assert optional == {"index", "prediction_index", "report_panels", "risk_interval_level", "turnbull_bootstrap"}
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
"""Pins down: the graph runs from a frame to aggregates per horizon with no file and no MLflow, and the expected
rate at the index visit is near the observed one. Fails if a horizon is dropped, a metric isn't a number, or the
fit stops recovering the prevalence."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["metrics"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["metrics"]
assert found["n_train"] == 210 and found["n_test"] == 90
assert {f"n_known_{h:g}y" for h in CONFIG["horizons_years"]} <= set(found)
assert all(isinstance(value, (int, float)) for value in found.values())
assert found["expected_0y"] == pytest.approx(found["observed_0y"], abs=0.05)
def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path,
predict_without_repository):
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per
precolposcopy member (no biopsy) and horizon, dated at her latest complete cytology, a risk that doesn't fall
with the horizon, the same outside this repository, and storable metadata. Fails if the model or the estimate go
back to one horizon, a biopsied member is scored, or the registered model needs this repository."""
version = training.train(SCENARIO, CohortFile(cohort_file))
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
output = tmp_path / "estimate.parquet"
estimate(SCENARIO, CohortFile(cohort_file), output)
risks = pd.read_parquet(output)
frame = pd.read_parquet(cohort_file)
biopsied = set(frame.loc[frame["tipo"] == "biopsia", "pac_id"])
assert set(risks["pac_id"]) == set(frame["pac_id"]) - biopsied
assert len(risks) == (300 - len(biopsied)) * len(CONFIG["horizons_years"])
scored = risks.dropna(subset=["ic_bajo"])
assert len(scored) and ((scored["ic_bajo"] <= scored["probabilidad"]) & (scored["probabilidad"] <= scored["ic_alto"])).all()
by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad")
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2"
uri = registry.resolve("cacu", "cin2_pim", version).model_uri
outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
assert outside.shape == (300, 1 + 3 * len(CONFIG["horizons_years"]))
np.testing.assert_allclose(outside.to_numpy(), inside)
def test_the_prediction_index_is_the_latest_complete_cytology_before_any_colposcopy():
"""Pins down the surveillance model's prediction index: the latest cytology with both results; one missing its
HPV gives way to the one before; a patient with a colposcopy or a biopsy gets none (the post-colposcopy scenario
scores her). Fails if the index goes back to the cohort's first cytology or a referred patient is scored."""
def sample(pac_id, day, bethesda, vph):
key = f"S{pac_id}-{day}"
rows = [_row(pac_id, INDEX, day, "citologia", sample=key), _row(pac_id, INDEX, day + 7, "bethesda", bethesda, key)]
return rows + ([_row(pac_id, INDEX, day + 7, "vph", vph, key)] if vph else [])
rows = [*sample(1, 0, "ASC-US", "NEGATIVO"), *sample(1, 700, "LIEBG", "POSITIVO"),
*sample(2, 0, "NORMAL", "NEGATIVO"), *sample(2, 900, "LIEBG", None),
*sample(3, 0, "LIEBG", "POSITIVO"), _row(3, INDEX, 40, "colposcopia"), *sample(3, 400, "NORMAL", "NEGATIVO")]
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = model.latest_index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
assert found["pac_id"].tolist() == [1, 2, 3]
assert found[model.INDEX_COLUMN].dt.date.tolist()[:2] == [INDEX + timedelta(days=700), INDEX]
assert found["cytology"].tolist()[:2] == ["LSIL", "NILM"] and found["hpv_positive"].tolist()[:2] == [1.0, 0.0]
assert pd.isna(found[model.INDEX_COLUMN].iloc[2]) and pd.isna(found["cytology"].iloc[2])
def test_the_registered_model_dates_each_risk_at_its_prediction_index(cohort_frame):
"""Pins down: with `prediction_index` the registered model gives the index date first (days since 1970) and the
risk of that visit's results, and no risk to a member without one. Fails if the date column is dropped, the
risk is computed from the cohort's index, or a member without an index gets a risk."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["fitted_model", "fitted_mixture"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
output = found["fitted_model"].predict_proba(cohort_frame)
features = model.latest_index_results(cohort_frame, CONFIG["index_sample_days"], CONFIG["cytology"])
h = len(CONFIG["horizons_years"])
dated = ~np.isnan(output[:, 0])
assert dated.sum() == features[model.INDEX_COLUMN].notna().sum() and np.isnan(output[~dated, 1:]).all()
np.testing.assert_allclose(output[dated, 0], (features.loc[dated, model.INDEX_COLUMN] - model.EPOCH).dt.days)
expected = found["fitted_mixture"].predict_proba(features.loc[dated, model._features(CONFIG["history"])])
np.testing.assert_allclose(output[dated, 1:1 + h], expected)
def test_the_interval_brackets_the_same_risk(cohort_frame):
"""Pins down: with `interval_level` the mixture gives the risk unchanged and, after it, the interval's lower and
upper ends around it, NaN only where the risk is. Fails if the delta method moves the point, the blocks' order
changes, or an end crosses the risk."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["fitted_mixture", "test_set", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
X = found["test_set"][model._features(CONFIG["history"])]
h = len(CONFIG["horizons_years"])
point = found["fitted_mixture"].predict_proba(X)
banded = found["fitted_model"].named_steps["mixture"].predict_proba(X)
assert found["fitted_mixture"].interval_level is None and banded.shape == (len(X), 3 * h)
np.testing.assert_allclose(banded[:, :h], point)
low, high, known = banded[:, h:2 * h], banded[:, 2 * h:], ~np.isnan(point)
assert (np.isnan(low) == ~known).all() and (low[known] <= point[known]).all() and (point[known] <= high[known]).all()
assert (high[known] - low[known]).max() > 0
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"] == "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
def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame):
"""Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN
(not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up."""
members = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["interval_coded_members"]
only_negative = members[members["hpv_positive"] == 0]
mixture = model.PrevalenceIncidenceMixture(CONFIG["horizons_years"], ("cytology",), ("hpv_positive",),
CONFIG["incidence"], {"cytology": list(CONFIG["cytology"])}).fit(
only_negative[model.FEATURES], only_negative[["c", "l", "r"]])
risks = mixture.predict_proba(members[model.FEATURES])
assert list(mixture.fits_) == [(0,)]
assert np.isnan(risks[members["hpv_positive"].to_numpy() == 1]).all()
assert not np.isnan(risks[members["hpv_positive"].to_numpy() == 0]).any()
def test_the_index_cytology_takes_kpncs_categories_not_a_binary():
"""Pins down the cytology of the TOML: each squamous or glandular code goes to its KPNC category (LIEBG is LSIL;
CIS and adenocarcinoma are HSIL+), with both results the more severe wins (AGC over ASC-US, HSIL+ over AGC), and a
member without a cytology gets none rather than the reference. Fails if the categories collapse back to
normal/abnormal, the glandular result is ignored, or a missing cytology is read as NILM."""
rows = [*_member(1, INDEX, "LIEBG", "POSITIVO"), *_member(2, INDEX, "CIS", "NEGATIVO"),
*_member(3, INDEX, "NORMAL", "NEGATIVO"), *_member(4, INDEX, "ASC-US", "POSITIVO"),
*_member(5, INDEX, "LIEAG", "POSITIVO"), *_member(6, INDEX, "NORMAL", "POSITIVO")]
glandular = [(4, "AGC"), (5, "AGC"), (6, "ADENOCARCINOMA")]
rows += [_row(pac_id, INDEX, 7, "glandular", code) for pac_id, code in glandular]
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
frame = frame[~((frame["pac_id"] == 3) & (frame["tipo"] == "bethesda"))]
found = model.index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
assert found["cytology"].tolist() == ["LSIL", "HSIL+", None, "AGC", "HSIL+", "HSIL+"]
POST_COLPOSCOPY = training.Scenario.load("cacu", "cin2_pim_post_colposcopy")
def _with_referral(rows, pac_id, index, bethesda, vph, colposcopy_days=-200, referral_days=-300):
"""A member's rows plus a referral result and a colposcopy before her index date."""
return rows + [*_visit(pac_id, index, referral_days, bethesda, vph), _row(pac_id, index, colposcopy_days, "colposcopia")]
def test_the_referral_grade_follows_kpncs_low_and_high_grade():
"""Pins down the history of the post-colposcopy TOML: HPV-positive NILM and LSIL referrals are low grade, ASC-H
high, an HPV-negative NILM refers no one and a result past the lookback doesn't count. Fails if the grade stops
reading the referral before the colposcopy, its HPV condition or the lookback."""
config = POST_COLPOSCOPY.config
rows = []
for pac_id, (bethesda, vph, referral_days) in enumerate([("NORMAL", "POSITIVO", -300), ("LIEBG", "NEGATIVO", -300),
("ASC-H", "NEGATIVO", -300), ("NORMAL", "NEGATIVO", -300),
("ASC-H", "POSITIVO", -700)], start=1):
rows = _with_referral(rows + _member(pac_id, INDEX, "NORMAL", "NEGATIVO"), pac_id, INDEX, bethesda, vph,
referral_days=referral_days)
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = model.index_results(frame, config["index_sample_days"], config["cytology"], config["history"])
assert found["referral_grade"].tolist() == ["low", "low", "high", None, None]
assert found["cytology"].tolist() == ["NILM"] * 5
def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame):
"""Pins down that a scenario is only its TOML: the post-colposcopy one runs `cin2_pim`'s dataflow with its own
cytology groups and referral grade, and gives metrics at every horizon. Fails if the shared dataflow stops taking
the history from the config or a scenario needs code of its own."""
rows = cohort_frame.to_dict("records")
for pac_id, group in cohort_frame.groupby("pac_id"):
index = group["fecha_indice"].iloc[0]
rows = _with_referral(rows, pac_id, index, "ASC-H" if pac_id % 3 == 0 else "LIEBG", "POSITIVO")
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = training.dataflow(*POST_COLPOSCOPY.modules, config=POST_COLPOSCOPY.config).execute(
["metrics"], inputs={"source_cohort": frame, "cohort_lineage": {}})["metrics"]
assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found)
assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento"
def test_the_subgroup_report_sets_each_combinations_mixture_against_turnbull(cohort_frame):
"""Pins down the report of every PIM scenario: one record per combination of the features present, its members
adding up to the coded members; Turnbull's cumulative risk never falls and stays in [0, 1] inside its band; the
model's risk sits inside its delta-method band; E/O, where Turnbull observed a case, equals E over O inside its
interval; the record names its methods and the page is Plotly's. Fails if a combination goes missing, Turnbull
stops respecting the intervals' ordering, a band is inverted, E/O loses its interval, or the methods go
unrecorded."""
config = {**CONFIG}
result = training.dataflow(*SCENARIO.modules, config=config).execute(
["population", "reports", "interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {},
"turnbull_bootstrap": 40})
record = result["population"]["subgrupos"]
combos = record["combinations"]
assert sum(c["n"] for c in combos) == len(result["interval_coded_members"])
assert set(record["metodos"]) == {"empirica", "modelo", "E/O"}
for c in combos:
emp = c["empirical"]
assert np.all(np.diff(emp["CR"]) >= -1e-12) and 0 <= emp["CR"][0] and emp["CR"][-1] <= 1 + 1e-12
assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(emp["low"], emp["CR"], emp["high"]))
if c["model"] is not None:
m = c["model"]
assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(m["low"], m["CR"], m["high"]))
for e in c["e_o"]:
if e["E_O"] is not None:
assert e["low"] <= e["E_O"] <= e["high"] and e["E_O"] == pytest.approx(e["E"] / e["O"])
assert any(e["E_O"] is not None for c in combos for e in c["e_o"])
json.dumps(record)
page = result["reports"]["subgrupos"]
assert page.startswith("<!doctype html>") and "Turnbull" in page and "método delta" in page
def test_turnbull_puts_a_prevalent_case_at_zero_and_an_interval_case_inside_its_interval():
"""Pins down Turnbull's coding: a prevalent member is mass at 0, a member found free and then a case is mass inside
`(l, r]`, a member free to the end carries mass beyond every finite point. Fails if the prevalence leaks past 0 or
a case is placed outside its interval."""
from models.cacu.cin2_pim.report import _at, _turnbull
c = np.array([1, 0, 0, 0])
l = np.array([0.0, 1.0, 2.0, 3.0])
r = np.array([0.0, 2.0, np.inf, np.inf])
support, cumulative = _turnbull(c, l, r)
assert _at(support, cumulative, [0.0])[0] == pytest.approx(0.25)
assert _at(support, cumulative, [2.0])[0] == pytest.approx(0.5)
assert _at(support, cumulative, [1.5])[0] == pytest.approx(0.25)
def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters):
"""Runs a notebook's code cells in this process, as the platform's runner would on a build's file (`COHORT_FILE`,
`MODELS_DOMAIN`, `MODELS_SCENARIO`), with `parameters` replacing its parameters cell; returns its namespace."""
import nbformat
monkeypatch.setenv("COHORT_FILE", str(cohort_file))
monkeypatch.setenv("MODELS_DOMAIN", domain)
monkeypatch.setenv("MODELS_SCENARIO", scenario)
namespace = {}
for cell in nbformat.read(path, as_version=4).cells:
if cell.cell_type != "code":
continue
exec(cell.source, namespace)
if "parameters" in cell.metadata.get("tags", []):
namespace.update(parameters)
return namespace
def test_the_subgroup_figure_draws_risks_in_percent():
"""Pins down: the report's curves are in percent, like the patient's risk and the table, with the axis saying so.
Fails if the figure goes back to proportions, which read as a risk a hundred times smaller."""
from models.cacu.cin2_pim import report
curve = {"years": [0.0, 5.0], "CR": [0.1, 0.2], "low": [0.05, 0.15], "high": [0.15, 0.25]}
record = {"combination": {"cytology": "LSIL", "hpv_positive": "positivo"}, "n": 10, "prevalent": 1,
"incident": 1, "empirical": curve, "model": curve, "e_o": []}
figure = report._figure([record], [0.0, 5.0])
assert [list(t.y) for t in figure.data if t.name in ("Turnbull", "Mezcla prevalencia-incidencia")] == [[10.0, 20.0]] * 2
assert figure.layout.yaxis.ticksuffix == " %" and "%" in figure.layout.yaxis.title.text
def test_each_subgroup_panel_has_its_own_scale():
"""Pins down: panels don't share the y axis, so each combination's curves fill their panel. Fails if the
subplots go back to one shared scale, where a 0.5 % curve is a flat line next to a 50 % one."""
from models.cacu.cin2_pim import report
def record(level, risk):
curve = {"years": [0.0, 5.0], "CR": [risk, risk], "low": [risk, risk], "high": [risk, risk]}
return {"combination": {"cytology": level, "hpv_positive": "positivo"}, "n": 10, "prevalent": 1,
"incident": 1, "empirical": curve, "model": curve, "e_o": []}
figure = report._figure([record("NILM", 0.005), record("HSIL+", 0.5)], [0.0, 5.0])
assert figure.layout.yaxis2.matches is None and figure.layout.yaxis2.anchor == "x2"
def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch):
"""Pins down the PIM report's notebook (`models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb`): its cells run on a
build's file with the platform's environment, compute the same combinations the dataflow does and draw them. Fails
if the notebook drifts from the report's functions or the scenario it is run for."""
from pathlib import Path
path = Path(model.__file__).parent / "notebooks" / "reporte_subgrupos.ipynb"
found = _run_notebook(path, cohort_file, "cacu", "cin2_pim", monkeypatch, turnbull_bootstrap=20)
assert found["risks"] and sum(r["n"] for r in found["risks"]) > 0 and found["turnbull_bootstrap"] == 20