diff --git a/README.md b/README.md index 52c1490..0e717cc 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,9 @@ WebApi. |---|---| | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | +| `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). | +| `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. | +| `dags/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. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | | `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | diff --git a/models/contract.py b/models/contract.py new file mode 100644 index 0000000..ed4c780 --- /dev/null +++ b/models/contract.py @@ -0,0 +1,50 @@ +"""The contract through which a model is asked for the risk of a cohort build's members. + +The caller hands the estimator the wide frame of a cohort build, `(columns, rows)`, with +`columns = ["pac_id", "fecha_indice", ]`. The estimator returns one `Risk` per member and +horizon, and its `Provenance`: the keys that reconcile a batch with MLflow (MLflow keeps no rows and no +patients). + +`Risk` and `Provenance` keep the names of the columns they're saved to (`evaluacion_riesgo`, +`evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what Persistance's `PROCEDENCIA` expects. + +This module doesn't import the kit, Persistance or the orchestration: it receives lists. +""" + +from dataclasses import asdict, dataclass +from typing import NamedTuple, Protocol, runtime_checkable + + +class Risk(NamedTuple): + """A member's risk at one horizon (FHIR `RiskAssessment.prediction`).""" + + pac_id: int + horizonte_anios: float # years from the index date; 0 = prevalent + probabilidad: float # 0 to 1 + ic_bajo: float | None = None + ic_alto: float | None = None + + +@dataclass(frozen=True) +class Provenance: + """Which model the risks come from: the keys a batch stores.""" + + modelo_nombre: str + modelo_version: str + mlflow_run_id: str + modelo_sha: str + + def as_dict(self) -> dict[str, str]: + return asdict(self) + + +@runtime_checkable +class RiskEstimator(Protocol): + """What every risk model the orchestration can call provides.""" + + cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia") + outcome: str # what it predicts ("cin2_mas") + + def provenance(self) -> Provenance: ... + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ... diff --git a/models/dags/__init__.py b/models/dags/__init__.py new file mode 100644 index 0000000..2d7d505 --- /dev/null +++ b/models/dags/__init__.py @@ -0,0 +1 @@ +"""Hamilton modules for the model DAGs: each function is a node, each parameter an edge.""" diff --git a/models/dags/reading.py b/models/dags/reading.py new file mode 100644 index 0000000..29fea47 --- /dev/null +++ b/models/dags/reading.py @@ -0,0 +1,51 @@ +"""The nodes every model DAG reads through: a cohort build, its members and their timeline. + +Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows +which tables a model depends on (`persistance.assets.validate` with them as sources). The repositories +are inputs too: whoever builds the driver passes a domain's `cohorte_repository` and a +`timeline_repository` already bound to its query. + +The timeline is cut at the build's clinical date (`datos_as_of`) and always at an explicit load cut-off +(`known_until`): the build's `conocida_hasta`, or the moment of the read when the build has none. The run +records `known_until`, so the read can be repeated once silver keeps its history. +""" + +from dataclasses import fields +from datetime import datetime, timezone + +import pandas as pd +from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.assets import Asset + +MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember)) + + +class UnknownBuild(LookupError): + """The requested cohort build doesn't exist.""" + + +def cohort_build(cohorte_armado: Asset, cohort_repository: CohorteRepository, build_id: int) -> CohortBuild: + """The build's lineage: cohort, version, fingerprints and cut-offs.""" + build = cohort_repository.build(build_id) + if build is None: + raise UnknownBuild(f"cohort build {build_id} doesn't exist") + return build + + +def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort_build: CohortBuild) -> pd.DataFrame: + """One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`.""" + return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS)) + + +def known_until(cohort_build: CohortBuild) -> datetime: + """The load cut-off of the read: the build's `conocida_hasta`, or now (UTC) when the build has none.""" + return cohort_build.conocida_hasta or datetime.now(timezone.utc) + + +def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, known_until: datetime, + timeline_repository: TimelineRepository) -> pd.DataFrame: + """The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and at `known_until`.""" + rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of, + known_until=known_until) + return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)) diff --git a/models/testing.py b/models/testing.py new file mode 100644 index 0000000..6e1e092 --- /dev/null +++ b/models/testing.py @@ -0,0 +1,52 @@ +"""Helpers for other code's tests: a known `RiskEstimator` to run the risk chain without a trained model. + +`CacuStandIn` gives a fixed, predictable probability from two baseline predictors, without MLflow, so a +test of estimating, storing, confirming or publishing risks can assert exact values. It isn't a clinical +model and isn't used outside tests; it has no tests of its own. +""" + +import hashlib +import json + +from models.contract import Provenance, Risk + +# A base probability and what each baseline predictor adds, capped at `tope`. +CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95} +NORMAL_PAPS = ("NORMAL",) + + +class CacuStandIn: + """A deterministic estimator over the frame of `cacu/cohorte_vigilancia`. + + The probability is `CACU_RULE["base"]`, plus `pap_anormal` if `pap_0` is neither `NORMAL` nor null, + plus `vph_positivo` if `hpv_0` is `POSITIVO`, capped at `tope`. One `Risk` per member and horizon, in + the frame's order, with no interval. `modelo_sha` is the sha256 of the rule, so changing it changes + the provenance. + """ + + def __init__(self, cohort_url: str = "cacu/cohorte_vigilancia", outcome: str = "cin2_mas", + horizons: tuple[float, ...] = (0.0,)): + self.cohort_url = cohort_url + self.outcome = outcome + self.horizons = tuple(horizons) + + def provenance(self) -> Provenance: + rule = {"regla": CACU_RULE, "pap_normales": NORMAL_PAPS, "horizontes": self.horizons} + sha = hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest() + return Provenance(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha) + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + missing = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columns] + if missing: + raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.") + i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0")) + risks = [] + for row in rows: + p = CACU_RULE["base"] + if row[i_pap] is not None and row[i_pap] not in NORMAL_PAPS: + p += CACU_RULE["pap_anormal"] + if row[i_hpv] == "POSITIVO": + p += CACU_RULE["vph_positivo"] + p = min(p, CACU_RULE["tope"]) + risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] + return risks diff --git a/pyproject.toml b/pyproject.toml index 52bb574..d054073 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,6 +7,8 @@ dependencies = [ "persistance", "extraction", "mlflow>=2.9", + # The model DAGs (`models/dags`): each function a node, each parameter an edge. + "apache-hamilton>=1.90", ] [project.optional-dependencies] diff --git a/tests/test_contract.py b/tests/test_contract.py new file mode 100644 index 0000000..2ebe277 --- /dev/null +++ b/tests/test_contract.py @@ -0,0 +1,63 @@ +"""What this module covers: the `RiskEstimator` contract in `models.contract` and the two records it +returns, `Risk` and `Provenance`. + +Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one +fixed probability per member and horizon. `Incomplete` lacks `provenance`. +""" + +from models.contract import Provenance, Risk, RiskEstimator + + +class ConstantEstimator: + """Meets the contract with a fixed probability for every member and horizon.""" + + cohort_url = "cacu/cohorte_vigilancia" + outcome = "cin2_mas" + + def provenance(self) -> Provenance: + return Provenance(modelo_nombre="constant", modelo_version="1", mlflow_run_id="none", modelo_sha="sha") + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + i_pac = columns.index("pac_id") + return [Risk(row[i_pac], h, 0.1) for row in rows for h in (0.0, 1.0)] + + +class Incomplete: + """Has everything but `provenance`.""" + + cohort_url = "cacu/cohorte_vigilancia" + outcome = "cin2_mas" + + def estimate(self, columns, rows): + return [] + + +def test_a_class_with_the_four_members_meets_the_contract(): + """Pins down: `RiskEstimator` is checked at run time by its members (`cohort_url`, `outcome`, + `provenance`, `estimate`), not by inheritance; missing one fails the check. + + Fails if the protocol stops being `runtime_checkable` or a member is renamed. + """ + assert isinstance(ConstantEstimator(), RiskEstimator) + assert not isinstance(Incomplete(), RiskEstimator) + + +def test_provenance_has_the_four_keys_a_batch_stores(): + """Pins down: `Provenance.as_dict()` has exactly the four keys of the risk batch's provenance columns. + + Fails if a field is renamed or added: the batch columns wouldn't match. + """ + assert set(ConstantEstimator().provenance().as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", + "modelo_sha"} + + +def test_a_risk_keeps_the_column_names_and_its_interval_is_optional(): + """Pins down: `Risk` fields are named after the columns they're saved to, in that order, and the + interval defaults to `None`. + + Fails if a field is renamed or reordered, or the interval becomes required. + """ + risk = Risk(1, 0.0, 0.25) + + assert Risk._fields == ("pac_id", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto") + assert (risk.ic_bajo, risk.ic_alto) == (None, None) diff --git a/tests/test_reading_nodes.py b/tests/test_reading_nodes.py new file mode 100644 index 0000000..13afc9c --- /dev/null +++ b/tests/test_reading_nodes.py @@ -0,0 +1,185 @@ +"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `known_until`, `timeline`) +run by a Hamilton driver built from that module alone, and their place in the asset graph. + +Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain +`timeline_events` table; it returns the `CohorteRepository` and a `TimelineRepository` bound to +`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and +executes the requested nodes. +""" + +import json +from datetime import date, datetime, timezone + +import pytest +from core.cacu.base import CaCuModel +from core.cacu.indicadores.models import ( + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, +) +from core.indicadores.cohortes import TablasCohorte +from hamilton import driver +from persistance.aristas.oro import CohorteRepository +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.assets import Asset, InvalidGraph, validate +from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select +from sqlalchemy.pool import StaticPool +from sqlmodel import Session, create_engine + +from models.dags import reading + +TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, + EvaluacionRiesgo) +ASSETS = {name: Asset(name) for name in ("cohorte_armado", "cohorte_miembro", "linea_de_tiempo")} + +metadata = MetaData() +events = Table( + "timeline_events", metadata, + Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime), + Column("clase", String), Column("tipo", String), Column("codigo", String), + Column("valor_codigo", String), Column("valor_numerico", Float), + Column("fuente_tabla", String), Column("fuente_id", String), +) + + +def _event(pac_id, fecha, conocida_en, fuente_id): + return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "procedimiento", + "tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "NORMAL", "valor_numerico": None, + "fuente_tabla": "citologiacervical", "fuente_id": fuente_id} + + +EVENTS = [ + _event(10, date(2025, 2, 1), datetime(2025, 2, 2), "kept-10"), + _event(20, date(2025, 3, 1), datetime(2025, 3, 2), "kept-20"), + _event(10, date(2026, 2, 1), datetime(2026, 1, 1), "after-datos-as-of"), + _event(20, date(2025, 6, 1), datetime(2026, 1, 3), "loaded-after-the-build"), + _event(99, date(2025, 2, 1), datetime(2025, 2, 2), "not-a-member"), + _event(10, date(2025, 4, 1), datetime(2099, 1, 1), "loaded-in-the-future"), +] + + +def timeline_query(*, patients, until, known_until): + """Stands in for the kit's query: same columns and filters, over `timeline_events`.""" + query = select(*(events.c[name] for name in TIMELINE_COLUMNS)).order_by(events.c.pac_id, events.c.fecha) + if patients is not None: + query = query.where(events.c.pac_id.in_(patients)) + if until is not None: + query = query.where(events.c.fecha <= until) + if known_until is not None: + query = query.where(events.c.conocida_en <= known_until.replace(tzinfo=None)) + return query + + +@pytest.fixture +def repositories(): + """Build 1 of `cacu/cohorte_vigilancia`: clinical cut-off 2025-12-31, load cut-off 2026-01-02 08:00 + UTC, members 20 and 10 (inserted in that order). Build 2 has no members; build 3 has member 10 and no + load cut-off. `EVENTS` has one event per member inside both cut-offs, one past the clinical cut-off, + one loaded after build 1, one of a patient outside the cohort and one loaded in the future. + """ + engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False}) + CaCuModel.metadata.create_all(engine) + metadata.create_all(engine) + load_cut = {1: "2026-01-02T08:00:00+00:00", 2: "2026-01-02T08:00:00+00:00", 3: None} + with Session(engine) as session: + session.add_all([ + CohorteArmado(armado_id=armado_id, url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", + reglas_sha="r", parametros=json.dumps({"corte": "2025-12-31", "conocida_hasta": cut}), + datos_as_of=date(2025, 12, 31), huella=f"h{armado_id}", marco_sha=f"m{armado_id}", + n_miembros=0, armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + for armado_id, cut in load_cut.items() + ]) + session.add_all([ + CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=fecha, + indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id)) + for armado_id, pac_id, fecha in ((1, 20, date(2025, 3, 1)), (1, 10, date(2025, 2, 1)), + (3, 10, date(2025, 2, 1))) + ]) + session.commit() + session.connection().execute(insert(events), EVENTS) + session.commit() + factory = lambda: Session(engine) # noqa: E731 + return CohorteRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query) + + +def _run(repositories, build_id, nodes=("members", "timeline")): + cohort_repository, timeline_repository = repositories + dr = driver.Builder().with_modules(reading).build() + return dr.execute(list(nodes), inputs={**ASSETS, "cohort_repository": cohort_repository, + "timeline_repository": timeline_repository, "build_id": build_id}) + + +def test_reads_the_members_and_their_timeline_of_a_build(repositories): + """Pins down: a driver with only the reading nodes returns the build's members ordered by `pac_id` + with `MEMBER_COLUMNS`, and a timeline with `TIMELINE_COLUMNS` holding only the members' events. + + Fails if `members` loses its order or columns, or `timeline` stops filtering by the members. + """ + result = _run(repositories, 1) + + assert list(result["members"].columns) == list(reading.MEMBER_COLUMNS) + assert result["members"]["pac_id"].tolist() == [10, 20] + assert list(result["timeline"].columns) == list(TIMELINE_COLUMNS) + assert 99 not in result["timeline"]["pac_id"].tolist() + + +def test_the_timeline_is_cut_where_the_build_was_made(repositories): + """Pins down: the timeline keeps events up to the build's `datos_as_of` and loaded by its + `conocida_hasta`, so reading it again gives the build's input. + + Fails if `timeline` reads with no cut-off, or takes the cut-offs from anywhere but the build. + """ + timeline = _run(repositories, 1)["timeline"] + + assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"] + + +def test_a_build_without_a_load_cut_off_is_read_up_to_now(repositories): + """Pins down: when the build has no `conocida_hasta`, `known_until` is the moment of the read (UTC), + never `None`, and the timeline is cut there. + + Fails if `known_until` lets `None` through (the read couldn't be repeated) or isn't the one the + timeline used. + """ + before = datetime.now(timezone.utc) + result = _run(repositories, 3, nodes=("known_until", "timeline")) + + assert before <= result["known_until"] <= datetime.now(timezone.utc) + assert result["timeline"]["fuente_id"].tolist() == ["kept-10"] + + +def test_a_build_without_members_reads_an_empty_timeline(repositories): + """Pins down: a build with no members gives empty frames with their columns, not everyone's timeline. + + Fails if an empty member list reaches the query as "no patient filter". + """ + result = _run(repositories, 2) + + assert result["members"].empty and list(result["members"].columns) == list(reading.MEMBER_COLUMNS) + assert result["timeline"].empty and list(result["timeline"].columns) == list(TIMELINE_COLUMNS) + + +def test_an_unknown_build_fails(repositories): + """Pins down: asking for a build that doesn't exist raises `UnknownBuild` naming it. + + Fails if `cohort_build` lets `None` through to the other nodes. + """ + with pytest.raises(reading.UnknownBuild, match="404"): + _run(repositories, 404, nodes=("cohort_build",)) + + +def test_the_assets_read_are_sources_of_the_graph(): + """Pins down: the reading nodes read three assets nobody in `models` produces (`cohorte_armado`, + `cohorte_miembro`, `linea_de_tiempo`), so the graph validates only with them declared as sources. + + Fails if a node stops declaring the asset it reads, or reads one more without saying so. + """ + nodes = driver.Builder().with_modules(reading).build().list_available_variables() + + with pytest.raises(InvalidGraph) as error: + validate(nodes) + assert len(str(error.value).splitlines()) == 3 + validate(nodes, sources=set(ASSETS))