From 22d1fda0f37c01dc9f93c30756d53742dde3783e Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:15:12 -0600 Subject: [PATCH] CaCu CIN2+ prototype: a CIN2+ biopsy within a provisional 12-month window, predicted from the index sample's results --- README.md | 2 +- models/cacu/cin2_logistic/model.py | 93 +++++++++++++++------ models/cacu/cin2_logistic/model.toml | 10 ++- tests/cacu/test_cin2_logistic.py | 120 ++++++++++++++++++--------- 4 files changed, 159 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index 510658b..165f792 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ WebApi. | `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. | | `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | | `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | -| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. Estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--armado N] [--version N]` (`estimate.py`); by default it uses the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | +| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. | diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py index 9fdeed8..4e8c8d3 100644 --- a/models/cacu/cin2_logistic/model.py +++ b/models/cacu/cin2_logistic/model.py @@ -1,19 +1,25 @@ -"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version. +"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology. -No clinical meaning. `y` is 1 if any Bethesda result isn't `NORMAL`, and `days` runs from the index date to the first -abnormal result, or to the last result when `y` is 0. `days` is only known after the outcome, so the metrics say -nothing about performance. +`y` is 1 when a biopsy graded in `event_grades` falls within `outcome_window_months` of the index date. A member with +no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet: +it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda +category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported; +nothing after them is used. Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver. """ import tomllib +from datetime import date from pathlib import Path import mlflow.pyfunc import pandas as pd +from sklearn.compose import ColumnTransformer from sklearn.linear_model import LogisticRegression from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import OneHotEncoder from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256 from models.io.registry import registry @@ -21,7 +27,9 @@ from models.io.storage import read_cohort, read_metadata from models.io.tracking import TrainingRun SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text()) -NORMAL = "NORMAL" +PREDICTORS = ("bethesda", "vph", "vph_16_18") +MISSING = "(none)" +DAYS_PER_MONTH = 30.44 def cohort(cohort_path: str) -> pd.DataFrame: @@ -42,16 +50,44 @@ def code_sha256() -> str: return file_sha256(folder / "model.py", folder / "model.toml") -def prepare(cohort: pd.DataFrame) -> pd.DataFrame: - """One row per member with a Bethesda result: `pac_id`, `fecha_indice`, `y`, `days`.""" - results = cohort[cohort["tipo"] == "bethesda"].copy() - results["days"] = (pd.to_datetime(results["fecha"]) - pd.to_datetime(results["fecha_indice"])).dt.days - results["abnormal"] = results["valor_codigo"] != NORMAL - members = results.groupby(["pac_id", "fecha_indice"], as_index=False).agg(y=("abnormal", "any"), last=("days", "max")) - first_abnormal = results[results["abnormal"]].groupby("pac_id")["days"].min() - members["days"] = members["pac_id"].map(first_abnormal).fillna(members["last"]).astype(int) - members["y"] = members["y"].astype(int) - return members[["pac_id", "fecha_indice", "y", "days"]] +def cutoff(lineage: dict) -> date: + """The build's cut-off: no event after it is in the file.""" + return date.fromisoformat(lineage["datos_as_of"]) + + +def predictors(cohort: pd.DataFrame) -> pd.DataFrame: + """One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none.""" + members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]] + sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])] + sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample") + results = cohort.merge(sample, left_on="pac_id", right_index=True) + results = results[results["fuente_id"] == results["sample"]] + genotype = results["tipo"] == "vph_genotipo_16_18" + results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"}) + results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"}) + wide = results[results["tipo"].isin(PREDICTORS)].pivot_table( + index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first") + wide = wide.reindex(columns=list(PREDICTORS)) + return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna( + {name: MISSING for name in PREDICTORS}) + + +def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame: + """One row per member: `y`, and `known`, whether the window is complete or the event already happened.""" + window = SETTINGS["outcome_window_months"] * DAYS_PER_MONTH + days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days + event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(SETTINGS["event_grades"]) & days.between(0, window) + members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]] + members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int) + follow_up = (pd.Timestamp(cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days + members["known"] = (members["y"] == 1) | (follow_up >= window) + return members[["pac_id", "y", "known"]] + + +def prepare(predictors: pd.DataFrame, outcome: pd.DataFrame) -> pd.DataFrame: + """The members whose outcome is known, with their predictors and `y`.""" + labelled = predictors.merge(outcome, on="pac_id") + return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True) def split(prepare: pd.DataFrame) -> dict: @@ -69,33 +105,38 @@ def test(split: dict) -> pd.DataFrame: return split["test"] -def fit(train: pd.DataFrame) -> LogisticRegression: - return LogisticRegression().fit(train[["days"]], train["y"]) +def fit(train: pd.DataFrame) -> Pipeline: + """One-hot predictors, an unseen category counted as none of the known ones, and a logistic regression.""" + encode = ColumnTransformer([("results", OneHotEncoder(handle_unknown="ignore"), list(PREDICTORS))]) + return Pipeline([("encode", encode), ("logistic", LogisticRegression(max_iter=1000))]).fit( + train[list(PREDICTORS)], train["y"]) -def predict(fit: LogisticRegression, test: pd.DataFrame) -> pd.Series: +def predict(fit: Pipeline, test: pd.DataFrame) -> pd.Series: """The probability of `y` for each row of `test`.""" - return pd.Series(fit.predict_proba(test[["days"]])[:, 1], index=test.index, name="probabilidad") + return pd.Series(fit.predict_proba(test[list(PREDICTORS)])[:, 1], index=test.index, name="probabilidad") def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dict: """Aggregates only: no patient data reaches MLflow.""" return {"auc": float(roc_auc_score(test["y"], predict)), "brier": float(brier_score_loss(test["y"], predict)), - "n_train": len(train), "n_test": len(test), "positive_rate_test": float(test["y"].mean())} + "n_train": len(train), "n_test": len(test), "positive_rate_train": float(train["y"].mean()), + "positive_rate_test": float(test["y"].mean()), "mean_probability_test": float(predict.mean())} class Cin2Logistic(mlflow.pyfunc.PythonModel): - """The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`.""" + """The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad` + for every member, whether their outcome is known or not.""" - def __init__(self, fitted: LogisticRegression): + def __init__(self, fitted: Pipeline): self.fitted = fitted def predict(self, context, model_input, params=None): - members = prepare(model_input) + members = predictors(model_input) return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members)) -def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str, +def registered_model(fit: Pipeline, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str, code_sha256: str, environment: str) -> str: """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content, and which build it is, from the kit or from dbt's rules.""" @@ -105,7 +146,9 @@ def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, coh cohorte_armado_id=armado_id, cohort=cohort) run.log_model(Cin2Logistic(fit)) run.finish(metrics=evaluate, hyperparameters={ - "cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256}) + "cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256, + "outcome_window_months": SETTINGS["outcome_window_months"], "event_grades": ",".join(SETTINGS["event_grades"]), + "horizon_years": SETTINGS["outcome_window_months"] / 12}) version = registry.register_run(run) registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"]) return version diff --git a/models/cacu/cin2_logistic/model.toml b/models/cacu/cin2_logistic/model.toml index 77a7594..10ebeda 100644 --- a/models/cacu/cin2_logistic/model.toml +++ b/models/cacu/cin2_logistic/model.toml @@ -2,6 +2,12 @@ domain = "cacu" scenario = "cin2_logistic" cohort = "cacu/cohorte_vigilancia" train_fraction = 0.7 +# Provisional, to be decided with the domain expert: the window in which a CIN2+ biopsy counts as the outcome. On the +# DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 24-month window leaves no member with a +# complete window; 12 months leaves 5,231 known members, 162 with the event. +outcome_window_months = 12 +event_grades = ["LIEAG", "CIS", "CARCINOMA"] description = """ -Modelo de prueba de la cadena de entrenamiento, sin significado clínico. Los días se conocen solo después del \ -desenlace, así que sus métricas no dicen nada sobre su desempeño.""" +Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \ +a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \ +validación clínica.""" diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index fc3afcf..b9ea0fb 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -1,10 +1,11 @@ -"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal -split, that training on a build's file registers a version with its lineage, and the `models train` and -`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none. +"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members +whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on +a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run` +commands over it, repeating no step. Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a -build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a -SQLite-backed MLflow. +build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2 +of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow. """ from datetime import date, datetime, timedelta, timezone @@ -22,88 +23,132 @@ from models.io.contracts import COHORT_SCHEMA as SCHEMA from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG from models.io.registry import PRODUCTION_ALIAS, registry +CUTOFF = date(2027, 6, 30) -def _row(pac_id, index, days, valor, tipo="bethesda"): + +def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None): + clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion") 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": "citologiacervical", - "fuente_id": f"{pac_id}-{tipo}-{days}"} + "conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo, + "valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical", + "fuente_id": sample or f"{pac_id}-{tipo}-{days}"} + + +def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60): + """The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given.""" + sample = f"S{pac_id}" + rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample), + _row(pac_id, index, 7, "vph", vph, sample)] + if biopsy: + rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy)) + return rows @pytest.fixture def cohort_frame(): - """Odd members become abnormal at day 30 after a normal result; even ones stay normal until day 300. An HPV row - each, which the outcome must ignore.""" + """Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members: + NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors must ignore.""" rows = [] for pac_id in range(1, 21): index = date(2025, 1, 1) + timedelta(days=pac_id) - rows += [_row(pac_id, index, 0, "NORMAL"), _row(pac_id, index, 5, "POSITIVO", tipo="vph")] - rows.append(_row(pac_id, index, 30, "LIEBG") if pac_id % 2 else _row(pac_id, index, 300, "NORMAL")) + if pac_id % 2: + rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG") + else: + rows += _member(pac_id, index, "NORMAL", "NEGATIVO") + rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"), + _row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")] return pd.DataFrame(rows, columns=SCHEMA.names) -def _write(frame, path, armado_id): +def _write(frame, path, metadata): table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False) path.parent.mkdir(parents=True, exist_ok=True) - pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path) + lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata} + pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path) return path @pytest.fixture def cohort_file(cohort_frame, tmp_path): """The frame as build 7's file.""" - return _write(cohort_frame, tmp_path / "7.parquet", 7) + return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7}) @pytest.fixture def exported(cohort_frame, tmp_path, monkeypatch): """Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to.""" folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" - _write(cohort_frame, folder / "7.parquet", 7) - _write(cohort_frame, folder / "12.parquet", 12) + _write(cohort_frame, folder / "7.parquet", {"armado_id": 7}) + _write(cohort_frame, folder / "12.parquet", {"armado_id": 12}) monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) return folder -def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame): - """Pins down: `y` is 1 with any abnormal result; `days` reaches the first abnormal result, or the last result when - `y` is 0. Fails if another variable's value counts as abnormal, or either date rule changes.""" - prepared = model.prepare(cohort_frame).set_index("pac_id") +def test_predictors_are_the_index_sample_results(cohort_frame): + """Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a + result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is + taken, or a missing result becomes NaN, which the encoder would reject.""" + found = model.predictors(cohort_frame).set_index("pac_id") - assert len(prepared) == 20 - assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30] - assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300] + assert len(found) == 20 + assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"] + assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"] -def test_first_abnormal_result_sets_days_when_there_are_several(): - """Pins down: with two abnormal results, `days` is the earlier one even if the file's order says otherwise. Fails - if `days` takes the last abnormal result or the first row.""" +def test_the_genotype_is_read_from_its_number(): + """Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails + if the genotype is read from `valor_codigo`, which is empty for it.""" index = date(2025, 1, 1) - frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")]) + frame = pd.DataFrame(_member(1, index, "ASC-US", "POSITIVO") + + [_row(1, index, 7, "vph_genotipo_16_18", sample="S1", numero=1.0)], columns=SCHEMA.names) - assert model.prepare(frame).loc[0, "days"] == 40 + assert model.predictors(frame).loc[0, "vph_16_18"] == "POSITIVO" + + +@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0), + ("LIEAG", 400, 0)]) +def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected): + """Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if + a lower grade counts, or a biopsy after the window does.""" + frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day), + columns=SCHEMA.names) + + assert model.outcome(frame, CUTOFF).loc[0, "y"] == expected + + +def test_a_member_without_a_complete_window_is_scored_but_not_trained_on(): + """Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out + of `prepare`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives, + which biases the risk down.""" + late = date(2027, 3, 1) + frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS", + biopsy_day=30), columns=SCHEMA.names) + outcome = model.outcome(frame, CUTOFF).set_index("pac_id") + + assert outcome["known"].tolist() == [False, True] + assert model.prepare(model.predictors(frame), model.outcome(frame, CUTOFF))["pac_id"].tolist() == [2] def test_split_trains_on_the_oldest_index_dates(cohort_frame): """Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split is random or follows another column.""" - parts = model.split(model.prepare(cohort_frame)) + parts = model.split(model.prepare(model.predictors(cohort_frame), model.outcome(cohort_frame, CUTOFF))) assert (len(parts["train"]), len(parts["test"])) == (14, 6) assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min() def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking): - """Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash and the note that - it has no clinical meaning, and an artifact that holds `prepare`, so it takes the long frame. Fails if any is lost, or - if the driver stops reaching `registered_model`.""" + """Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's + window and the note that it's a prototype, and an artifact that holds `predictors`, so it takes the long frame. Fails + if any is lost, or if the driver stops reaching `registered_model`.""" version = train(cohort_file) resolved = registry.resolve("cacu", "cin2_logistic", version) stored = registry.get("cacu", "cin2_logistic", version) run = registry.client.get_run(stored.run_id).data assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha - assert "sin significado clínico" in stored.description + assert "Prototipo" in stored.description and run.params["outcome_window_months"] == "12" assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics assert len(run.params["cohort_sha256"]) == 64 @@ -239,7 +284,7 @@ def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking): assert main([*RUN, "--train", "--armado", "7"]) == 0 assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0 frame = pd.read_parquet(exported / "12.parquet") - _write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12) + _write(frame[frame["pac_id"] != 1], exported / "12.parquet", {"armado_id": 12}) assert main([*RUN, "--train", "--armado", "12"]) == 0 assert len(_versions()) == 3 @@ -300,8 +345,7 @@ def dbt_exported(cohort_frame, tmp_path, monkeypatch): for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])): path = folder / f"{number}.parquet" path.parent.mkdir(parents=True, exist_ok=True) - table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False) - pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path) + _write(frame, path, {"build": number, "producer": "dbt"}) monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) return folder