CaCu PIM: risk intervals, what the number is, and the surveillance risk from the latest cytology
- The registered mixture gives each risk's interval at `risk_interval_level` (delta method on the log scale, from the fit's inverse Hessian), so the patient's risk carries it. - `[estimand]` in `model.toml` says what the model's number is (quantity, outcome, index date, unit of the horizons, interval), read into `Scenario.estimand` for the screens that show it. - The surveillance scenario predicts from each patient's latest cytology with both cytology and HPV results, before any colposcopy (`prediction_index = "ultima_citologia"`): every new complete sample is a new index date, and a sample still missing a result gives way to the one before. Patients past a colposcopy are the post-colposcopy scenario's. Training keeps the first cytology in the window. The rule runs inside the registered model, so it loads without this repository.
This commit is contained in:
@@ -163,7 +163,7 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
"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", "report_panels", "turnbull_bootstrap"}
|
||||
assert optional == {"index", "prediction_index", "report_panels", "risk_interval_level", "turnbull_bootstrap"}
|
||||
|
||||
|
||||
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
||||
@@ -181,9 +181,10 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
||||
|
||||
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 member
|
||||
and horizon, 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, or the registered model needs this 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"
|
||||
@@ -191,7 +192,12 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
|
||||
estimate(SCENARIO, CohortFile(cohort_file), output)
|
||||
|
||||
risks = pd.read_parquet(output)
|
||||
assert len(risks) == 300 * len(CONFIG["horizons_years"])
|
||||
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"
|
||||
@@ -199,10 +205,75 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
|
||||
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, len(CONFIG["horizons_years"]))
|
||||
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"] == "Riesgo acumulado" and SCENARIO.estimand["horizons_unit"] == "años"
|
||||
assert {"description", "outcome", "index_date", "interval"} <= set(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."""
|
||||
|
||||
Reference in New Issue
Block a user