contract: only the contract after removing the stand-ins
Drops the helpers only the stand-ins used, tests the contract with an estimator defined in the test, and updates the README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@ 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). `CacuStandIn`, `TeaStandIn` y `CamaStandIn`: sustitutos deterministas sin MLflow, para pruebas y para desplegar sin el modelo real; no son modelos clínicos. |
|
||||
| `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). |
|
||||
| `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 (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
|
||||
|
||||
@@ -11,8 +11,6 @@ patients).
|
||||
This module doesn't import the kit, Persistance or the orchestration: it receives lists.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import NamedTuple, Protocol, runtime_checkable
|
||||
|
||||
@@ -50,13 +48,3 @@ class RiskEstimator(Protocol):
|
||||
def provenance(self) -> Provenance: ...
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
|
||||
|
||||
|
||||
def _rule_sha(rule: dict) -> str:
|
||||
return hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _missing(columns: list[str], needed: tuple[str, ...]) -> None:
|
||||
missing = [c for c in needed if c not in columns]
|
||||
if missing:
|
||||
raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.")
|
||||
|
||||
+47
-136
@@ -1,152 +1,63 @@
|
||||
"""What this module covers: the `RiskEstimator` contract and the three stand-ins in `models.contract`
|
||||
(`CacuStandIn`, `TeaStandIn`, `CamaStandIn`).
|
||||
"""What this module covers: the `RiskEstimator` contract in `models.contract` and the two records it
|
||||
returns, `Risk` and `Provenance`.
|
||||
|
||||
Fixtures: no pytest fixtures. Each stand-in has a small hand-written frame (`COLUMNS*`, `ROWS*`) shaped like
|
||||
its cohort's: `pac_id`, `fecha_indice`, outcome columns and the predictors the rule reads. `monkeypatch`
|
||||
changes a rule to check that the provenance follows it.
|
||||
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
|
||||
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from models import contract
|
||||
from models.contract import CAMA_RULE, TEA_RULE, CacuStandIn, CamaStandIn, Risk, RiskEstimator, TeaStandIn
|
||||
|
||||
COLUMNS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"]
|
||||
ROWS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"),
|
||||
(3, "2024-09-01", 0, None, None)]
|
||||
from models.contract import Provenance, Risk, RiskEstimator
|
||||
|
||||
|
||||
def test_the_cacu_stand_in_meets_the_contract():
|
||||
"""Pins down: `CacuStandIn` is a `RiskEstimator` (runtime check of the protocol).
|
||||
class ConstantEstimator:
|
||||
"""Meets the contract with a fixed probability for every member and horizon."""
|
||||
|
||||
Fails if the protocol or the stand-in renames `cohort_url`, `outcome`, `provenance` or `estimate`.
|
||||
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(CacuStandIn(), RiskEstimator)
|
||||
assert isinstance(ConstantEstimator(), RiskEstimator)
|
||||
assert not isinstance(Incomplete(), RiskEstimator)
|
||||
|
||||
|
||||
def test_one_risk_per_member_and_horizon_in_frame_order():
|
||||
"""Pins down: `estimate` returns one `Risk` per member and horizon, members in the frame's order,
|
||||
probabilities in [0, 1], no interval.
|
||||
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 risks are grouped by horizon, reordered, or the interval stops being `None`.
|
||||
Fails if a field is renamed or added: the batch columns wouldn't match.
|
||||
"""
|
||||
risks = CacuStandIn(horizons=(0.0, 1.0)).estimate(COLUMNS, ROWS)
|
||||
|
||||
assert [(r.pac_id, r.horizonte_anios) for r in risks] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)]
|
||||
assert all(isinstance(r, Risk) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in risks)
|
||||
assert set(ConstantEstimator().provenance().as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id",
|
||||
"modelo_sha"}
|
||||
|
||||
|
||||
def test_the_cacu_rule_adds_per_baseline_predictor():
|
||||
"""Pins down: normal or missing results add nothing; an abnormal pap and a positive HPV add their terms.
|
||||
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 term of `CACU_RULE` changes or a null pap starts counting as abnormal.
|
||||
Fails if a field is renamed or reordered, or the interval becomes required.
|
||||
"""
|
||||
p = {r.pac_id: r.probabilidad for r in CacuStandIn().estimate(COLUMNS, ROWS)}
|
||||
risk = Risk(1, 0.0, 0.25)
|
||||
|
||||
assert p == {1: 0.01, 2: 0.16, 3: 0.01}
|
||||
|
||||
|
||||
def test_it_is_deterministic():
|
||||
"""Pins down: two instances give the same risks and the same provenance.
|
||||
|
||||
Fails if anything random or time-dependent enters the stand-in.
|
||||
"""
|
||||
a, b = CacuStandIn(), CacuStandIn()
|
||||
|
||||
assert a.estimate(COLUMNS, ROWS) == b.estimate(COLUMNS, ROWS)
|
||||
assert a.provenance() == b.provenance()
|
||||
|
||||
|
||||
def test_provenance_has_the_four_keys_and_its_sha_follows_the_rule(monkeypatch):
|
||||
"""Pins down: `Provenance.as_dict()` has exactly the four keys a batch stores, none empty, and
|
||||
`modelo_sha` changes when the rule changes.
|
||||
|
||||
Fails if a provenance field is renamed (the batch columns wouldn't match) or the sha stops covering
|
||||
the rule.
|
||||
"""
|
||||
provenance = CacuStandIn().provenance()
|
||||
assert set(provenance.as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"}
|
||||
assert all(provenance.as_dict().values())
|
||||
|
||||
monkeypatch.setitem(contract.CACU_RULE, "vph_positivo", 0.2)
|
||||
assert CacuStandIn().provenance().modelo_sha != provenance.modelo_sha
|
||||
|
||||
|
||||
def test_without_its_predictors_it_fails_and_names_them():
|
||||
"""Pins down: a frame without a predictor the rule reads raises `ValueError` naming it.
|
||||
|
||||
Fails if a missing column is silently treated as null.
|
||||
"""
|
||||
with pytest.raises(ValueError, match="pap_0"):
|
||||
CacuStandIn().estimate(["pac_id", "hpv_0"], [(1, None)])
|
||||
|
||||
|
||||
COLUMNS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes",
|
||||
"hipoacusia_0"]
|
||||
|
||||
|
||||
def test_the_tea_stand_in_meets_the_contract_and_reads_its_cohort():
|
||||
"""Pins down: `TeaStandIn` is a `RiskEstimator` over `tea/cohorte_tamizaje` at 4 years.
|
||||
|
||||
Fails if its default cohort or horizon changes.
|
||||
"""
|
||||
estimator = TeaStandIn()
|
||||
assert isinstance(estimator, RiskEstimator)
|
||||
assert estimator.cohort_url == "tea/cohorte_tamizaje" and estimator.horizons == (4.0,)
|
||||
|
||||
|
||||
def test_the_tea_rule_adds_mchat_nicu_and_low_apgar():
|
||||
"""Pins down: a low-risk M-CHAT adds nothing; a high-risk one, NICU admission and a low Apgar each add
|
||||
their term; missing values add nothing.
|
||||
|
||||
Fails if a term of `TEA_RULE` is dropped or the Apgar cut-off changes side.
|
||||
"""
|
||||
rows = [(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 = TEA_RULE
|
||||
assert [x.probabilidad for x in TeaStandIn().estimate(COLUMNS_TEA, rows)] == pytest.approx(
|
||||
[r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]])
|
||||
|
||||
|
||||
def test_the_tea_stand_in_without_its_predictors_fails():
|
||||
"""Pins down: a TEA frame without `mchat_0` raises `ValueError` naming it.
|
||||
|
||||
Fails if the TEA stand-in stops checking its columns.
|
||||
"""
|
||||
with pytest.raises(ValueError, match="mchat_0"):
|
||||
TeaStandIn().estimate(["pac_id", "fecha_indice"], [])
|
||||
|
||||
|
||||
COLUMNS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"]
|
||||
|
||||
|
||||
def test_the_cama_stand_in_meets_the_contract_and_reads_its_cohort():
|
||||
"""Pins down: `CamaStandIn` is a `RiskEstimator` over `cama/cohorte_tamizaje` at 1 year.
|
||||
|
||||
Fails if its default cohort or horizon changes.
|
||||
"""
|
||||
estimator = CamaStandIn()
|
||||
assert isinstance(estimator, RiskEstimator)
|
||||
assert estimator.cohort_url == "cama/cohorte_tamizaje" and estimator.horizons == (1.0,)
|
||||
|
||||
|
||||
def test_the_cama_rule_adds_by_index_birads_and_4a_counts_as_4():
|
||||
"""Pins down: BI-RADS 2 and a missing BI-RADS add nothing; 4A adds as 4; 5 adds its term.
|
||||
|
||||
Fails if `BIRADS_SUSPICION` loses the 4A/4B/4C mapping or a term of `CAMA_RULE` changes.
|
||||
"""
|
||||
rows = [(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 = CAMA_RULE
|
||||
assert [x.probabilidad for x in CamaStandIn().estimate(COLUMNS_CAMA, rows)] == pytest.approx(
|
||||
[r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]])
|
||||
|
||||
|
||||
def test_the_cama_stand_in_without_its_predictor_fails():
|
||||
"""Pins down: a CaMa frame without `birads_0` raises `ValueError` naming it.
|
||||
|
||||
Fails if the CaMa stand-in stops checking its columns.
|
||||
"""
|
||||
with pytest.raises(ValueError, match="birads_0"):
|
||||
CamaStandIn().estimate(["pac_id", "fecha_indice"], [])
|
||||
assert Risk._fields == ("pac_id", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto")
|
||||
assert (risk.ic_bajo, risk.ic_alto) == (None, None)
|
||||
|
||||
Reference in New Issue
Block a user