diff --git a/tests/test_live_estimators.py b/tests/test_live_estimators.py index 99a12ef..7b2d05a 100644 --- a/tests/test_live_estimators.py +++ b/tests/test_live_estimators.py @@ -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"] diff --git a/tests/test_orquestacion_riesgos.py b/tests/test_orquestacion_riesgos.py index a226f0d..d4479f6 100644 --- a/tests/test_orquestacion_riesgos.py +++ b/tests/test_orquestacion_riesgos.py @@ -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"]) diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 1881fe9..4d07a5f 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -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 diff --git a/tests/test_seguimiento.py b/tests/test_seguimiento.py index 7362612..e1987bf 100644 --- a/tests/test_seguimiento.py +++ b/tests/test_seguimiento.py @@ -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"] diff --git a/webapi/follow_up/estratos.toml b/webapi/follow_up/estratos.toml index f31bcbb..6e0f66e 100644 --- a/webapi/follow_up/estratos.toml +++ b/webapi/follow_up/estratos.toml @@ -27,6 +27,7 @@ etiqueta = "Estatus de seguimiento" expression = "cacu.seguimiento:estrato" unidad = "paciente" valores = [ + { valor = "CASO", etiqueta = "Caso (cáncer)" }, { valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" }, { valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" }, { valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" }, @@ -37,6 +38,7 @@ valores = [ seguimiento_marco = "cacu.seguimiento.marco" seguimiento_referencia = "cacu.seguimiento.referencia" seguimiento_precedencia = "cacu.seguimiento.precedencia" +seguimiento_grados_caso = "cacu.seguimiento.caso.grados" seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias" seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito" seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito" diff --git a/webapi/follow_up/listing.py b/webapi/follow_up/listing.py index 580ff2c..b7ff4ac 100644 --- a/webapi/follow_up/listing.py +++ b/webapi/follow_up/listing.py @@ -5,7 +5,9 @@ vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada pacient estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas -de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula. +de CACU_DIAS_TOMA_DIAGNOSTICO), su última biopsia reportada al corte y su probabilidad vigente de LIEAG+ y de +cáncer en cada horizonte (los lotes confirmados que muestra su ficha). `orden` la ordena por la más reciente o por +una de esas probabilidades a `horizonte`. `prioridad` está reservada y va nula. **Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la @@ -26,7 +28,7 @@ from types import SimpleNamespace from sqlalchemy import func, select from sqlmodel import Session -from webapi.follow_up.silver import citologias, notas +from webapi.follow_up.silver import biopsias, citologias, notas from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de from webapi.orchestration.tables.cacu import TABLAS from webapi.follow_up.view import P @@ -73,6 +75,12 @@ PARAMETROS_DE_LA_LISTA = { "horizonte_dias": "cacu.horizontes.toma_diagnostico_dias", } ESTRATO = "estatus_seguimiento" +# How the list can be ordered: by its most recent study (the default), or by the probability, at `horizonte`, of +# LIEAG+ (CIN2+, the models whose outcome starts with `cin2`), of cancer or of surviving (a case's), highest first. +ORDENES = ("reciente", "lieag", "cancer", "supervivencia") +HORIZONTE_POR_OMISION = 5.0 +# The outcomes other than CIN2+ the list shows, by their key in `probabilidades`. +DESENLACES = {"cancer": "cancer", "muerte": "supervivencia"} class PedidoInvalido(ValueError): @@ -89,6 +97,8 @@ def seguimiento_de( corte: date | None = None, meses: int | None = None, estatus: str | None = None, + orden: str = "reciente", + horizonte: float | None = None, page: int = 1, page_size: int = 50, hoy: date | None = None, @@ -113,6 +123,8 @@ def seguimiento_de( raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.") if estatus is not None and estatus not in ESTATUS: raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.") + if orden not in ORDENES: + raise PedidoInvalido(f"orden desconocido {orden!r}; hay {list(ORDENES)}.") if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA: raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.") @@ -122,6 +134,13 @@ def seguimiento_de( items = _items(sesion, corte, desde, lista, estatus_de, tablas) if estatus is not None: items = [i for i in items if i["estatus"]["codigo"] == estatus] + horizontes = sorted({h["horizonte_anios"] for i in items for p in (i["probabilidades"] or {}).values() for h in p}) + horizonte = HORIZONTE_POR_OMISION if horizonte is None else float(horizonte) + if horizontes and horizonte not in horizontes: + raise PedidoInvalido(f"horizonte = {horizonte:g}: los modelos dan {[f'{h:g}' for h in horizontes]} años.") + if orden != "reciente": + # highest first, patients the model doesn't score last; the sort is stable, so ties stay most recent first + items.sort(key=lambda i: (p := _probabilidad(i, orden, horizonte)) is None or -p) total = len(items) paginas = -(-total // page_size) @@ -132,7 +151,8 @@ def seguimiento_de( "simulado": True, "corte": corte.isoformat(), "ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()}, - "filtros": {"estatus": estatus}, + "filtros": {"estatus": estatus, "orden": orden, "horizonte": horizonte}, + "horizontes_disponibles": horizontes, "estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()], "reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas), "paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas}, @@ -176,6 +196,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]: if "vph" in lista["estudios"] and e["vph"] is not None: de_la_paciente["vph"].append(e) gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])} + biopsia_de = _ultima_biopsia(sesion, corte, tablas) + riesgos = _probabilidades_por_paciente() edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas) notas_de = _notas_por_paciente(sesion, corte) items = [] @@ -199,6 +221,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]: "genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]), }, "dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista), + "ultima_biopsia": biopsia_de.get(pac_id), + "probabilidades": {k: v[pac_id] for k, v in riesgos.items() if pac_id in v} or None, "prioridad": None, "_orden": mas_reciente, }) @@ -207,6 +231,54 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]: return items +def _ultima_biopsia(sesion: Session, corte: date, tablas: TablasKit) -> dict[int, dict]: + """Each patient's latest biopsy reported by the cut-off: its report date and grade (`GradoCIN`).""" + b = biopsias(tablas) + filas = sesion.execute(select(b.c.pac_id, b.c.fecha_reporte, b.c.grado).where(b.c.fecha_reporte.is_not(None))).all() + found: dict[int, dict] = {} + for pac_id, fecha, grado in filas: + fecha = _fecha(fecha) + if fecha <= corte and (pac_id not in found or fecha > date.fromisoformat(found[pac_id]["fecha"])): + found[pac_id] = {"fecha": fecha.isoformat(), "grado": grado} + return found + + +def _probabilidades_por_paciente() -> dict[str, dict[int, list[dict]]]: + """Each patient's current probability of LIEAG+ (`lieag`, the outcomes `cin2*`), of cancer (`cancer`) and of + surviving (`supervivencia`, the complement of the survival model's death) at every horizon, with its interval: the + confirmed batches the patient's record shows (`current_risks_by_patient`).""" + from persistance import cacu + + found: dict[str, dict[int, list[dict]]] = {} + for desenlace, por_paciente in cacu.cohort_repository.current_risks_by_patient().items(): + clave = "lieag" if (desenlace or "").startswith("cin2") else DESENLACES.get(desenlace) + if clave is None: + continue + destino = found.setdefault(clave, {}) + for pac_id, horizontes in por_paciente.items(): + filas = [_horizonte(h, complemento=clave == "supervivencia") for h in horizontes] + if clave == "supervivencia" and filas and not any(f["horizonte_anios"] == 0 for f in filas): + # at the index date every patient is alive + filas.insert(0, {"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0}) + destino.setdefault(pac_id, filas) + return found + + +def _horizonte(h, *, complemento: bool) -> dict: + """A horizon's probability and interval; with `complemento`, of not having the outcome (surviving a death).""" + if not complemento: + return {"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo, + "ic_alto": h.ic_alto} + return {"horizonte_anios": h.horizonte_anios, "probabilidad": 1 - h.probabilidad, + "ic_bajo": None if h.ic_alto is None else 1 - h.ic_alto, + "ic_alto": None if h.ic_bajo is None else 1 - h.ic_bajo} + + +def _probabilidad(item: dict, clave: str, horizonte: float) -> float | None: + return next((h["probabilidad"] for h in ((item["probabilidades"] or {}).get(clave) or []) + if h["horizonte_anios"] == horizonte), None) + + def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]: """Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe).""" c = citologias() diff --git a/webapi/follow_up/routes.py b/webapi/follow_up/routes.py index e057c34..846b3e1 100644 --- a/webapi/follow_up/routes.py +++ b/webapi/follow_up/routes.py @@ -66,4 +66,11 @@ def _requested(args) -> dict: pedido[nombre] = int(texto) if estatus := args.get("estatus"): pedido["estatus"] = estatus + if orden := args.get("orden"): + pedido["orden"] = orden + if (horizonte := args.get("horizonte")) not in (None, ""): + try: + pedido["horizonte"] = float(horizonte) + except ValueError: + raise ValueError(f"horizonte debe ser un número de años; llegó {horizonte!r}") from None return pedido diff --git a/webapi/follow_up/status.py b/webapi/follow_up/status.py index 142e5a7..0868c32 100644 --- a/webapi/follow_up/status.py +++ b/webapi/follow_up/status.py @@ -6,6 +6,8 @@ reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo pasado no cambia cuando la paciente avanza. + CASO una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` (CIS o carcinoma): la + paciente ya tiene cáncer, y lo que se sigue es su supervivencia POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de @@ -38,7 +40,7 @@ from webapi.follow_up.functions import dias_entre from webapi.follow_up.view import P, vista from webapi.orchestration.tables import TablasKit -ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA") +ESTATUS = ("CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA") RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3) MARCOS = ("estatus", "ronda") REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte @@ -81,7 +83,7 @@ def reglas_de(valores: Mapping) -> Reglas: precedencia = tuple(valores["seguimiento_precedencia"]) if sorted(precedencia) != sorted(ESTATUS): raise ReglaDesconocida( - f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; " + f"cacu.seguimiento.precedencia debe ordenar los {len(ESTATUS)} estatus, sin repetir: {ESTATUS}; " f"llegó {precedencia}." ) exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS) @@ -186,6 +188,13 @@ def estatus_al( .group_by(evidencias.c.pac_id) .cte("seguimiento_colposcopia") ) + # Un caso: una biopsia reportada antes de la referencia con un grado de cáncer. + caso = ( + select(reporte.c.pac_id) + .distinct() + .where(antes(reporte.c.fecha_reporte), reporte.c.grado.in_(P("seguimiento_grados_caso", lista=True))) + .cte("seguimiento_caso") + ) tratamiento = ( select(nota.c.pac_id) .distinct() @@ -210,6 +219,7 @@ def estatus_al( ) persona = V_PERSONA cumple = { + "CASO": caso.c.pac_id.is_not(None), "POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None), "POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None), "INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente), @@ -219,7 +229,8 @@ def estatus_al( return ( select(persona.c.pac_id, estatus.label("estatus")) .select_from( - persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id) + persona.outerjoin(caso, caso.c.pac_id == persona.c.pac_id) + .outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id) .outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id) .outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id) ) diff --git a/webapi/imports/schemas/cacu/paciente.py b/webapi/imports/schemas/cacu/paciente.py index 49393dc..1f38733 100644 --- a/webapi/imports/schemas/cacu/paciente.py +++ b/webapi/imports/schemas/cacu/paciente.py @@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema from webapi.imports.schemas.coercion import ( Catalog, CatalogValue, + FlexDate, PostalCode, RequiredDate, RequiredHospitalId, @@ -25,6 +26,8 @@ class PacienteImportSchema(ImportSchema): pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None # IND-01: required, since age at each event of interest is derived from it. pac_fecha_nacimiento: RequiredDate + # Survival's outcome; empty while she is alive or the date is unknown. + pac_fecha_defuncion: FlexDate = None pac_codigo_postal: PostalCode = None pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None diff --git a/webapi/orchestration/cycle.py b/webapi/orchestration/cycle.py index e1b8d77..68ed63d 100644 --- a/webapi/orchestration/cycle.py +++ b/webapi/orchestration/cycle.py @@ -203,20 +203,20 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]: @config.when(with_cohorts=True) -def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]: +def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[tuple[int, bool]]]: """El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008). - Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador - (`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como - un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. - Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden + Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da a cada estimador de la cohorte + (`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los + riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no + duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. Confirmar o anular un lote es la orden `confirm-risks`, no este paso. """ tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES lotes = {} for url in cohort_urls(ctx.project, _manifest(ctx)): - estimador = ctx.estimators.get(url) - if estimador is None: + estimadores = ctx.estimators.get(url) or [] + if not estimadores: continue def frame(sesion, url=url): @@ -226,8 +226,9 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu armado_id, ancho = ctx.repos.gold.cohorts.read(frame) if armado_id is None: continue - riesgos = [tuple(r) for r in estimador.estimar(*ancho)] - lotes[url] = ctx.repos.gold.cohorts.save_batch( - armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos - ) + lotes[url] = [] + for estimador in estimadores: + riesgos = [tuple(r) for r in estimador.estimar(*ancho)] + lotes[url].append(ctx.repos.gold.cohorts.save_batch( + armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos)) return lotes diff --git a/webapi/orchestration/estimators.py b/webapi/orchestration/estimators.py index 473b923..94c4ef2 100644 --- a/webapi/orchestration/estimators.py +++ b/webapi/orchestration/estimators.py @@ -1,5 +1,5 @@ -"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version -its domain has in production. +"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with every model version +of its domain in production, one batch per model. `estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`, `desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger @@ -11,7 +11,6 @@ unused by design. from dataclasses import dataclass from importlib import import_module -from typing import Any @dataclass(frozen=True) @@ -61,45 +60,19 @@ class ScenarioEstimator: return self._provenance -class Cin2LogisticEstimator(ScenarioEstimator): - """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`).""" - - def __init__(self, domain: str = "cacu", version: str | None = None): - super().__init__(domain, "cin2_logistic", version) - self.desenlace = "cin2_mas" - - -# The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production -# scores the cohort it names. -LIVE_SCENARIOS = {"cama": ("survival",)} - - -def _scenario_estimators(domain: str) -> dict[str, Any]: +def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]: + """The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the + registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario + definition in `models` is skipped. Empty where none is in production, the same as no estimator being + configured: `estimate` then does nothing.""" from models.dags.training import Scenario from models.io.registry import registry - found = {} - for name in LIVE_SCENARIOS.get(domain, ()): - scenario = Scenario.load(domain, name) + found: dict[str, list[ScenarioEstimator]] = {} + for name in registry.in_production(domain): try: - registry.resolve(domain, name) + scenario = Scenario.load(domain, name) except LookupError: continue - found[scenario.cohort] = ScenarioEstimator(domain, name) + found.setdefault(scenario.cohort, []).append(ScenarioEstimator(domain, name)) return found - - -def live_estimators(domain: str) -> dict[str, Any]: - """The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where - none is in production yet, the same as no estimator being configured: `estimate` then does nothing.""" - if domain != "cacu": - return _scenario_estimators(domain) - from models.dags.training import Scenario - from models.io.registry import registry - - scenario = Scenario.load(domain, "cin2_logistic") - try: - registry.resolve(domain, scenario.scenario) - except LookupError: - return {} - return {scenario.cohort: Cin2LogisticEstimator(domain)} diff --git a/webapi/orchestration/reference/parametros.toml b/webapi/orchestration/reference/parametros.toml index f55b478..d79eeb1 100644 --- a/webapi/orchestration/reference/parametros.toml +++ b/webapi/orchestration/reference/parametros.toml @@ -203,13 +203,20 @@ estado = "provisional" fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo" [cacu.seguimiento.precedencia] -# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de -# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir). +# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de "CASO", +# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cinco, sin repetir). # Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo). -valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"] +valor = ["CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"] estado = "provisional" fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" +[cacu.seguimiento.caso.grados] +# Qué grados de biopsia hacen de la paciente un caso (ya tiene cáncer, invasor o in situ): su estatus es CASO, gane lo +# que gane lo demás, y lo que se le sigue es la supervivencia. Opciones: grados de `GradoCIN`. +valor = ["CIS", "CARCINOMA"] +estado = "provisional" +fuente = "Responsable del proyecto, 2026-11-22: un escenario para las pacientes que ya tienen cáncer, sobre el que se evalúa la supervivencia; falta que clínica la confirme" + [cacu.seguimiento.colposcopia.evidencias] # Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto): # "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos`