Each scenario's index and rules in its pipeline, matching dbt's cohorts
models/steps/indexing.py: a scenario that lists it gets its source cohort as `source_cohort`, and the node `cohort` re-indexes it by `[config.index]` of its model.toml: the surveillance kind (first cytology) and the post-colposcopy kind (visit k), with dbt's rules in dbt's order and names, the recruitment window taken from the source cohort's parameters. Every kind ends with `observacion_previa_insuficiente`, a threshold on the days observed before the index (0 for now: the data are left-truncated, so rules on earlier events read only what was recorded). On the synthetic copy the pipeline gives dbt's patients, index dates and attrition for cin2_pim and cin2_logistic (surveillance) and cin2_pim_post_colposcopy (visit 1, now on cacu/cohorte_total). cin2_logistic's MUESTREO records the index attrition and the prior history; a stored build's lineage carries its parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
@@ -151,13 +151,13 @@ def test_split_trains_on_the_oldest_index_dates(cohort_frame):
|
||||
|
||||
|
||||
def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
"""Pins down the driver's external inputs: the loaders' `cohort` and `cohort_lineage` and the config's keys, and
|
||||
"""Pins down the driver's external inputs: the loaders' `source_cohort` (re-indexed into `cohort` by the scenario's index) and `cohort_lineage` 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(dataflow(*SCENARIO.modules, config=CONFIG))
|
||||
|
||||
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
|
||||
assert optional == {"calibration_bins", "classifier", "max_iter", "split_order", "target_column"}
|
||||
assert required == {"source_cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
|
||||
assert optional == {"calibration_bins", "classifier", "index", "max_iter", "split_order", "target_column"}
|
||||
|
||||
|
||||
def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
|
||||
@@ -168,7 +168,7 @@ def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
|
||||
lineage = {"datos_as_of": CUTOFF.isoformat()}
|
||||
found = dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
||||
["metrics", "fitted_model", "test_set", "test_probabilities"],
|
||||
inputs={"cohort": cohort_frame, "cohort_lineage": lineage})
|
||||
inputs={"source_cohort": cohort_frame, "cohort_lineage": lineage})
|
||||
|
||||
assert found["metrics"]["n_train"] == 14 and found["metrics"]["n_test"] == 6
|
||||
probabilities = found["fitted_model"].predict_proba(cohort_frame)
|
||||
|
||||
+15
-12
@@ -28,19 +28,22 @@ SCENARIO = training.Scenario.load("cacu", "cin2_pim")
|
||||
CONFIG = SCENARIO.config
|
||||
|
||||
|
||||
def _row(pac_id, index, days, tipo, valor=None):
|
||||
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": f"{pac_id}-{tipo}-{days}"}
|
||||
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
|
||||
|
||||
|
||||
def _visit(pac_id, index, day, bethesda, vph):
|
||||
return [_row(pac_id, index, day, "bethesda", bethesda), _row(pac_id, index, day, "vph", vph)]
|
||||
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=()):
|
||||
rows = [_row(pac_id, index, 0, "citologia"), *_visit(pac_id, index, 7, bethesda, vph)]
|
||||
"""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]
|
||||
|
||||
@@ -150,15 +153,15 @@ def test_patient_6_referred_and_lost_carries_no_information():
|
||||
|
||||
|
||||
def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
"""Pins down the driver's external inputs: the loader's `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,
|
||||
"""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 == {"cohort", "cytology", "event_grades", "history", "horizons_years", "incidence",
|
||||
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"}
|
||||
assert optional == set()
|
||||
assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index
|
||||
|
||||
|
||||
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
||||
@@ -166,7 +169,7 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
||||
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={"cohort": cohort_frame})["metrics"]
|
||||
["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)
|
||||
@@ -202,7 +205,7 @@ def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort
|
||||
"""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={"cohort": cohort_frame})["interval_coded_members"]
|
||||
["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(
|
||||
@@ -271,7 +274,7 @@ def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame):
|
||||
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
|
||||
found = training.dataflow(*POST_COLPOSCOPY.modules, config=POST_COLPOSCOPY.config).execute(
|
||||
["metrics"], inputs={"cohort": frame})["metrics"]
|
||||
["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"
|
||||
|
||||
Reference in New Issue
Block a user