testing: CacuStandIn as a helper for other code's tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user