Merge pull request 'CaCu follow-up: CASO status with CIS, per-status probabilities, and a cycle that estimates with every production scenario' (#19) from integration/cacu-197-conciliacion into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/19
This commit was merged in pull request #19.
This commit is contained in:
@@ -13,34 +13,38 @@ from webapi.recomputation import RecomputationQueue
|
||||
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
|
||||
|
||||
|
||||
def test_only_cacu_has_a_live_estimator():
|
||||
"""With no version in the registry, CaMa's cycle estimates nothing, and TEA never has a live estimator. Fails if a
|
||||
domain without a production model gets an estimator that would then fail resolving a version."""
|
||||
def test_with_an_empty_registry_no_domain_has_a_live_estimator():
|
||||
"""With no version in the registry, neither CaMa's nor TEA's cycle estimates anything. Fails if a domain without
|
||||
a production model gets an estimator that would then fail resolving a version."""
|
||||
assert estimators.live_estimators("cama") == {}
|
||||
assert estimators.live_estimators("tea") == {}
|
||||
|
||||
|
||||
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
|
||||
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
|
||||
Fails if `live_estimators` stops catching the registry's `LookupError`."""
|
||||
Fails if `live_estimators` offers a scenario the registry does not list as in production."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: [])
|
||||
assert estimators.live_estimators("cacu") == {}
|
||||
|
||||
|
||||
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
|
||||
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
|
||||
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
|
||||
def test_every_scenario_in_production_scores_its_cohort(monkeypatch):
|
||||
"""Each scenario the registry has in production gets an estimator on the cohort its `model.toml` names, so two
|
||||
scenarios on one cohort give that cohort two estimators; a registered name with no scenario in `models` is
|
||||
skipped. An estimator reports nothing until it has estimated. Fails if the scenarios go back to a fixed list,
|
||||
if one cohort keeps a single estimator, or if an unknown registered name breaks the cycle."""
|
||||
from models.dags.training import Scenario
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: ["cancer_pim", "cin2_pim", "no_such_model"])
|
||||
live = estimators.live_estimators("cacu")
|
||||
assert list(live) == [URL]
|
||||
estimator = live[URL]
|
||||
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
|
||||
cohort = Scenario.load("cacu", "cin2_pim").cohort
|
||||
assert Scenario.load("cacu", "cancer_pim").cohort == cohort
|
||||
assert list(live) == [cohort]
|
||||
assert [e.scenario for e in live[cohort]] == ["cancer_pim", "cin2_pim"]
|
||||
with pytest.raises(RuntimeError):
|
||||
estimator.procedencia()
|
||||
live[cohort][0].procedencia()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
@@ -48,7 +52,7 @@ def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monk
|
||||
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
|
||||
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
|
||||
as anything but `preliminary`."""
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: [EstimadorFijo()]})
|
||||
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
|
||||
assert result["estado"] == "ok", result
|
||||
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
|
||||
|
||||
@@ -56,7 +56,7 @@ def cuenta(base, sql):
|
||||
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
estimador = EstimadorFijo()
|
||||
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: [estimador]})["estimate"][URL][0]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
@@ -68,16 +68,30 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
|
||||
|
||||
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
|
||||
assert cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0] == (primero, False)
|
||||
assert cacu.run("estimate")["estimate"] == {}
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_dos_modelos_de_una_cohorte_dejan_un_lote_cada_uno(cacu):
|
||||
"""Two estimators on one cohort (two scenarios in production on the same build) write one batch each. Fails if
|
||||
`estimate` keeps only one estimator per cohort or folds two models into one batch."""
|
||||
class OtroModelo(EstimadorFijo):
|
||||
def procedencia(self):
|
||||
return Procedencia(modelo_nombre="cacu-otro")
|
||||
|
||||
lotes = cacu.run("estimate", estimators={URL: [EstimadorFijo(), OtroModelo()]})["estimate"][URL]
|
||||
|
||||
assert [nuevo for _, nuevo in lotes] == [True, True] and lotes[0][0] != lotes[1][0]
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
|
||||
|
||||
@@ -43,6 +43,18 @@ def test_paciente_schema_coerces_date_from_datetime_object():
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_cacu_paciente_keeps_her_date_of_death():
|
||||
"""Pins down: a CaCu patient's `pac_fecha_defuncion` is imported (the survival scenario's outcome), and an alive
|
||||
patient has none. Fails if the schema drops the column again: every CaCu death would be lost on import and the
|
||||
survival model would train with no deaths."""
|
||||
from datetime import date
|
||||
|
||||
dead = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="1960-03-01", pac_fecha_defuncion="2025-07-09")
|
||||
alive = PacienteImportSchema(pac_id_hospital="H-2", pac_fecha_nacimiento="1960-03-01")
|
||||
|
||||
assert dead.pac_fecha_defuncion == date(2025, 7, 9) and alive.pac_fecha_defuncion is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_is_fully_optional():
|
||||
schema = PacientesImportSchema()
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
+124
-4
@@ -8,9 +8,10 @@ de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostr
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "horizontes_disponibles", "reglas",
|
||||
"paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -41,12 +42,13 @@ def test_el_pedido_se_respeta(client):
|
||||
|
||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA", "orden": "reciente", "horizonte": 5.0}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500",
|
||||
"?orden=edad", "?horizonte=cinco"],
|
||||
)
|
||||
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
|
||||
response = client.get(f"/cacu/seguimiento{query}")
|
||||
@@ -68,3 +70,121 @@ def test_in_dev_esta_obsoleta():
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
in_dev()
|
||||
|
||||
|
||||
def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(client):
|
||||
"""Fija: con un lote de CIN2+ confirmado, cada fila trae sus probabilidades por horizonte y `orden=lieag` pone
|
||||
primero a la de mayor probabilidad al `horizonte` pedido, y al final a quien el modelo no evalúa; un horizonte que
|
||||
los modelos no dan es 400. Falla si la lista deja de leer los lotes vigentes, o si ordena solo dentro de la página."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
baja, alta = int(filas[0]["pac_id"]), int(filas[1]["pac_id"])
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-orden",
|
||||
marco_sha="m", n_miembros=2, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (baja, alta)])
|
||||
session.commit()
|
||||
armado = build.armado_id
|
||||
indice = date(2025, 3, 1)
|
||||
lote, _ = cacu.cohort_repository.save_batch(
|
||||
armado, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "9", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2", [(baja, indice, 1.0, 0.02, 0.01, 0.04), (baja, indice, 5.0, 0.05, 0.03, 0.08),
|
||||
(alta, indice, 1.0, 0.10, 0.07, 0.14), (alta, indice, 5.0, 0.30, 0.22, 0.40)])
|
||||
cacu.cohort_repository.change_state(lote, "final", "revisado")
|
||||
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=lieag&horizonte=1").get_json()
|
||||
|
||||
assert cuerpo["horizontes_disponibles"] == [1.0, 5.0] and cuerpo["filtros"]["orden"] == "lieag"
|
||||
assert [i["pac_id"] for i in cuerpo["items"][:2]] == [str(alta), str(baja)]
|
||||
assert cuerpo["items"][0]["probabilidades"]["lieag"][1] == {"horizonte_anios": 5.0, "probabilidad": 0.30,
|
||||
"ic_bajo": 0.22, "ic_alto": 0.40}
|
||||
assert all(i["probabilidades"] is None for i in cuerpo["items"][2:])
|
||||
assert client.get("/cacu/seguimiento?corte=2025-12-31&orden=lieag&horizonte=3").status_code == 400
|
||||
|
||||
|
||||
def test_un_caso_tiene_su_estatus_y_su_probabilidad_de_supervivencia(client):
|
||||
"""Fija: una paciente con biopsia de carcinoma es CASO, gane lo que gane lo demás, y su probabilidad de supervivencia
|
||||
es 1 − la de morir del modelo de supervivencia, con el IC invertido, y 1 a los 0 años; la lista se ordena por ella.
|
||||
Falla si CASO
|
||||
deja de ganar o si la supervivencia se muestra como la probabilidad de morir."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
from webapi.follow_up.status import ESTATUS
|
||||
|
||||
assert ESTATUS[0] == "CASO"
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
paciente = int(filas[2]["pac_id"])
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_total", version="0.4.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-caso",
|
||||
marco_sha="m", n_miembros=1, armado_en=datetime(2026, 1, 2, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=paciente, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="biopsiacervical", indice_fuente_id=str(paciente)))
|
||||
session.commit()
|
||||
armado = build.armado_id
|
||||
lote, _ = cacu.cohort_repository.save_batch(
|
||||
armado, {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"muerte", [(paciente, date(2025, 3, 1), 5.0, 0.30, 0.20, 0.45)])
|
||||
cacu.cohort_repository.change_state(lote, "final", "revisado")
|
||||
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=supervivencia&horizonte=5"
|
||||
).get_json()
|
||||
|
||||
primera = cuerpo["items"][0]
|
||||
assert primera["pac_id"] == str(paciente)
|
||||
assert primera["probabilidades"]["supervivencia"] == [
|
||||
{"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0},
|
||||
{"horizonte_anios": 5.0, "probabilidad": 0.7, "ic_bajo": 0.55, "ic_alto": 0.8}]
|
||||
|
||||
|
||||
def test_una_biopsia_de_un_grado_de_caso_hace_caso_a_la_paciente(client, monkeypatch):
|
||||
"""Fija: quien tiene una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` al corte es CASO, gane lo
|
||||
que gane lo demás, y nadie sin una lo es; el filtro `estatus=CASO` las da. La base de demostración no tiene
|
||||
carcinomas, así que la regla se toma aquí como CIN2. Falla si la precedencia deja de poner CASO primero o el
|
||||
estatus deja de leer el grado de la biopsia de su regla."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.follow_up import listing
|
||||
from webapi.follow_up.silver import biopsias
|
||||
|
||||
original = listing.valor_de
|
||||
monkeypatch.setattr(listing, "valor_de", lambda sesion, clave, **kw:
|
||||
["CIN2"] if clave == "cacu.seguimiento.caso.grados" else original(sesion, clave, **kw))
|
||||
b = biopsias()
|
||||
with get_cacu_session() as session:
|
||||
con_cin2 = {r.pac_id for r in session.execute(select(b.c.pac_id).where(b.c.grado == "CIN2"))}
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
casos = {int(i["pac_id"]) for i in filas if i["estatus"]["codigo"] == "CASO"}
|
||||
|
||||
assert casos and casos == con_cin2 & {int(i["pac_id"]) for i in filas}
|
||||
solo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&estatus=CASO").get_json()["items"]
|
||||
assert {int(i["pac_id"]) for i in solo} == casos
|
||||
|
||||
|
||||
def test_un_caso_es_un_carcinoma_invasor_o_in_situ():
|
||||
"""Fija: la regla de CASO toma CIS y carcinoma, como el índice del escenario de supervivencia, para que la tabla y
|
||||
la supervivencia hablen de las mismas pacientes. Falla si la regla deja fuera el in situ."""
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import webapi.orchestration.reference as referencia
|
||||
|
||||
parametros = tomllib.loads((Path(referencia.__file__).parent / "parametros.toml").read_text(encoding="utf-8"))
|
||||
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
||||
|
||||
Reference in New Issue
Block a user