Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 28ff4605f3 | |||
| 2b855be12d | |||
| 92c5c69c2d | |||
| ee1c307d57 | |||
| e5526b9ec3 | |||
| 86b508cba8 | |||
| 04c8cbafd1 | |||
| 4c5bccb805 | |||
| 73547f2bb1 | |||
| ca9d3ad81f |
@@ -1,2 +1,8 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
uv.lock
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# models
|
||||
|
||||
Python package with the standard `train()`/`predict()` interface for the
|
||||
three screening models — CaCu, CaMa and TEA. Consumed by `WebApi`, but
|
||||
independent of it: this package can read its own training/inference data
|
||||
directly from `Persistance`, without going through `WebApi` at all.
|
||||
|
||||
## Structure
|
||||
|
||||
- `models/base.py` — `ScreeningModel`, the abstract base every model
|
||||
implements (`train(data)` / `predict(data)`).
|
||||
- `models/cacu.py`, `models/cama.py`, `models/tea.py` — one concrete
|
||||
class per domain.
|
||||
|
||||
## How entities are accessed from models
|
||||
|
||||
This package depends on `../Persistance` (a local `uv` path dependency —
|
||||
see `pyproject.toml`), and through it on `../Core`. **As of now this is
|
||||
wiring, not usage**: `train()`/`predict()` in `cacu.py`/`cama.py`/`tea.py`
|
||||
just raise `NotImplementedError` — no model imports `persistance` yet.
|
||||
|
||||
When real training/inference logic is added, the access pattern is the
|
||||
same repository instances `WebApi` reads from — no separate data layer
|
||||
for `models` to maintain:
|
||||
|
||||
```python
|
||||
# models/models/cacu.py
|
||||
from typing import Any
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaCuModel(ScreeningModel):
|
||||
def train(self, data: Any = None) -> None:
|
||||
if data is None:
|
||||
data = citologia_cervical_repository.list(limit=10_000)
|
||||
# ... fit on `data`
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaCu prediction is not implemented yet.")
|
||||
```
|
||||
|
||||
The `data: Any = None` default on `train()`/`predict()` is what lets a
|
||||
caller (e.g. `WebApi`) optionally hand over already-fetched rows instead
|
||||
of forcing every call to hit the database — but a model implementation is
|
||||
just as free to call `persistance.<domain>` itself when `data` is `None`,
|
||||
exactly like the example above.
|
||||
|
||||
Each domain's available repositories (`paciente_repository`,
|
||||
`citologia_cervical_repository`, etc.) and how to extend one with
|
||||
table-specific business logic are documented in
|
||||
`../Persistance/README.md`.
|
||||
|
||||
## Riesgos (ADR-MD-008)
|
||||
|
||||
`models/riesgo.py` es el contrato con que Orquestacion pide riesgos a un modelo: `EstimadorDeRiesgo`
|
||||
(recibe el marco ancho de un armado de cohorte y devuelve un `Riesgo` por miembro y horizonte, más su
|
||||
`Procedencia`, las llaves para conciliar con MLflow). `RiesgoSintetico` es un sustituto determinista, sin
|
||||
MLflow, para pruebas y para desplegar sin el modelo real; no es un modelo clínico. El modelo real
|
||||
(Modelo-cacu, con su artefacto de MLflow) entra como otra clase que cumple el contrato (MD-Q6).
|
||||
@@ -0,0 +1,21 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ScreeningModel(ABC):
|
||||
"""Standard train()/predict() interface every screening model implements,
|
||||
regardless of which of the three data marts (CaCu/CaMa/TEA) it targets.
|
||||
|
||||
Implementations are free to pull their own data straight from
|
||||
`persistance.<domain>` — the same standard repository API WebApi uses —
|
||||
or accept already-fetched rows from a caller; `data` is intentionally
|
||||
untyped at this scaffolding stage.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def train(self, data: Any = None) -> None:
|
||||
"""Fit the model, optionally on `data` passed in by the caller."""
|
||||
|
||||
@abstractmethod
|
||||
def predict(self, data: Any) -> Any:
|
||||
"""Score `data` and return predictions."""
|
||||
@@ -0,0 +1,19 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaCuModel(ScreeningModel):
|
||||
"""Scaffold for the CaCu (cervical cancer) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.cacu`'s
|
||||
repositories (`paciente_repository`, `citologia_cervical_repository`,
|
||||
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
|
||||
No real model yet — this is interface scaffolding only.
|
||||
"""
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaCu training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaCu prediction is not implemented yet.")
|
||||
@@ -0,0 +1,19 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaMaModel(ScreeningModel):
|
||||
"""Scaffold for the CaMa (breast cancer) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.cama`'s
|
||||
repositories (`paciente_repository`, `mastografia_repository`,
|
||||
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
|
||||
No real model yet — this is interface scaffolding only.
|
||||
"""
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaMa training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaMa prediction is not implemented yet.")
|
||||
@@ -1,8 +0,0 @@
|
||||
"""The dbt project, alone so `dagster-dbt project prepare-and-package` can build its manifest."""
|
||||
|
||||
from dagster_dbt import DbtProject
|
||||
|
||||
from persistance.config import DBT_DIR
|
||||
|
||||
dbt_project = DbtProject(project_dir=DBT_DIR, profiles_dir=DBT_DIR)
|
||||
dbt_project.prepare_if_dev()
|
||||
@@ -1,45 +0,0 @@
|
||||
"""Dagster code location: every heavy step of the platform is an asset or job defined here."""
|
||||
|
||||
import dagster as dg
|
||||
import dlt
|
||||
from dagster_dbt import DbtCliResource, dbt_assets
|
||||
from dagster_dlt import DagsterDltResource, DagsterDltTranslator, dlt_assets
|
||||
from dagster_dlt.translator import DltResourceTranslatorData
|
||||
|
||||
from models.dbt_project import dbt_project
|
||||
from persistance.destination import platform
|
||||
from persistance.sources.sample import sample_patients
|
||||
|
||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||
|
||||
|
||||
class BronzeKeys(DagsterDltTranslator):
|
||||
"""Name dlt assets bronze/<table>, the key dbt's sources point at."""
|
||||
|
||||
def get_asset_spec(self, data: DltResourceTranslatorData) -> dg.AssetSpec:
|
||||
spec = super().get_asset_spec(data)
|
||||
return spec.replace_attributes(key=dg.AssetKey(["bronze", data.resource.table_name]))
|
||||
|
||||
|
||||
@dlt_assets(
|
||||
dlt_source=sample_patients(),
|
||||
dlt_pipeline=dlt.pipeline("sample", destination=platform(), dataset_name="bronze"),
|
||||
group_name="ingest",
|
||||
dagster_dlt_translator=BronzeKeys(),
|
||||
)
|
||||
def sample_ingest(context: dg.AssetExecutionContext, dlt: DagsterDltResource):
|
||||
yield from dlt.run(context=context)
|
||||
|
||||
|
||||
@dbt_assets(manifest=dbt_project.manifest_path)
|
||||
def transforms(context: dg.AssetExecutionContext, dbt: DbtCliResource):
|
||||
yield from dbt.cli(["build"], context=context).stream()
|
||||
|
||||
|
||||
sample_job = dg.define_asset_job("sample", selection=dg.AssetSelection.all(), tags=WRITES)
|
||||
|
||||
defs = dg.Definitions(
|
||||
assets=[sample_ingest, transforms],
|
||||
jobs=[sample_job],
|
||||
resources={"dlt": DagsterDltResource(), "dbt": DbtCliResource(project_dir=dbt_project)},
|
||||
)
|
||||
@@ -0,0 +1,176 @@
|
||||
"""El contrato con que se le pide a un modelo el riesgo de los miembros de una cohorte (ADR-MD-008).
|
||||
|
||||
Quien llama (la arista `estimar` de Orquestacion) le da al estimador el marco de un armado
|
||||
de cohorte, ancho: `(columnas, filas)`, con `columnas = ["pac_id", "fecha_indice", <variables>]`
|
||||
(lo que devuelve `indicadores_kit.cohortes.armado.leer_marco`). El estimador devuelve un
|
||||
`Riesgo` por miembro y horizonte, y su `Procedencia`: las llaves con que se concilia con
|
||||
MLflow (opción A del prototipo; MLflow no guarda filas ni pacientes).
|
||||
|
||||
Este módulo no importa al kit, a Persistance ni a Orquestacion: recibe listas.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import NamedTuple, Protocol, runtime_checkable
|
||||
|
||||
|
||||
class Riesgo(NamedTuple):
|
||||
"""El riesgo de un miembro a un horizonte (FHIR `RiskAssessment.prediction`)."""
|
||||
|
||||
pac_id: int
|
||||
horizonte_anios: float # años desde la fecha índice; 0 = prevalente
|
||||
probabilidad: float # de 0 a 1
|
||||
ic_bajo: float | None = None
|
||||
ic_alto: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Procedencia:
|
||||
"""De qué modelo salen los riesgos: las llaves que guarda el lote (`PROCEDENCIA` de Persistance)."""
|
||||
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
mlflow_run_id: str
|
||||
modelo_sha: str
|
||||
|
||||
def como_dict(self) -> dict[str, str]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class EstimadorDeRiesgo(Protocol):
|
||||
"""Lo que cumple todo modelo de riesgo que Orquestacion puede llamar."""
|
||||
|
||||
cohorte_url: str # la cohorte cuyo marco consume ("cacu/cohorte_vigilancia")
|
||||
desenlace: str # lo que predice ("cin2_mas")
|
||||
|
||||
def procedencia(self) -> Procedencia: ...
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: ...
|
||||
|
||||
|
||||
# La regla del sustituto: una probabilidad base y lo que suma cada predictor basal.
|
||||
REGLA_SINTETICA = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
|
||||
PAP_NORMALES = ("NORMAL",)
|
||||
|
||||
|
||||
class RiesgoSintetico:
|
||||
"""Un estimador sustituto determinista, sin MLflow: para pruebas y para desplegar sin el modelo real.
|
||||
|
||||
La probabilidad sale de una tabla fija por los predictores basales: `REGLA_SINTETICA["base"]`,
|
||||
más `pap_anormal` si `pap_0` no es `NORMAL` ni nulo, más `vph_positivo` si `hpv_0` es
|
||||
`POSITIVO`, con tope. Sin intervalo. No es un modelo clínico.
|
||||
"""
|
||||
|
||||
def __init__(self, cohorte_url: str = "cacu/cohorte_vigilancia", desenlace: str = "cin2_mas",
|
||||
horizontes: tuple[float, ...] = (0.0,)):
|
||||
self.cohorte_url = cohorte_url
|
||||
self.desenlace = desenlace
|
||||
self.horizontes = tuple(horizontes)
|
||||
|
||||
def procedencia(self) -> Procedencia:
|
||||
regla = {"regla": REGLA_SINTETICA, "pap_normales": PAP_NORMALES, "horizontes": self.horizontes}
|
||||
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
return Procedencia(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha)
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
|
||||
faltan = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columnas]
|
||||
if faltan:
|
||||
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
|
||||
i_pac, i_pap, i_vph = (columnas.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
|
||||
riesgos = []
|
||||
for fila in filas:
|
||||
p = REGLA_SINTETICA["base"]
|
||||
if fila[i_pap] is not None and fila[i_pap] not in PAP_NORMALES:
|
||||
p += REGLA_SINTETICA["pap_anormal"]
|
||||
if fila[i_vph] == "POSITIVO":
|
||||
p += REGLA_SINTETICA["vph_positivo"]
|
||||
p = min(p, REGLA_SINTETICA["tope"])
|
||||
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
|
||||
return riesgos
|
||||
|
||||
|
||||
# La regla del sustituto de TEA: lo que suma la interpretación del M-CHAT índice y lo perinatal.
|
||||
REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05,
|
||||
"apgar_corte": 7, "tope": 0.95}
|
||||
|
||||
|
||||
class RiesgoSinteticoTea:
|
||||
"""El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow.
|
||||
|
||||
La probabilidad de un diagnóstico de TEA al horizonte (4 años = 48 meses, el de la cohorte) es
|
||||
`REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si
|
||||
`ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin
|
||||
intervalo. No es un modelo clínico.
|
||||
"""
|
||||
|
||||
def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d",
|
||||
horizontes: tuple[float, ...] = (4.0,)):
|
||||
self.cohorte_url = cohorte_url
|
||||
self.desenlace = desenlace
|
||||
self.horizontes = tuple(horizontes)
|
||||
|
||||
def procedencia(self) -> Procedencia:
|
||||
regla = {"regla": REGLA_SINTETICA_TEA, "horizontes": self.horizontes}
|
||||
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
return Procedencia(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow",
|
||||
modelo_sha=sha)
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
|
||||
necesarias = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min")
|
||||
faltan = [c for c in necesarias if c not in columnas]
|
||||
if faltan:
|
||||
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
|
||||
i_pac, i_mchat, i_ucin, i_apgar = (columnas.index(c) for c in necesarias)
|
||||
r = REGLA_SINTETICA_TEA
|
||||
riesgos = []
|
||||
for fila in filas:
|
||||
p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(fila[i_mchat], 0.0)
|
||||
if fila[i_ucin] == 1:
|
||||
p += r["ucin"]
|
||||
if fila[i_apgar] is not None and fila[i_apgar] < r["apgar_corte"]:
|
||||
p += r["apgar_bajo"]
|
||||
p = min(p, r["tope"])
|
||||
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
|
||||
return riesgos
|
||||
|
||||
|
||||
# La regla del sustituto de CaMa: lo que suma el BI-RADS índice.
|
||||
REGLA_SINTETICA_CAMA = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80,
|
||||
"tope": 0.95}
|
||||
BIRADS_SUSPECHA = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4",
|
||||
"B4C": "birads_4", "B5": "birads_5"}
|
||||
|
||||
|
||||
class RiesgoSinteticoCama:
|
||||
"""El sustituto determinista de CaMa, sobre el marco de `cama/cohorte_tamizaje` (T-21g). Sin MLflow.
|
||||
|
||||
La probabilidad de cáncer de mama por biopsia al horizonte (1 año, el de la cohorte) es
|
||||
`REGLA_SINTETICA_CAMA["base"]` más lo que suma la categoría del BI-RADS índice (`birads_0`), con
|
||||
tope. Las subcategorías 4A, 4B y 4C suman como 4. Sin intervalo. No es un modelo clínico.
|
||||
"""
|
||||
|
||||
def __init__(self, cohorte_url: str = "cama/cohorte_tamizaje", desenlace: str = "d",
|
||||
horizontes: tuple[float, ...] = (1.0,)):
|
||||
self.cohorte_url = cohorte_url
|
||||
self.desenlace = desenlace
|
||||
self.horizontes = tuple(horizontes)
|
||||
|
||||
def procedencia(self) -> Procedencia:
|
||||
regla = {"regla": REGLA_SINTETICA_CAMA, "birads": BIRADS_SUSPECHA, "horizontes": self.horizontes}
|
||||
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
return Procedencia(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow",
|
||||
modelo_sha=sha)
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
|
||||
faltan = [c for c in ("pac_id", "birads_0") if c not in columnas]
|
||||
if faltan:
|
||||
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
|
||||
i_pac, i_birads = columnas.index("pac_id"), columnas.index("birads_0")
|
||||
r = REGLA_SINTETICA_CAMA
|
||||
riesgos = []
|
||||
for fila in filas:
|
||||
p = min(r["base"] + r.get(BIRADS_SUSPECHA.get(fila[i_birads]), 0.0), r["tope"])
|
||||
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
|
||||
return riesgos
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Prueba de concepto: un modelo de riesgo de CIN2+ con MLflow, de `toy-model/riesgo_juguete.py`.
|
||||
|
||||
Entrena una logística sobre el marco de `cacu/cohorte_vigilancia`, la registra en MLflow
|
||||
(`MLFLOW_TRACKING_URI`; en el despliegue, `http://<host>:9705`) y la sirve a la arista `estimar` con
|
||||
`EstimadorMlflow`, que cumple `EstimadorDeRiesgo`. Lo corre Orquestacion:
|
||||
|
||||
uv run python -m orquestacion modelos entrenar [--horizonte 1] [--armado 3]
|
||||
uv run python -m orquestacion ciclo cacu --desde 2025 --hasta 2025 --solo estimar --modelo cacu_cin2_mas --version 1
|
||||
|
||||
Sin pacientes en MLflow (ADR-MD-008): ni filas ni `input_example`. `ModeloCin2Mas` se serializa por
|
||||
referencia a este módulo: cargarlo pide `models` instalado.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from mlflow.models import ModelSignature
|
||||
from mlflow.types import ColSpec, Schema
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
|
||||
from indicadores_kit.cacu.tablas import COHORTES
|
||||
from indicadores_kit.oro.cohortes.armado import leer_marco, linaje, ultimo_armado
|
||||
from indicadores_kit.oro.cohortes.definicion import leer_definicion, ruta_de_cohorte
|
||||
|
||||
from models.riesgo import Procedencia, Riesgo
|
||||
|
||||
EXPERIMENTO = "cacu-cin2"
|
||||
NOMBRE_MODELO = "cacu_cin2_mas"
|
||||
COHORTE_URL = "cacu/cohorte_vigilancia"
|
||||
DESENLACE = "cin2_mas"
|
||||
COVARIABLES = ["pap_0", "hpv_0"]
|
||||
SIN_ESTADO = -999
|
||||
HORIZONTE = 1.0
|
||||
|
||||
|
||||
# 1 · descargar ---------------------------------------------------------------------------
|
||||
|
||||
def descargar(repositorio, armado_id=None):
|
||||
"""El marco del armado (el último si no se dice) y su linaje `kit.*`, en una sesión de `repositorio`. Solo lee."""
|
||||
d = leer_definicion(ruta_de_cohorte("cacu", "cohorte_vigilancia"))
|
||||
|
||||
def leer(sesion):
|
||||
aid = armado_id if armado_id is not None else ultimo_armado(sesion, d.url, cohortes=COHORTES)
|
||||
if aid is None:
|
||||
raise LookupError(f"No hay armados de {d.url}: corre antes la arista `cohortes`.")
|
||||
columnas, filas = leer_marco(sesion, aid, d, cohortes=COHORTES)
|
||||
return pd.DataFrame(filas, columns=columnas), linaje(sesion, aid, d, cohortes=COHORTES)
|
||||
|
||||
return repositorio.leer(leer)
|
||||
|
||||
|
||||
# 2 · preparar ----------------------------------------------------------------------------
|
||||
|
||||
def a_nulos(df):
|
||||
"""`-999` es nulo, en números y en códigos."""
|
||||
return df.replace({SIN_ESTADO: np.nan, float(SIN_ESTADO): np.nan, str(SIN_ESTADO): np.nan})
|
||||
|
||||
|
||||
def preparar(marco, horizonte=HORIZONTE):
|
||||
"""El marco con la etiqueta `y` a `horizonte` años, sin las filas no etiquetables.
|
||||
|
||||
Provisional (MD-Q6): y = 1 si `c == 1` o `r <= h`; y = 0 si `c == 0` y `l >= h`; lo demás se excluye.
|
||||
"""
|
||||
df = a_nulos(marco)
|
||||
df["fecha_indice"] = pd.to_datetime(df["fecha_indice"])
|
||||
positivo = (df["c"] == 1) | (df["r"] <= horizonte)
|
||||
negativo = (df["c"] == 0) & (df["l"] >= horizonte) & ~positivo
|
||||
df["y"] = np.where(positivo, 1, np.where(negativo, 0, -1))
|
||||
return df[df["y"] >= 0].sort_values(["fecha_indice", "pac_id"]).reset_index(drop=True)
|
||||
|
||||
|
||||
# 3 · entrenar y evaluar ------------------------------------------------------------------
|
||||
|
||||
def dividir(df, fraccion=0.7):
|
||||
"""Partición temporal: las fechas índice más antiguas entrenan. Nunca al azar."""
|
||||
corte = df["fecha_indice"].iloc[int(len(df) * fraccion)]
|
||||
return df[df["fecha_indice"] < corte], df[df["fecha_indice"] >= corte], corte
|
||||
|
||||
|
||||
class ModeloCin2Mas(mlflow.pyfunc.PythonModel):
|
||||
"""El pyfunc: indicadoras de las covariables y una logística. Recibe el marco, devuelve P(CIN2+) por fila.
|
||||
|
||||
Un nulo o un nivel que no se vio al ajustar da ceros en sus indicadoras.
|
||||
"""
|
||||
|
||||
def __init__(self, horizonte=HORIZONTE, C=1.0):
|
||||
self.horizonte, self.C = float(horizonte), C
|
||||
self.niveles, self.logistica = {}, None
|
||||
|
||||
def indicadoras(self, df):
|
||||
df = a_nulos(df)
|
||||
return pd.DataFrame(
|
||||
{f"{c}={n}": (df[c].astype("string") == n).fillna(False).astype(float).to_numpy()
|
||||
for c in COVARIABLES for n in self.niveles[c]},
|
||||
index=df.index,
|
||||
)
|
||||
|
||||
def ajustar(self, df):
|
||||
self.niveles = {c: sorted(a_nulos(df)[c].dropna().astype(str).unique()) for c in COVARIABLES}
|
||||
self.logistica = LogisticRegression(C=self.C, max_iter=1000).fit(self.indicadoras(df), df["y"])
|
||||
return self
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
return self.logistica.predict_proba(self.indicadoras(model_input))[:, 1]
|
||||
|
||||
|
||||
def evaluar(modelo, entrena, prueba):
|
||||
p = modelo.predict(None, prueba)
|
||||
return {
|
||||
"brier": brier_score_loss(prueba["y"], p, labels=[0, 1]),
|
||||
"auc": roc_auc_score(prueba["y"], p) if prueba["y"].nunique() == 2 else float("nan"),
|
||||
"n_entrenamiento": len(entrena), "n_prueba": len(prueba),
|
||||
"positivos_entrenamiento": int(entrena["y"].sum()), "positivos_prueba": int(prueba["y"].sum()),
|
||||
}
|
||||
|
||||
|
||||
# 4 · registrar ---------------------------------------------------------------------------
|
||||
|
||||
def sha_del_artefacto(model_uri):
|
||||
"""sha256 de `python_model.pkl` (preprocesamiento + logística); el `MLmodel` lleva ids y fechas."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
ruta = Path(mlflow.artifacts.download_artifacts(model_uri, dst_path=tmp)) / "python_model.pkl"
|
||||
return hashlib.sha256(ruta.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def registrar(modelo, metricas, parametros, linaje):
|
||||
"""Una corrida con el linaje, los parámetros, las métricas y el pyfunc registrado. Sin pacientes."""
|
||||
firma = ModelSignature(inputs=Schema([ColSpec("string", c, required=False) for c in COVARIABLES]))
|
||||
mlflow.set_experiment(EXPERIMENTO)
|
||||
with mlflow.start_run() as corrida:
|
||||
mlflow.set_tags({**linaje, "desenlace": DESENLACE})
|
||||
mlflow.log_params(parametros)
|
||||
mlflow.log_metrics(metricas)
|
||||
info = mlflow.pyfunc.log_model(name="modelo", python_model=modelo, signature=firma,
|
||||
registered_model_name=NOMBRE_MODELO)
|
||||
mlflow.set_tag("modelo_sha", sha_del_artefacto(info.model_uri))
|
||||
return corrida.info.run_id, str(info.registered_model_version)
|
||||
|
||||
|
||||
def entrenar(repositorio, horizonte=HORIZONTE, armado_id=None):
|
||||
"""Pasos 1-4. Devuelve (`run_id`, versión registrada, métricas)."""
|
||||
marco, linaje = descargar(repositorio, armado_id)
|
||||
df = preparar(marco, horizonte)
|
||||
entrena, prueba, corte = dividir(df)
|
||||
if entrena["y"].nunique() < 2:
|
||||
raise ValueError(f"La partición de entrenamiento tiene una sola clase ({len(entrena)} etiquetados).")
|
||||
modelo = ModeloCin2Mas(horizonte).ajustar(entrena)
|
||||
metricas = evaluar(modelo, entrena, prueba)
|
||||
# El corte es la fecha índice de una paciente: a MLflow va solo su mes.
|
||||
parametros = {"horizonte_anios": horizonte, "C": modelo.C, "corte_temporal_mes": corte.strftime("%Y-%m"),
|
||||
"covariables": ",".join(COVARIABLES), "etiqueta": "provisional MD-Q6"}
|
||||
run_id, version = registrar(modelo, metricas, parametros, linaje)
|
||||
return run_id, version, metricas
|
||||
|
||||
|
||||
# 6b · el estimador de la arista `estimar` -------------------------------------------------
|
||||
|
||||
class EstimadorMlflow:
|
||||
"""Cumple `EstimadorDeRiesgo` con una versión registrada de `NOMBRE_MODELO`."""
|
||||
|
||||
cohorte_url = COHORTE_URL
|
||||
desenlace = DESENLACE
|
||||
|
||||
def __init__(self, version):
|
||||
cliente = mlflow.MlflowClient()
|
||||
mv = cliente.get_model_version(NOMBRE_MODELO, str(version))
|
||||
uri = f"models:/{NOMBRE_MODELO}/{mv.version}"
|
||||
sha = sha_del_artefacto(uri)
|
||||
if sha != cliente.get_run(mv.run_id).data.tags.get("modelo_sha"):
|
||||
raise ValueError(f"El artefacto de {uri} no es el que se registró.")
|
||||
self.pyfunc = mlflow.pyfunc.load_model(uri)
|
||||
self.horizonte = self.pyfunc.unwrap_python_model().horizonte
|
||||
self._procedencia = Procedencia(NOMBRE_MODELO, str(mv.version), mv.run_id, sha)
|
||||
|
||||
def procedencia(self):
|
||||
return self._procedencia
|
||||
|
||||
def estimar(self, columnas, filas):
|
||||
marco = pd.DataFrame(filas, columns=columnas)
|
||||
entrada = a_nulos(marco)[COVARIABLES].astype(object)
|
||||
p = self.pyfunc.predict(entrada.where(entrada.notna(), None))
|
||||
return [Riesgo(int(pac), self.horizonte, round(float(q), 6)) for pac, q in zip(marco["pac_id"], p)]
|
||||
@@ -0,0 +1,19 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class TeaModel(ScreeningModel):
|
||||
"""Scaffold for the TEA (autism spectrum disorder) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.tea`'s
|
||||
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
|
||||
...) or be handed already-fetched rows. No real model yet — this is
|
||||
interface scaffolding only.
|
||||
"""
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("TEA training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("TEA prediction is not implemented yet.")
|
||||
+28
-12
@@ -1,17 +1,33 @@
|
||||
[project]
|
||||
name = "models"
|
||||
version = "0.0.0"
|
||||
description = "Dagster assets and jobs; one module per model."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = ["core", "persistance", "dagster", "dagster-webserver", "dagster-dbt", "dagster-dlt", "mlflow-skinny"]
|
||||
version = "0.1.0"
|
||||
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"persistance",
|
||||
# El marco y el linaje de las cohortes (`leer_marco`, `linaje`): `riesgo_logistico`.
|
||||
"indicadores-kit",
|
||||
# Solo el cliente: registra y carga contra el servidor del despliegue (9705), fijado a su versión.
|
||||
"mlflow-skinny==3.16.1",
|
||||
"scikit-learn==1.9.1",
|
||||
"pandas==3.0.6",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
core = { path = "../Core", editable = true }
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.uv.build-backend]
|
||||
module-name = "models"
|
||||
module-root = ""
|
||||
[tool.uv.sources]
|
||||
core = { workspace = true }
|
||||
persistance = { workspace = true }
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["models"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
# Las pruebas registran en un sqlite temporal, que el cliente `skinny` no admite.
|
||||
"mlflow==3.16.1",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import pytest
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from models.cama import CaMaModel
|
||||
from models.tea import TeaModel
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
|
||||
def test_train_not_implemented(cls):
|
||||
model = cls()
|
||||
with pytest.raises(NotImplementedError):
|
||||
model.train()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
|
||||
def test_predict_not_implemented(cls):
|
||||
model = cls()
|
||||
with pytest.raises(NotImplementedError):
|
||||
model.predict(data=None)
|
||||
@@ -1,10 +0,0 @@
|
||||
import mlflow
|
||||
|
||||
|
||||
def test_logs_a_run(tmp_path):
|
||||
mlflow.set_tracking_uri(f"sqlite:///{tmp_path / 'mlflow.db'}")
|
||||
with mlflow.start_run() as run:
|
||||
mlflow.log_param("seed", 7)
|
||||
mlflow.log_metric("auc", 0.5)
|
||||
got = mlflow.get_run(run.info.run_id)
|
||||
assert got.data.params == {"seed": "7"} and got.data.metrics == {"auc": 0.5}
|
||||
@@ -0,0 +1,105 @@
|
||||
"""El contrato `EstimadorDeRiesgo` y el estimador sustituto (ADR-MD-008)."""
|
||||
|
||||
import pytest
|
||||
|
||||
from models import riesgo
|
||||
from models.riesgo import (
|
||||
REGLA_SINTETICA_CAMA,
|
||||
REGLA_SINTETICA_TEA,
|
||||
EstimadorDeRiesgo,
|
||||
Riesgo,
|
||||
RiesgoSintetico,
|
||||
RiesgoSinteticoCama,
|
||||
RiesgoSinteticoTea,
|
||||
)
|
||||
|
||||
COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"]
|
||||
FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)]
|
||||
|
||||
|
||||
def test_el_sustituto_cumple_el_contrato():
|
||||
assert isinstance(RiesgoSintetico(), EstimadorDeRiesgo)
|
||||
|
||||
|
||||
def test_un_riesgo_por_miembro_y_horizonte_en_el_orden_del_marco():
|
||||
riesgos = RiesgoSintetico(horizontes=(0.0, 1.0)).estimar(COLUMNAS, FILAS)
|
||||
|
||||
assert [(r.pac_id, r.horizonte_anios) for r in riesgos] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)]
|
||||
assert all(isinstance(r, Riesgo) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in riesgos)
|
||||
|
||||
|
||||
def test_la_regla_suma_por_predictor_basal():
|
||||
p = {r.pac_id: r.probabilidad for r in RiesgoSintetico().estimar(COLUMNAS, FILAS)}
|
||||
|
||||
assert p == {1: 0.01, 2: 0.16, 3: 0.01}
|
||||
|
||||
|
||||
def test_es_determinista():
|
||||
a, b = RiesgoSintetico(), RiesgoSintetico()
|
||||
|
||||
assert a.estimar(COLUMNAS, FILAS) == b.estimar(COLUMNAS, FILAS)
|
||||
assert a.procedencia() == b.procedencia()
|
||||
|
||||
|
||||
def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monkeypatch):
|
||||
procedencia = RiesgoSintetico().procedencia()
|
||||
assert set(procedencia.como_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"}
|
||||
assert all(procedencia.como_dict().values())
|
||||
|
||||
monkeypatch.setitem(riesgo.REGLA_SINTETICA, "vph_positivo", 0.2)
|
||||
assert RiesgoSintetico().procedencia().modelo_sha != procedencia.modelo_sha
|
||||
|
||||
|
||||
def test_sin_los_predictores_falla_y_los_nombra():
|
||||
with pytest.raises(ValueError, match="pap_0"):
|
||||
RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)])
|
||||
|
||||
|
||||
# --- El sustituto de TEA (T-21f) ---------------------------------------------------------------
|
||||
|
||||
COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes",
|
||||
"hipoacusia_0"]
|
||||
|
||||
|
||||
def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte():
|
||||
estimador = RiesgoSinteticoTea()
|
||||
assert isinstance(estimador, EstimadorDeRiesgo)
|
||||
assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (4.0,)
|
||||
|
||||
|
||||
def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo():
|
||||
filas = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None),
|
||||
(2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"),
|
||||
(3, None, None, None, None, None, None, 0, None)]
|
||||
r = REGLA_SINTETICA_TEA
|
||||
assert [x.probabilidad for x in RiesgoSinteticoTea().estimar(COLUMNAS_TEA, filas)] == pytest.approx(
|
||||
[r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]])
|
||||
|
||||
|
||||
def test_el_sustituto_de_tea_sin_sus_predictores_falla():
|
||||
with pytest.raises(ValueError, match="mchat_0"):
|
||||
RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], [])
|
||||
|
||||
|
||||
# --- El sustituto de CaMa (T-21g) --------------------------------------------------------------
|
||||
|
||||
COLUMNAS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"]
|
||||
|
||||
|
||||
def test_el_sustituto_de_cama_cumple_el_contrato_y_lee_su_cohorte():
|
||||
estimador = RiesgoSinteticoCama()
|
||||
assert isinstance(estimador, EstimadorDeRiesgo)
|
||||
assert estimador.cohorte_url == "cama/cohorte_tamizaje" and estimador.horizontes == (1.0,)
|
||||
|
||||
|
||||
def test_la_regla_de_cama_suma_por_birads_indice_y_4a_cuenta_como_4():
|
||||
filas = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0),
|
||||
(3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)]
|
||||
r = REGLA_SINTETICA_CAMA
|
||||
assert [x.probabilidad for x in RiesgoSinteticoCama().estimar(COLUMNAS_CAMA, filas)] == pytest.approx(
|
||||
[r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]])
|
||||
|
||||
|
||||
def test_el_sustituto_de_cama_sin_su_predictor_falla():
|
||||
with pytest.raises(ValueError, match="birads_0"):
|
||||
RiesgoSinteticoCama().estimar(["pac_id", "fecha_indice"], [])
|
||||
@@ -1,49 +0,0 @@
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, make_url, text
|
||||
|
||||
POSTGRES = os.environ.get("POSTGRES_TEST_URL") # set by CI's postgres job
|
||||
HOSPITAL = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
|
||||
PATIENTS = 312
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
["sqlite", pytest.param("postgres", marks=pytest.mark.skipif(not POSTGRES, reason="no PG"))],
|
||||
)
|
||||
def test_sample_job_loads_and_reloads_without_duplicates(backend, tmp_path):
|
||||
(tmp_path / "dagster").mkdir()
|
||||
env = {
|
||||
**os.environ,
|
||||
"ISSSTELEON_DATA": str(tmp_path),
|
||||
"DLT_DATA_DIR": str(tmp_path / "dlt"),
|
||||
"DAGSTER_HOME": str(tmp_path / "dagster"),
|
||||
"HOSPITAL_CACU_URL": f"sqlite:///{HOSPITAL}",
|
||||
}
|
||||
if backend == "sqlite":
|
||||
url = env["PLATFORM_DATABASE_URL"] = f"sqlite:///{tmp_path / 'platform.db'}"
|
||||
attach = [f"ATTACH '{tmp_path}/platform__{s}.db' AS {s}" for s in ("bronze", "silver")]
|
||||
else:
|
||||
env.update(PLATFORM_DATABASE_URL=POSTGRES, DBT_TARGET="postgres")
|
||||
url = make_url(POSTGRES).set(drivername="postgresql+psycopg2") # dlt's driver
|
||||
attach = []
|
||||
with create_engine(url).begin() as con:
|
||||
con.exec_driver_sql("drop schema if exists bronze cascade")
|
||||
con.exec_driver_sql("drop schema if exists silver cascade")
|
||||
|
||||
for _ in range(2): # each run in its own process, as the Dagster daemon launches them
|
||||
subprocess.run(
|
||||
["dagster", "job", "execute", "-m", "models.definitions", "-j", "sample"],
|
||||
env=env,
|
||||
check=True,
|
||||
)
|
||||
with create_engine(url).connect() as con:
|
||||
for statement in attach:
|
||||
con.exec_driver_sql(statement)
|
||||
assert con.execute(text("select count(*) from bronze.patients")).scalar() == PATIENTS
|
||||
assert (
|
||||
con.execute(text("select count(*) from silver.cacu_patients")).scalar() == PATIENTS
|
||||
)
|
||||
Reference in New Issue
Block a user