diff --git a/README.md b/README.md index 98f8598..5d6c0ec 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ WebApi. | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. | | `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | +| `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. | | `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/__init__.py b/models/cacu/cin2_logistic/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py new file mode 100644 index 0000000..68524c0 --- /dev/null +++ b/models/cacu/cin2_logistic/model.py @@ -0,0 +1,96 @@ +"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version. + +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. + +Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver. +""" + +import hashlib +import tomllib +from pathlib import Path + +import mlflow.pyfunc +import pandas as pd +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import brier_score_loss, roc_auc_score + +from models.io.cohorts import cohort_lineage, read_cohort +from models.io.registry import registered_name +from models.io.training import TrainingRun + +SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text()) +NORMAL = "NORMAL" + + +def cohort(cohort_path: str) -> pd.DataFrame: + return read_cohort(cohort_path) + + +def lineage(cohort_path: str) -> dict: + return cohort_lineage(cohort_path) + + +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 split(prepare: pd.DataFrame) -> dict: + """The oldest index dates train and the newest test.""" + ordered = prepare.sort_values(["fecha_indice", "pac_id"], kind="stable") + cut = int(len(ordered) * SETTINGS["train_fraction"]) + return {"train": ordered.iloc[:cut], "test": ordered.iloc[cut:]} + + +def train(split: dict) -> pd.DataFrame: + return split["train"] + + +def test(split: dict) -> pd.DataFrame: + return split["test"] + + +def fit(train: pd.DataFrame) -> LogisticRegression: + return LogisticRegression().fit(train[["days"]], train["y"]) + + +def predict(fit: LogisticRegression, 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") + + +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())} + + +class Cin2Logistic(mlflow.pyfunc.PythonModel): + """The registered artifact: takes a build's long frame and returns each member's probability.""" + + def __init__(self, fitted: LogisticRegression): + self.fitted = fitted + + def predict(self, context, model_input, params=None): + return predict(self.fitted, prepare(model_input)) + + +def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, environment: str) -> str: + """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content.""" + run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment, + cohorte_armado_id=int(lineage["armado_id"])) + run.log_model(Cin2Logistic(fit)) + version = run.finish(metrics=evaluate, hyperparameters={ + "cohort_file": str(cohort_path), "cohort_sha256": hashlib.sha256(Path(cohort_path).read_bytes()).hexdigest()}) + name = registered_name(SETTINGS["domain"], SETTINGS["scenario"]) + run.client.update_model_version(name, version, description=SETTINGS["description"]) + return version diff --git a/models/cacu/cin2_logistic/model.toml b/models/cacu/cin2_logistic/model.toml new file mode 100644 index 0000000..77a7594 --- /dev/null +++ b/models/cacu/cin2_logistic/model.toml @@ -0,0 +1,7 @@ +domain = "cacu" +scenario = "cin2_logistic" +cohort = "cacu/cohorte_vigilancia" +train_fraction = 0.7 +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.""" diff --git a/models/cacu/cin2_logistic/train.py b/models/cacu/cin2_logistic/train.py new file mode 100644 index 0000000..054ebe0 --- /dev/null +++ b/models/cacu/cin2_logistic/train.py @@ -0,0 +1,12 @@ +"""The model's Hamilton driver.""" + +from hamilton import driver + +from models.cacu.cin2_logistic import model + + +def train(cohort_path: str, environment: str = "DEV") -> str: + """Trains on a build's file and returns the registered version.""" + dr = driver.Builder().with_modules(model).build() + inputs = {"cohort_path": str(cohort_path), "environment": environment} + return dr.execute(["registered_model"], inputs=inputs)["registered_model"] diff --git a/models/io/cohorts.py b/models/io/cohorts.py index 7f40e13..ae65dbc 100644 --- a/models/io/cohorts.py +++ b/models/io/cohorts.py @@ -22,6 +22,12 @@ class CohortFileError(ValueError): """The file isn't a cohort build: its columns or types aren't `SCHEMA`'s.""" +def cohort_lineage(path: str | Path) -> dict[str, str]: + """The lineage in the file's metadata, without reading any rows.""" + metadata = pq.read_metadata(path).metadata + return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} + + def read_cohort(path: str | Path) -> pd.DataFrame: """The build's rows, after checking the file's schema without reading them.""" schema = pq.read_schema(path) diff --git a/pyproject.toml b/pyproject.toml index 12680a5..fe2228b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,7 @@ dependencies = [ # Cohort builds are Parquet files, read and written as frames. "pandas>=2.0", "pyarrow>=15", + "scikit-learn>=1.4", ] [project.optional-dependencies] diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py index bb6e7ed..320e708 100644 --- a/scripts/export_cohort.py +++ b/scripts/export_cohort.py @@ -31,7 +31,7 @@ from sqlalchemy import column, select, table from sqlalchemy.engine import make_url from sqlalchemy.exc import DBAPIError -from models.io.cohorts import SCHEMA +from models.io.cohorts import SCHEMA, cohort_lineage ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] @@ -55,12 +55,6 @@ def cohort_file(build: CohortBuild, root: Path) -> Path: return root / domain / cohort / f"{build.armado_id}.parquet" -def lineage_of(path: Path) -> dict[str, str]: - """The lineage in the file's metadata, without reading any rows.""" - metadata = pq.read_metadata(path).metadata - return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} - - def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]: """Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`.""" name = f"{domain}_linea_de_tiempo" @@ -115,7 +109,7 @@ def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) - """The build's file: reused if it's already there and belongs to the build, written once if not.""" path = cohort_file(build, root) if path.exists(): - lineage = lineage_of(path) + lineage = cohort_lineage(path) if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros): raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}") return path, "reused" diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py new file mode 100644 index 0000000..6670515 --- /dev/null +++ b/tests/cacu/test_cin2_logistic.py @@ -0,0 +1,93 @@ +"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal +split, and that training on a build's file registers a version with its lineage. + +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; `mlflow_tracking` (conftest), a SQLite-backed MLflow. +""" + +from datetime import date, datetime, timedelta, timezone + +import mlflow.pyfunc +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from models.cacu.cin2_logistic import model +from models.cacu.cin2_logistic.train import train +from models.io.cohorts import SCHEMA +from models.io.registry import ARMADO_TAG, MODEL_SHA_TAG, registry + + +def _row(pac_id, index, days, valor, tipo="bethesda"): + 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}"} + + +@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.""" + 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")) + return pd.DataFrame(rows, columns=SCHEMA.names) + + +@pytest.fixture +def cohort_file(cohort_frame, tmp_path): + """The frame as build 7's file.""" + table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False) + path = tmp_path / "7.parquet" + pq.write_table(table.replace_schema_metadata({"armado_id": "7", "url": "cacu/cohorte_vigilancia"}), path) + return path + + +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") + + assert len(prepared) == 20 + assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30] + assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300] + + +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.""" + index = date(2025, 1, 1) + frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")]) + + assert model.prepare(frame).loc[0, "days"] == 40 + + +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)) + + 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`.""" + 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 run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics + assert len(run.params["cohort_sha256"]) == 64 + + probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame) + assert len(probabilities) == 20 and probabilities.between(0, 1).all()