Compare commits

...

4 Commits

Author SHA1 Message Date
ulises 9a62ddcdaf CaMa recurrence: import schemas for the follow-up and the new patient variables, silver mappings and /cama/recurrencia
The patient takes the menopausal state, molecular and clinical subtype, integrative cluster, cellularity, mutation load,
Ki-67 category and source of the record; a new import entity carries the recurrence and the last contact; hormone and
anti-HER2 therapy are treatments. The route serves each cohort's scenarios, a scenario's figure and a patient's scenarios
over the live cohort build, computing the models and the bootstrap in the background and caching them per build. Includes
the survival import work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:42 -06:00
edgar 26f2b35338 Retire GET /cacu/pacientes/<id>/riesgo: the record reads the FHIR RiskAssessment
The WebApp patient record now reads GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (WebApp
feature/cohorts-dbt-canonical), so the custom route, its blueprint and its tests go; the risk batches and the
follow-up list point to the FHIR search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:15:55 -06:00
edgar 0c1b383da2 CaCu's individual risk as a FHIR RiskAssessment, and each risk's index date
GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (DEV only, tagged simulado, a searchset validated with R4B, as
TEA's patient resources): the patient's current batch, one prediction per horizon with its outcome, probability and
whenPeriod from the risk's index date, the confidence interval in an extension; declared in the CapabilityStatement.
GET /cacu/pacientes/<id>/riesgo adds riesgo.fecha_indice. Tests and the risk-band fixture carry the index date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:46 -06:00
edgar 7d06f9db9d The cycle builds the cohorts dbt defines; models' moved modules
The `cohorts` and `estimate` steps take the project's cohorts from dbt's manifest (`cohort_urls`) and build each one
with models' `build_of` over dbt's queries, instead of the Python-frame TOMLs in models/cohorts, which are gone; without
a manifest a project has no cohort steps. The recruitment window and cut-off are dbt's vars. The live estimator reads
cin2_logistic through `Scenario` and `KitBuild`, and governance imports `models.reports.experiment`, where models now
keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:18:00 -06:00
39 changed files with 1095 additions and 245 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
set -e
# The notebook runner shares the image but runs with no network, a read-only
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
# system and only the jobs folder (models.reports.notebook_jobs): it never touches /data.
if [ "$1" = "notebooks" ]; then
exec /app/WebApi/.venv/bin/python -m models notebooks serve
fi
+1
View File
@@ -0,0 +1 @@
2026-11-22T10:18:21+00:00
+1 -1
View File
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
dependencies = [
"flask>=3.0",
"persistance",
"models[notebooks]",
"models[notebooks,seer-survival]",
"extraction",
"apache-hamilton>=1.90",
"pandas>=2.0",
File diff suppressed because one or more lines are too long
+18 -8
View File
@@ -16,9 +16,9 @@ armado = [
]
lote_final = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, fecha_indice = 2025-08-01, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
[[caso]]
@@ -34,6 +34,16 @@ incluye = ["armado", "lote_final"]
filas = []
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
[[caso]]
nombre = "el periodo es el de la fecha índice del riesgo, no la del miembro"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-09-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0 }
espera."2025-S2" = { "cat:BAJO" = 1 }
[[caso]]
nombre = "los cortes son parámetros"
incluye = ["armado", "lote_final"]
@@ -46,7 +56,7 @@ nombre = "un lote preliminar más nuevo no desplaza al vigente"
incluye = ["armado", "lote_final"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
@@ -54,7 +64,7 @@ espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
nombre = "una evaluación anulada en su versión 2 queda sin dato"
incluye = ["armado", "lote_final"]
filas = [
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
]
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
@@ -63,7 +73,7 @@ nombre = "una evaluación a otro horizonte no cuenta"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
@@ -72,7 +82,7 @@ nombre = "sin lote confirmado no hay población"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
@@ -82,6 +92,6 @@ filas = [
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0 }
+109
View File
@@ -0,0 +1,109 @@
"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cacu`): a patient's
current risk as a FHIR R4 `RiskAssessment` in a `searchset` Bundle, as TEA's patient resources are served: the
resource's shape (status, subject, method, one prediction per horizon from the risk's index date, the interval
extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the
`CapabilityStatement` entry. The reads behind it are Persistance's, tested there.
Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaCu demonstration
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a surveillance build with two of its patients, one
with a confirmed batch whose risks have the model's index date.
"""
import os
from datetime import date, datetime, timezone
import pytest
from conftest import cliente_de
MODEL_INDEX = date(2026, 6, 1)
@pytest.fixture(scope="module")
def client(tmp_path_factory):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
with pytest.MonkeyPatch.context() as mp:
mp.setenv("DEV_REVISION", "pruebas")
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0 and 3 years, the
3-year one with an interval. Returns (scored patient, member without risks)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
from persistance import cacu
from persistance.db import get_cacu_session
scored, unscored = [p.pac_id for p in cacu.persona_repository.list(limit=2)]
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 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 (scored, unscored)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_mas", [(scored, MODEL_INDEX, 3.0, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.0, 0.08, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, batch
def test_a_scored_patient_gets_her_risk_assessment(client, seeded):
"""Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/<pac_id>`, evaluated
when the batch was, by the registered model and version, with one prediction per horizon whose period starts at
the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension;
tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere."""
scored, _, batch = seeded
response = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}")
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
bundle = response.get_json()
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1)
risk = bundle["entry"][0]["resource"]
assert bundle["entry"][0]["fullUrl"].endswith(f"/cacu/fhir/RiskAssessment/{batch}-{scored}")
assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"})
assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z"
assert risk["method"]["coding"][0]["code"] == "cacu-cin2_pim" and risk["method"]["coding"][0]["version"] == "3"
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["cin2_mas", "cin2_mas"]
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
(0.08, {"start": "2026-06-01", "end": "2026-06-01"}), (0.21, {"start": "2026-06-01", "end": "2029-06-01"})]
assert "extension" not in risk["prediction"][0]
assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}}
assert any(t["code"] == "simulado" for t in risk["meta"]["tag"])
def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded):
"""Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error.
Fails if a missing risk becomes a 404 or a resource with no predictions."""
_, unscored, _ = seeded
for subject in (f"Patient/{unscored}", "Patient/987654321"):
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject={subject}").get_json()
assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry`
@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"])
def test_the_risk_is_searched_by_patient(client, query):
"""Pins down: without `subject=Patient/<pac_id>` the answer is a 400 `OperationOutcome`. Fails if the route lists
every patient's risk."""
response = client.get(f"/cacu/fhir/RiskAssessment{query}")
assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome"
def test_the_capability_statement_declares_the_search(client):
"""Pins down: CaCu's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient
resources stay TEA's. Fails if the route exists without being declared, or the other way round."""
resources = client.get("/cacu/fhir/metadata").get_json()["rest"][0]["resource"]
risk = [r for r in resources if r["type"] == "RiskAssessment"]
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
+13 -6
View File
@@ -15,6 +15,7 @@ from sqlalchemy import create_engine, text
from sqlmodel import Session
from webapi.orchestration import Context, run
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.connection import point_to
ANIO = 2025
@@ -65,16 +66,22 @@ def test_volver_a_correr_no_agrega_reportes(bases):
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
def test_en_cacu_arma_su_cohorte_una_vez(bases):
def test_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases):
"""Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores
as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from
anywhere else than dbt, or a build's count and members disagree."""
proyecto, ctx, motor, _, pasos = bases
if proyecto != "cacu":
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
assert "cohorts" not in [p.name for p in pasos]
return
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
armados = [p.summary for p in pasos if p.name == "cohorts"][0]
assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados
with motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
for armado_id, _ in armados.values():
assert con.execute(text("SELECT n_miembros FROM cohorte_armado WHERE armado_id = :a"),
{"a": armado_id}).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
+14 -4
View File
@@ -1,5 +1,7 @@
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
import json
import pytest
from hamilton import driver
@@ -33,8 +35,16 @@ def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
assert {"load", "catalogs"} <= antes(deps, "check_silver")
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
def test_las_cohortes_son_las_del_manifiesto_de_dbt(tmp_path, monkeypatch):
"""Pins down: a project builds cohorts and estimates only if dbt's manifest has a cohort of it (`meta.cohort` of
a population query), today only CaCu's; without a manifest no project does. Fails if the cycle reads cohort
definitions from anywhere else than dbt."""
manifest = tmp_path / "manifest.json"
nodo = {"config": {"meta": {"cohort": "cacu/cohorte_vigilancia", "kind": "population"}}}
manifest.write_text(json.dumps({"nodes": {"model.p.cacu_surveillance_all_patients": nodo}}))
assert {"cohorts", "estimate"} <= set(steps_of("cacu", manifest))
for proyecto in ("cama", "tea"):
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
assert not {"cohorts", "estimate"} & set(steps_of(proyecto, manifest))
monkeypatch.delenv("DBT_MANIFEST", raising=False)
assert not {"cohorts", "estimate"} & set(steps_of("cacu"))
+1 -1
View File
@@ -38,7 +38,7 @@ class EstimadorFijo:
def estimar(self, columnas, filas):
self.columnas = columnas
return [(fila[0], self.horizonte, self.probabilidad, None, None) for fila in filas]
return [(fila[0], fila[1], self.horizonte, self.probabilidad, None, None) for fila in filas]
@pytest.fixture
-87
View File
@@ -1,87 +0,0 @@
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
there.
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
"""
from datetime import date, datetime, timezone
import pytest
from conftest import cliente_de
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"}
HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"}
@pytest.fixture(scope="module")
def client(tmp_path_factory):
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
with pytest.MonkeyPatch.context() as mp:
mp.delenv("DEV_REVISION", raising=False)
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
from persistance import cacu
from persistance.db import get_cacu_session
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 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 (scored, unscored)])
session.flush()
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, outside
def test_a_scored_member_has_the_contracts_shape(client, seeded):
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
the WebApp's validation."""
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
body = response.get_json()
assert response.status_code == 200 and body["simulado"] is True
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
horizons = body["riesgo"]["horizontes"]
assert all(set(h) == HORIZON_KEYS for h in horizons)
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
null. Fails if either case errors or invents a risk."""
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
assert member["cohorte"] is not None and member["riesgo"] is None
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
def test_an_unknown_patient_is_404(client, seeded):
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
+1 -1
View File
@@ -41,7 +41,7 @@ def batches(client):
def batch(version, risk, ahora):
lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version},
"cin2_12m", [(pac_id, 1.0, risk, None, None)], ahora=ahora)
"cin2_12m", [(pac_id, date(2025, 1, 1), 1.0, risk, None, None)], ahora=ahora)
return lote_id
older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc))
Generated
+188 -3
View File
@@ -992,6 +992,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/86/32914542064b8aee77ac48142f8a1955df78da4eb905dd41697d26941d21/fhir_resources-8.3.0-py2.py3-none-any.whl", hash = "sha256:151e6c9b4336e36383cc2aaf2067a6f112a420fce1c7bd289182e55dd950871b", size = 2288069, upload-time = "2026-07-03T15:23:51.97Z" },
]
[[package]]
name = "filelock"
version = "4.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/6c/bf/a895b0b8e83d0a64d134f658e393e83998abfc22bbb8b58181ce55268706/filelock-4.3.0.tar.gz", hash = "sha256:143407310acf479e82d88068e3b9a6486f45fb410c0ed8729fe7359eaabeb6f1", size = 742199, upload-time = "2026-11-22T02:15:03.187Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/68/66/870b527908a06c7ec0e91239bd2c4d0bb22921efd4f915428b4e47d461a6/filelock-4.3.0-py3-none-any.whl", hash = "sha256:f933f39f7e01249a4a49b9abab30edc6d4b874624c3de5dd0b0d137aa8adb979", size = 244553, upload-time = "2026-11-22T02:15:01.667Z" },
]
[[package]]
name = "flask"
version = "3.1.3"
@@ -1354,6 +1363,69 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
]
[[package]]
name = "hf-xet"
version = "1.8.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" },
{ url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" },
{ url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" },
{ url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" },
{ url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" },
{ url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" },
{ url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" },
{ url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" },
{ url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" },
{ url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" },
{ url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" },
{ url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" },
{ url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" },
{ url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" },
{ url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" },
{ url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" },
]
[[package]]
name = "httpcore2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h11" },
{ name = "truststore" },
]
sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" },
]
[[package]]
name = "httpx2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio", marker = "sys_platform != 'emscripten'" },
{ name = "httpcore2", marker = "sys_platform != 'emscripten'" },
{ name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" },
{ name = "idna" },
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" },
]
[[package]]
name = "httpx2-jsfetch"
version = "1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
]
[[package]]
name = "huey"
version = "3.4.0"
@@ -1363,6 +1435,26 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/57/31/cee585bd4d1e39947a426a6736f4e17d22b454952370fb9cf48eb3103085/huey-3.4.0-py3-none-any.whl", hash = "sha256:d0580762397744026f83baae5f2b97a62474a62b8565ac75bbafefe72f9c784f", size = 136493, upload-time = "2026-09-04T02:04:32.848Z" },
]
[[package]]
name = "huggingface-hub"
version = "2.4.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click" },
{ name = "filelock" },
{ name = "fsspec" },
{ name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
{ name = "httpx2" },
{ name = "packaging" },
{ name = "pyyaml" },
{ name = "tqdm" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" },
]
[[package]]
name = "idna"
version = "3.20"
@@ -2068,32 +2160,66 @@ notebooks = [
{ name = "nbclient" },
{ name = "nbconvert" },
]
seer-survival = [
{ name = "matplotlib" },
{ name = "mpmath" },
{ name = "networkx" },
{ name = "pgmpy" },
{ name = "scipy" },
{ name = "statsmodels" },
]
[package.metadata]
requires-dist = [
{ name = "apache-hamilton", specifier = ">=1.90" },
{ name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" },
{ name = "extraction", editable = "../Extraction" },
{ name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" },
{ name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" },
{ name = "mlflow", specifier = ">=2.9" },
{ name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" },
{ name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" },
{ name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" },
{ name = "networkx", marker = "extra == 'seer-survival'", specifier = ">=3.0" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "pandera", specifier = ">=0.20" },
{ name = "persistance", editable = "../Persistance" },
{ name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" },
{ name = "pyarrow", specifier = ">=15" },
{ name = "scikit-learn", specifier = ">=1.4" },
{ name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" },
{ name = "statsmodels", marker = "extra == 'seer-survival'", specifier = ">=0.14" },
{ name = "tea", editable = "../models/libs/tea" },
{ name = "tea", extras = ["s3"], marker = "extra == 'eeg-reference'", editable = "../models/libs/tea" },
]
provides-extras = ["eeg-reference", "notebooks"]
provides-extras = ["eeg-reference", "notebooks", "seer-survival", "seer-survival-dca"]
[package.metadata.requires-dev]
dev = [
{ name = "ipykernel", specifier = ">=6.29" },
{ name = "matplotlib", specifier = ">=3.8" },
{ name = "mpmath", specifier = ">=1.3" },
{ name = "nbclient", specifier = ">=0.10" },
{ name = "nbconvert", specifier = ">=7.16" },
{ name = "networkx", specifier = ">=3.0" },
{ name = "pgmpy", specifier = ">=1.0" },
{ name = "pytest", specifier = ">=8.0.0" },
{ name = "reportlab", specifier = ">=4.0" },
{ name = "scipy", specifier = ">=1.11" },
{ name = "statsmodels", specifier = ">=0.14" },
]
notebooks = [
{ name = "graphviz", specifier = ">=0.20" },
{ name = "ipykernel", specifier = ">=6.29" },
]
[[package]]
name = "mpmath"
version = "1.4.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c5/b0/6de8e78014ff1842a90cc9a56da6ccfb598a5390ed0257fcdb7d9680c18b/mpmath-1.4.1.tar.gz", hash = "sha256:efd6d1b75f09d69524a67609949812668b28e81ecbfe0ab449ced8c13e92642e", size = 2093211, upload-time = "2026-03-15T01:17:38.245Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/13/f2/abeec3db71d221ccd3cd89d206be1fabf5a3ee7178862f5fba23a59607e0/mpmath-1.4.1-py3-none-any.whl", hash = "sha256:dc4f0ea2304480d4a9a48a94c1020571558ade522b44a6912efac63a586e140f", size = 567787, upload-time = "2026-03-15T01:17:36.392Z" },
]
[[package]]
@@ -2393,6 +2519,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/09/ed/559d2915dce85794bc0c36064043da170da50cd98746dcbddd85d5932017/nest_asyncio2-1.7.4-py3-none-any.whl", hash = "sha256:86e77b52c3d1496b294af3c944b44213b9b82a12a5ee590c0acc4ca4692ef6c7", size = 8543, upload-time = "2026-10-07T22:31:49.245Z" },
]
[[package]]
name = "networkx"
version = "3.7"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" },
]
[[package]]
name = "numba"
version = "0.68.1"
@@ -2564,6 +2699,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" },
]
[[package]]
name = "opt-einsum"
version = "3.4.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004, upload-time = "2024-09-26T14:33:24.483Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932, upload-time = "2024-09-26T14:33:23.039Z" },
]
[[package]]
name = "packaging"
version = "26.3"
@@ -2763,6 +2907,29 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
]
[[package]]
name = "pgmpy"
version = "1.1.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "huggingface-hub" },
{ name = "joblib" },
{ name = "networkx" },
{ name = "numpy" },
{ name = "opt-einsum" },
{ name = "pandas" },
{ name = "pyparsing" },
{ name = "scikit-base" },
{ name = "scikit-learn" },
{ name = "scipy" },
{ name = "statsmodels" },
{ name = "tqdm" },
]
sdist = { url = "https://files.pythonhosted.org/packages/72/9a/b94ccd1d6cbf2982937c26e54e887b47ee10f848ad53c4427965578a358d/pgmpy-1.1.2.tar.gz", hash = "sha256:a62a89352f139a5d459839e54e6bfa202a7d8749e6dc6d7ceec088a71529af45", size = 2183113, upload-time = "2026-04-30T11:34:49.538Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c6/5d/d03634ed296986abad834a69b0df21510cc9b6c40fb8afaed5df1c4b6074/pgmpy-1.1.2-py3-none-any.whl", hash = "sha256:e55c78763a4a45dd644a13b250cea86af0c7e08590cf35de489624f34a4d9a0b", size = 2446383, upload-time = "2026-04-30T11:34:47.189Z" },
]
[[package]]
name = "pillow"
version = "12.3.0"
@@ -3826,6 +3993,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" },
]
[[package]]
name = "scikit-base"
version = "1.2.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d9/e9/287707e71be93558076d873f92444fa788c1a11c259982a1967ad2071b0e/scikit_base-1.2.1.tar.gz", hash = "sha256:6cccfab1cf51e36141b731fe3248bd3c1a55361e965ddc7457be75ad8a9803eb", size = 136836, upload-time = "2026-11-08T20:24:26.859Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c1/b4/21adac81fbb522bdbb74c4809c7ea06fbde847a24c54b68dfed1519ff3dc/scikit_base-1.2.1-py3-none-any.whl", hash = "sha256:8695538dcf61c5439752b56baeca9d4ce52de012ddc4cee50ee67c910a9b5fb9", size = 163886, upload-time = "2026-11-08T20:24:25.324Z" },
]
[[package]]
name = "scikit-learn"
version = "1.9.1"
@@ -4324,6 +4500,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" },
]
[[package]]
name = "truststore"
version = "0.10.5"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" },
]
[[package]]
name = "typeguard"
version = "4.6.0"
@@ -4503,7 +4688,7 @@ dependencies = [
{ name = "flask" },
{ name = "flask-cors" },
{ name = "gunicorn" },
{ name = "models", extra = ["notebooks"] },
{ name = "models", extra = ["notebooks", "seer-survival"] },
{ name = "openpyxl" },
{ name = "pandas" },
{ name = "pdfplumber" },
@@ -4539,7 +4724,7 @@ requires-dist = [
{ name = "flask", specifier = ">=3.0" },
{ name = "flask-cors", specifier = ">=4.0" },
{ name = "gunicorn", specifier = ">=23.0" },
{ name = "models", extras = ["notebooks"], editable = "../models" },
{ name = "models", extras = ["notebooks", "seer-survival"], editable = "../models" },
{ name = "openpyxl", specifier = ">=3.1" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "pdfplumber", specifier = ">=0.11" },
+6 -4
View File
@@ -12,6 +12,8 @@ from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reports import reports_bp
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
from webapi.cama_recurrence.routes import cama_recurrence_bp
from webapi.cama_survival.routes import cama_survival_bp
from webapi.follow_up.routes import follow_up_blueprint
@@ -92,18 +94,18 @@ def create_app() -> Flask:
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
url_prefix=f"/{domain}/fhir")
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
# an access rule still to be defined, not an environment variable.
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
from persistance import cacu as cacu_repositories
from persistance.db import get_cacu_session, get_cama_session
from webapi.patient_risk import patient_risk_blueprint
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(cama_survival_bp, url_prefix="/cama/supervivencia")
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
return app
+2 -2
View File
@@ -8,7 +8,7 @@ either run elsewhere and register its result through `POST /model-versions`
`cohorte_armado_id`), or be triggered in place through `POST
/model-versions/<domain>/<scenario>/train`, for a deployment with no
command-line access to run the `entrenar` compose profile by hand.
Notebooks (`models.pipelines.experiment`) run in the background on the build's
Notebooks (`models.reports.experiment`) run in the background on the build's
file alone and are kept as MLflow runs.
"""
import contextlib
@@ -28,7 +28,7 @@ from models.io.lineage import DOMAINS
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
from models.io.storage import build_file, cohorts_root, exported_builds
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
from models.pipelines import experiment
from models.reports import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
from persistance.settings import settings
View File
+42
View File
@@ -0,0 +1,42 @@
"""`/cama/recurrencia`: the scenarios of each cohort, the figure of one and the scenarios a patient meets."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_recurrence import service
cama_recurrence_bp = Blueprint("cama_recurrence", __name__)
@cama_recurrence_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_recurrence_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_recurrence_bp.get("/figura")
def figure():
cohort = request.args.get("cohorte", "").strip()
scenario = request.args.get("escenario", "").strip()
if not cohort or not scenario:
raise BadRequest("faltan los parámetros «cohorte» y «escenario»")
try:
return jsonify(service.figure(cohort, scenario))
except service.Calculating:
return jsonify({"estado": "calculando"}), 202
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}» en la cohorte «{cohort}»")
except LookupError:
raise NotFound(f"el escenario «{scenario}» no tiene recaídas suficientes para dibujarse")
@cama_recurrence_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+183
View File
@@ -0,0 +1,183 @@
"""CaMa's recurrence analysis over the live cohort build.
Each cohort (METABRIC, SCAN-B) is recoded from the latest build of `cama/cohorte_total` by the dictionary of
`models.cama.recurrence`. Its covariates, the terms of each horizon and the bootstrap of the combined estimate are
computed once per build, in the background, and kept on disk; a scenario's figure is computed when it is asked for and kept
in memory. A new build computes them again.
"""
import hashlib
import pickle
import tempfile
import threading
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.recurrence import analysis, cohort as recurrence_cohort
from models.io.storage import KitBuild
DOMAIN, COHORT = "cama", "cama/cohorte_total"
CACHE_DIR = Path(tempfile.gettempdir()) / "cama_recurrence"
class NotAvailable(LookupError):
"""There is no cohort build to draw on."""
class Calculating(RuntimeError):
"""The cohort's models and bootstrap are still being computed."""
@dataclass
class CohortState:
name: str
frame: pd.DataFrame
scenarios: list[dict]
masks: dict
status: str = "calculando"
error: str | None = None
covariates: list[str] = field(default_factory=list)
dropped: list[str] = field(default_factory=list)
models: dict = field(default_factory=dict)
point: dict = field(default_factory=dict)
draws: dict = field(default_factory=dict)
figures: dict = field(default_factory=dict)
@dataclass
class Live:
build_id: int
model: dict
events: pd.DataFrame
cohorts: dict[str, CohortState]
_lock = threading.RLock()
_live: Live | None = None
def _cache_file(build_id: int, name: str, model_text: str, members: int) -> Path:
key = hashlib.sha256(f"{build_id}|{name}|{members}|{model_text}".encode()).hexdigest()[:20]
return CACHE_DIR / f"{name}-{key}.pkl"
def _compute(state: CohortState, model: dict, cache: Path) -> None:
try:
if cache.is_file():
with cache.open("rb") as handle:
saved = pickle.load(handle)
else:
settings, calculator = model["modeling"], model["calculator"]
horizons = model["config"]["horizons_months"]
cfg = model["cohorts"][state.name]
covariates, dropped = analysis.prune_covariates(state.frame, cfg["covariates"], cfg["treatment"], settings)
models = analysis.select_models(state.frame, covariates, horizons, settings)
calc = analysis.Calculator(state.frame, covariates, models, horizons, settings["bdeu_ess"])
point = calc.risk(np.arange(calc.n), state.masks)
draws = calc.bootstrap(state.masks, calculator["bootstrap_replicas"], settings["seed"])
saved = {"covariates": covariates, "dropped": dropped, "models": models, "point": point, "draws": draws}
CACHE_DIR.mkdir(parents=True, exist_ok=True)
with cache.open("wb") as handle:
pickle.dump(saved, handle)
with _lock:
state.covariates, state.dropped, state.models = saved["covariates"], saved["dropped"], saved["models"]
state.point, state.draws, state.status = saved["point"], saved["draws"], "listo"
except Exception as error: # the cohort reports its failure; the others keep working
with _lock:
state.status, state.error = "error", f"{type(error).__name__}: {error}"
def live() -> Live:
"""The latest build's cohorts; recoded again only when the build changed."""
global _live
repositories = import_module(f"persistance.{DOMAIN}")
build_id = repositories.cohort_repository.latest_build(COHORT)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el análisis de recurrencia")
with _lock:
if _live is not None and _live.build_id == int(build_id):
return _live
model = recurrence_cohort.load()
model_text = recurrence_cohort.TOML.read_text(encoding="utf-8")
events = KitBuild(DOMAIN, int(build_id)).frame()
cohorts = {}
for name, cfg in model["cohorts"].items():
frame = recurrence_cohort.recode(events, model, name)
if frame.empty:
continue
scenarios = cfg["scenarios"]
state = CohortState(name, frame, scenarios, analysis.scenario_masks(frame, scenarios))
cohorts[name] = state
cache = _cache_file(int(build_id), name, model_text, len(frame))
threading.Thread(target=_compute, args=(state, model, cache), daemon=True).start()
_live = Live(int(build_id), model, events, cohorts)
return _live
def _cohort(current: Live, name: str) -> CohortState:
if name not in current.cohorts:
raise KeyError(name)
return current.cohorts[name]
def scenarios() -> dict:
current = live()
minimum = current.model["calculator"]["min_events"]
cohorts = []
for name, state in current.cohorts.items():
rows = []
for scenario in state.scenarios:
mask = state.masks[scenario["name"]]
events = int(state.frame.loc[mask, "evento"].sum())
rows.append({"nombre": scenario["name"], "condiciones": scenario["when"], "n": int(mask.sum()),
"recaidas": events, "dibujable": events >= minimum})
cohorts.append({"id": name, "nombre": current.model["cohorts"][name]["name"], "estado": state.status,
"error": state.error, "escenarios": rows})
return {"build": current.build_id, "horizontes": current.model["config"]["horizons_months"], "cohortes": cohorts}
def figure(cohort: str, scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for an unknown cohort or scenario, `Calculating` while the cohort
is being computed, `LookupError` when the scenario has too few recurrences to be drawn."""
current = live()
state = _cohort(current, cohort)
if scenario not in state.masks:
raise KeyError(scenario)
with _lock:
if state.status == "calculando":
raise Calculating(cohort)
if state.status == "error":
raise RuntimeError(state.error)
if scenario not in state.figures:
figure_record = analysis.scenario_figure(
state.frame, scenario, state.masks[scenario], state.point[scenario], state.draws[scenario],
current.model["config"]["horizons_months"], current.model["calculator"])
if figure_record is None:
raise LookupError(scenario)
state.figures[scenario] = {"cohorte": cohort, "cohorte_nombre": current.model["cohorts"][cohort]["name"],
"condiciones": next(s["when"] for s in state.scenarios if s["name"] == scenario),
"build": current.build_id, **figure_record}
return state.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient's covariates meet in each cohort; one that needs a covariate she lacks does not include her."""
current = live()
events = current.events[current.events["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
found = []
# The analysis is for patients after treatment: those whose timeline holds the post-treatment scenario.
if not (events["tipo"] == "escenario_postratamiento").any():
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": False, "escenarios": found}
for name, state in current.cohorts.items():
recoded = recurrence_cohort.recode(events, current.model, name, of_source=False, follow_up=False)
if recoded.empty:
continue
masks = analysis.scenario_masks(recoded, state.scenarios)
found += [{"cohorte": name, "escenario": n} for n, mask in masks.items() if bool(mask[0])]
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": True, "escenarios": found}
+5
View File
@@ -0,0 +1,5 @@
"""CaMa's survival figures over the model in production.
service.py the production model and the live cohort, a scenario's figure and a patient's scenarios, cached
routes.py the routes: `/cama/supervivencia/...`
"""
+37
View File
@@ -0,0 +1,37 @@
"""`/cama/supervivencia`: the survival figure of a clinical scenario and the scenarios of a patient."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_survival import service
cama_survival_bp = Blueprint("cama_survival", __name__)
@cama_survival_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_survival_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_survival_bp.get("/figura")
def figure():
scenario = request.args.get("escenario", "").strip()
if not scenario:
raise BadRequest("falta el parámetro «escenario»")
try:
return jsonify(service.figure(scenario))
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}»")
@cama_survival_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+124
View File
@@ -0,0 +1,124 @@
"""The production CaMa survival model over the live cohort build.
A scenario's figure is computed on request from the production version of `cama/seer_survival` and the latest build of its
cohort, and kept per (model version, cohort build, scenario): a new version or a new build computes it again. The saved model
is rehydrated with the current class before it scores (`SeerSurvivalModel.rehydrate`).
"""
import os
import pickle
import threading
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
import mlflow.sklearn
import pandas as pd
from models.cama.seer_survival import seer_model
from models.dags.training import Scenario
from models.io.registry import registry
from models.io.storage import KitBuild
DOMAIN, SCENARIO = "cama", "seer_survival"
class NotAvailable(LookupError):
"""There is no production version, or no cohort build to draw on."""
class SavedFile:
"""The model saved as a file (`CAMA_SURVIVAL_MODEL`), versioned by its modification time."""
def __init__(self, path: str):
self.path = Path(path)
self.version = f"archivo-{int(self.path.stat().st_mtime)}"
def load(self):
with self.path.open("rb") as handle:
return pickle.load(handle)
@dataclass
class Live:
"""The model of the production version and the live build's members, recoded once for both."""
version: str
build_id: int
model: seer_model.SeerSurvivalModel
cohort: pd.DataFrame
frame: object
figures: dict
_lock = threading.RLock()
_live: Live | None = None
def _resolve() -> tuple[str, int, object]:
scenario = Scenario.load(DOMAIN, SCENARIO)
repositories = import_module(f"persistance.{DOMAIN}")
file = os.environ.get("CAMA_SURVIVAL_MODEL")
if file:
if not Path(file).is_file():
raise NotAvailable("no hay un modelo de supervivencia guardado")
resolved = SavedFile(file)
else:
try:
resolved = registry.resolve(DOMAIN, SCENARIO)
except LookupError as error:
raise NotAvailable("no hay una versión del modelo de supervivencia en producción") from error
build_id = repositories.cohort_repository.latest_build(scenario.cohort)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el modelo de supervivencia")
return resolved.version, int(build_id), resolved
def live() -> Live:
"""The production version over the latest build; loaded again only when either changed."""
global _live
version, build_id, resolved = _resolve()
with _lock:
if _live is None or (_live.version, _live.build_id) != (version, build_id):
saved = resolved.load() if isinstance(resolved, SavedFile) else mlflow.sklearn.load_model(resolved.model_uri)
model = seer_model.SeerSurvivalModel.rehydrate(saved)
cohort = KitBuild(DOMAIN, build_id).frame()
recoded = model.recode(cohort)
_live = Live(version, build_id, model, cohort, model.frame(recoded), {})
return _live
def scenarios() -> dict:
current = live()
return {"model_version": current.version, "build": current.build_id, "scenarios": current.model.scenario_names()}
def figure(scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for a scenario the model doesn't define."""
current = live()
if scenario not in current.model.scenario_names():
raise KeyError(scenario)
with _lock:
if scenario not in current.figures:
settings = seer_model.figure_settings()
current.figures[scenario] = {
"model_version": current.version, "build": current.build_id,
**current.model.figure_record(
current.frame, scenario, ks_max_seconds=settings["ks_max_seconds"], n_boot=settings["n_boot"],
min_members=settings["min_members"], min_deaths=settings["min_deaths"])}
return current.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient belongs to, from her variables over the timeline (age, stage, subtype, surgery)."""
current = live()
events = current.cohort[current.cohort["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
model = current.model
recoded = model.recode(events)
names = []
if len(recoded):
masks = model.scenario_masks(model.frame(recoded))
names = [name for name, mask in masks.items() if bool(mask[0])]
return {"model_version": current.version, "build": current.build_id, "pac_id": pac_id, "scenarios": names}
+29 -1
View File
@@ -1,4 +1,5 @@
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA and CaCu, its patients' screening and
individual risk.
GET metadata CapabilityStatement
GET Measure, Measure/<id> the measures (dbt's definitions)
@@ -8,6 +9,7 @@
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's individual risk, the current batch (DEV only)
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
@@ -36,6 +38,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
blueprint = Blueprint(f"{project}_fhir", __name__)
titles = labels(manifest)
patients = with_patients and project == "tea"
risks = with_patients and project == "cacu"
def definitions() -> dict:
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
@@ -80,6 +83,9 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
"definition": canonical("OperationDefinition/resumen-tea")}]},
{"type": "ValueSet", "interaction": [{"code": "read"}]},
]
if risks:
resources += [{"type": "RiskAssessment", "interaction": [{"code": "search-type"}],
"searchParam": [{"name": "subject", "type": "reference"}]}]
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
@@ -169,9 +175,31 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
if patients:
_patient_routes(blueprint, repositories, now)
if risks:
_risk_routes(blueprint, repositories)
return blueprint
def _risk_routes(blueprint: Blueprint, repositories) -> None:
"""CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from webapi.fhir import cacu
@blueprint.get("/RiskAssessment")
def risk_assessments():
subject = request.args.get("subject", "")
reference = subject.removeprefix("Patient/")
if not reference.isdigit():
return outcome(400, "invalid", "falta `subject=Patient/<pac_id>`: el riesgo se busca por paciente")
try:
count, offset = page()
except ValueError as error:
return outcome(400, "invalid", str(error))
pac_id = int(reference)
risk = repositories.cohort_repository.current_risk(pac_id)
found = [] if risk is None else [cacu.risk_assessment(pac_id, risk, simulated_data())]
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
def _period_asked(repositories):
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
if periodo := request.args.get("periodo"):
+62
View File
@@ -0,0 +1,62 @@
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data).
The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed
evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient:
id `<lote_id>-<pac_id>`
status the batch's state (`final`)
subject `Patient/<pac_id>`: CaCu's follow-up list uses the platform's `pac_id` (TEA keeps a
pseudonym until its patients get their own identity)
occurrenceDateTime when the batch was evaluated
method the registered model and its version (MLflow)
prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod`
from the risk's index date (the model's decision point) to that date plus the horizon;
the immediate risk (horizon 0) is a period of one day. A confidence interval, when the
model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a
decimal or a range, not both).
Not yet: `basis` (CaCu doesn't publish its cytology and HPV `Observation`s) and `mitigation` (ASCCP's clinical
action thresholds are for CIN3+; the outcome here is CIN2+).
"""
from datetime import date, datetime, timedelta, timezone
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
OUTCOME = f"{CODE_SYSTEM}/desenlace"
MODEL = f"{CODE_SYSTEM}/modelo"
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"}
DAYS_PER_YEAR = 365.25
def _utc(moment: datetime) -> str:
moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _until(start: date, years: float) -> date:
return start + timedelta(days=round(years * DAYS_PER_YEAR))
def _prediction(horizon, outcome: dict, start: date | None) -> dict:
item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad}
if start is not None:
item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()}
if horizon.ic_bajo is not None and horizon.ic_alto is not None:
item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo},
"high": {"value": horizon.ic_alto}}}]
return item
def risk_assessment(pac_id: int, risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`."""
desenlace = risk.desenlace or "cin2_mas"
outcome = concept(OUTCOME, desenlace, OUTCOMES.get(desenlace))
resource = {
"resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote,
"subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en),
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
}
return tagged(resource, simulated)
+1 -1
View File
@@ -9,7 +9,7 @@ de CACU_DIAS_TOMA_DIAGNOSTICO). `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
misma que usan los lotes de riesgo y `GET /cacu/pacientes/<pac_id>/riesgo`; `id_seudonimo` repite ese valor
misma que usan los lotes de riesgo y `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`; `id_seudonimo` repite ese valor
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
@@ -19,3 +19,21 @@ class BiopsiaMamaImportSchema(ImportSchema):
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
bx_pdf_blob: Optional[bytes] = None
bx_ocr_confianza: Optional[float] = None
bx_tipo_histologico: Optional[str] = None
bx_grado_nottingham: Optional[str] = None
bx_receptor_estrogeno: Optional[str] = None
bx_receptor_estrogeno_pct: Optional[float] = None
bx_receptor_progesterona: Optional[str] = None
bx_receptor_progesterona_pct: Optional[float] = None
bx_her2: Optional[str] = None
bx_her2_fish: Optional[str] = None
bx_ki67_pct: Optional[float] = None
bx_tamano_tumor_mm: Optional[float] = None
bx_ganglios_positivos: Optional[float] = None
bx_invasion_linfovascular: Optional[str] = None
bx_multifocalidad: Optional[str] = None
bx_margenes: Optional[str] = None
bx_pt: Optional[str] = None
bx_pn: Optional[str] = None
bx_lateralidad: Optional[str] = None
bx_localizacion: Optional[str] = None
@@ -22,3 +22,6 @@ class MastografiaImportSchema(ImportSchema):
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
mast_dicom_blob: Optional[bytes] = None
mast_interpretacion: Optional[str] = None
mast_densidad: Optional[str] = None
mast_margen_masa: Optional[str] = None
mast_tipo_hallazgo: Optional[str] = None
@@ -36,3 +36,5 @@ class NotaMedicaImportSchema(ImportSchema):
nm_presion_arterial_sistolica: Optional[int] = None
nm_presion_arterial_diastolica: Optional[int] = None
nm_temperatura: Optional[float] = None
nm_estadio_clinico: Optional[str] = None
nm_metastasis: Optional[str] = None
+14
View File
@@ -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,19 @@ 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
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
pac_estado_civil: Optional[str] = None
pac_raza: Optional[str] = None
pac_brca1: Optional[str] = None
pac_brca2: Optional[str] = None
pac_estado_menopausico: Optional[str] = None
pac_pam50: Optional[str] = None
pac_subtipo_clinico: Optional[str] = None
pac_cluster_integrativo: Optional[str] = None
pac_celularidad: Optional[str] = None
pac_carga_mutacional: Optional[float] = None
pac_ki67_categoria: Optional[str] = None
pac_fuente: Optional[str] = None
@@ -0,0 +1,13 @@
"""Import schema for `core.cama.models.SeguimientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class SeguimientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
seg_tipo: RequiredStr
seg_fecha: FlexDate = None
seg_detalle: Optional[str] = None
@@ -0,0 +1,14 @@
"""Import schema for `core.cama.models.TratamientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class TratamientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
trat_tipo: RequiredStr
trat_fecha: FlexDate = None
trat_detalle: Optional[str] = None
trat_lateralidad: Optional[str] = None
+14
View File
@@ -18,6 +18,8 @@ from persistance.cacu import paciente_repository as cacu_paciente_repository
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
from persistance.cama import tratamiento_mama_repository as cama_tratamiento_mama_repository
from persistance.cama import seguimiento_mama_repository as cama_seguimiento_mama_repository
from persistance.cama import mastografia_repository as cama_mastografia_repository
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
@@ -51,6 +53,8 @@ from webapi.imports.schemas.cama.episodio_clinico import (
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
)
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
from webapi.imports.schemas.cama.tratamiento_mama import TratamientoMamaImportSchema
from webapi.imports.schemas.cama.seguimiento_mama import SeguimientoMamaImportSchema
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
from webapi.imports.schemas.cama.ordenes_estudio import (
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
@@ -150,6 +154,16 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
repository=cama_biometria_hematica_repository,
conflict_fields=None,
),
"cama.TratamientoMama": EntitySpec(
schema=TratamientoMamaImportSchema,
repository=cama_tratamiento_mama_repository,
conflict_fields=None,
),
"cama.SeguimientoMama": EntitySpec(
schema=SeguimientoMamaImportSchema,
repository=cama_seguimiento_mama_repository,
conflict_fields=None,
),
"cama.EpisodioClinico": EntitySpec(
schema=CamaEpisodioClinicoImportSchema,
repository=cama_episodio_clinico_repository,
+17 -33
View File
@@ -37,13 +37,13 @@ from webapi.orchestration.reference.rules import (
from webapi.orchestration.reference.periods import periodos_de_tipos
from webapi.orchestration.tables import tablas_de
from persistance.edges.silver import save_load_in
from sqlmodel import SQLModel, func, select
from sqlmodel import SQLModel, select
from webapi.orchestration.context import Context
from webapi.orchestration.semantic_layer import catalog_layers, event_views
from models.cohorts.build import build_of, latest_build, read_frame
from models.cohorts.definition import read_definition
from webapi.orchestration.project import cohort_definitions, period_types
from models.io.storage import read_queries
from webapi.orchestration.project import cohort_urls, period_types
log = logging.getLogger(__name__)
@@ -188,23 +188,17 @@ def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict
@config.when(with_cohorts=True)
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
"""Arma cada cohorte del proyecto con las reglas de dbt, su única definición: la población, la fecha índice, las
exclusiones y las variables son consultas del manifest (`read_queries`), con su ventana de reclutamiento y su
corte (las variables de dbt), y corren en la base después de `event_models`.
"""
tablas = tablas_de(ctx.project)
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
def armado(definicion, sesion):
corte = ctx.cutoff or _last_load_date(sesion, tablas)
return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
linea=ctx.repos.silver.timeline.query)
manifest = _manifest(ctx)
armados = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
for url in cohort_urls(ctx.project, manifest):
consultas = read_queries(manifest, url)
armados[url] = ctx.repos.gold.cohorts.assemble(
lambda sesion, consultas=consultas: build_of(sesion, consultas, cohortes=tablas_cohorte))
return armados
@@ -220,30 +214,20 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
estimador = ctx.estimators.get(definicion.url)
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
continue
def frame(sesion, definicion=definicion):
armado_id = latest_build(sesion, definicion.url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, definicion,
cohortes=tablas_cohorte)
def frame(sesion, url=url):
armado_id = latest_build(sesion, url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, cohortes=tablas_cohorte)
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[definicion.url] = ctx.repos.gold.cohorts.save_batch(
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
return lotes
def _last_load_date(sesion, tablas) -> date | None:
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
if ultima is None or isinstance(ultima, date):
return ultima.date() if isinstance(ultima, datetime) else ultima
return date.fromisoformat(str(ultima)[:10])
+23 -21
View File
@@ -3,9 +3,9 @@ its domain has in production.
`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
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
set, so an estimator here ignores the wide frame and rebuilds the model's own input (`models.io.storage.KitBuild`):
the cycle's latest build for membership, the domain's timeline for the events, then the production version in
MLflow to score it at the horizons its run recorded (`horizons_years`). `estimar`'s arguments go
unused by design.
"""
@@ -37,28 +37,29 @@ class Cin2LogisticEstimator:
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import mlflow.pyfunc
from persistance.settings import settings
import json
from models.cacu.cin2_logistic.model import SETTINGS
import mlflow.pyfunc
import numpy as np
from models.dags.estimation import estimate_frame
from models.dags.training import Scenario
from models.io.registry import registered_name, registry
from models.io.storage import cohorts_root, read_cohort
from models.pipelines.export_cohort import export_kit_build
from models.io.storage import KitBuild
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
url = SETTINGS["cohort"]
build_id = repos.cohort_repository.latest_build(url)
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
window = SETTINGS["outcome_window_months"]
self.desenlace = f"cin2_{window}m"
scenario = Scenario.load(self.domain, "cin2_logistic")
build_id = repos.cohort_repository.latest_build(scenario.cohort)
resolved = registry.resolve(self.domain, scenario.scenario, self.version)
frame = KitBuild(self.domain, build_id).frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame))
self.desenlace = scenario.outcome
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(risks, window / 12)]
return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))]
def procedencia(self) -> Provenance:
if self._provenance is None:
@@ -71,11 +72,12 @@ def live_estimators(domain: str) -> dict[str, Any]:
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
from models.cacu.cin2_logistic.model import SETTINGS
from models.dags.training import Scenario
from models.io.registry import registry
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, SETTINGS["scenario"])
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}
return {scenario.cohort: Cin2LogisticEstimator(domain)}
+6 -6
View File
@@ -1,9 +1,9 @@
"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`)."""
"""What the cycle needs to know of a project's definitions, all from dbt's manifest: its period types and its cohorts."""
import json
from pathlib import Path
from models.cohorts.definition import ROOT
from models.io.storage import cohort_urls as _cohort_urls
def period_types(proyecto: str, manifest: Path) -> list[str]:
@@ -13,7 +13,7 @@ def period_types(proyecto: str, manifest: Path) -> list[str]:
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
def cohort_definitions(proyecto: str) -> list[Path]:
"""The cohort TOMLs the cycle builds (`models/cohorts/<project>/*.toml`): today only CaCu's surveillance cohort.
Those in `<project>/proposals/` aren't built."""
return sorted((ROOT / proyecto).glob("*.toml"))
def cohort_urls(proyecto: str, manifest: Path | None) -> list[str]:
"""The cohorts the cycle builds: those of the project in dbt's manifest (`Transformation/models/<project>/cohorts/`,
`meta.cohort` of their population query). dbt is their only definition. None without a manifest."""
return _cohort_urls(manifest, proyecto) if manifest else []
+7 -6
View File
@@ -18,7 +18,8 @@ from hamilton.lifecycle import NodeExecutionHook
from webapi.orchestration import cycle
from webapi.orchestration.context import Context
from webapi.orchestration.project import cohort_definitions
from webapi.orchestration.context import dbt_manifest_path
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.repositories import repositories_of
log = logging.getLogger(__name__)
@@ -49,10 +50,10 @@ class _Logbook(NodeExecutionHook):
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
def _driver(proyecto: str, manifest, *adaptadores) -> driver.Driver:
return (driver.Builder()
.with_modules(cycle)
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
.with_config({"with_cohorts": bool(cohort_urls(proyecto, manifest))})
.with_adapters(*adaptadores)
.build())
@@ -61,9 +62,9 @@ def _in_order(dr: driver.Driver) -> list[str]:
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
def steps_of(proyecto: str) -> list[str]:
def steps_of(proyecto: str, manifest=None) -> list[str]:
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
return _in_order(_driver(proyecto))
return _in_order(_driver(proyecto, manifest or dbt_manifest_path()))
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
@@ -75,7 +76,7 @@ def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
if ctx.repos is None:
ctx = replace(ctx, repos=repositories_of(ctx.project))
bitacora = _Logbook()
dr = _driver(ctx.project, bitacora)
dr = _driver(ctx.project, ctx.dbt_manifest, bitacora)
todos = _in_order(dr)
pedidos = [p for p in todos if only is None or p in only]
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
+81 -8
View File
@@ -4,10 +4,10 @@
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
"""
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente, SeguimientoMama, TratamientoMama
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.extracted import ConEstructurado, DesdeTexto
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
@@ -36,11 +36,39 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"biopsia.her2", "biopsia.ki67_pct"),
texto=lambda f: f.bx_pdf_blob,
)
DE_LA_MASTOGRAFIA = ConEstructurado(DE_LA_INTERPRETACION, {"mastografia.densidad": "mast_densidad"})
# A mammogram's findings, each a part of its report.
LOS_HALLAZGOS = (
Hija("mastografia", "parte", solo_si=("mast_margen_masa",), fecha="mast_fecha_reporte",
resultados={"mast_margen_masa": "mastografia.margen_masa"}),
Hija("mastografia", "parte", solo_si=("mast_tipo_hallazgo",), fecha="mast_fecha_reporte",
resultados={"mast_tipo_hallazgo": "mastografia.tipo_hallazgo"}),
)
DE_LA_NOTA = DesdeTexto(
"cama", ("nota_medica.estadio_clinico",),
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
)
# What a biopsy report and a note carry structured wins over the text's reading; the rest is read from the text.
DE_LA_PATOLOGIA = ConEstructurado(DEL_REPORTE_DE_PATOLOGIA, {
"biopsia.tipo_histologico": "bx_tipo_histologico", "biopsia.grado_nottingham": "bx_grado_nottingham",
"biopsia.receptor_estrogeno": "bx_receptor_estrogeno", "biopsia.receptor_estrogeno_pct": "bx_receptor_estrogeno_pct",
"biopsia.receptor_progesterona": "bx_receptor_progesterona",
"biopsia.receptor_progesterona_pct": "bx_receptor_progesterona_pct", "biopsia.her2": "bx_her2",
"biopsia.ki67_pct": "bx_ki67_pct", "biopsia.her2_fish": "bx_her2_fish",
"biopsia.tamano_tumor_mm": "bx_tamano_tumor_mm", "biopsia.ganglios_positivos": "bx_ganglios_positivos",
"biopsia.invasion_linfovascular": "bx_invasion_linfovascular", "biopsia.multifocalidad": "bx_multifocalidad",
"biopsia.margenes": "bx_margenes", "biopsia.pt": "bx_pt", "biopsia.pn": "bx_pn",
})
DE_LA_NOTA_ESTRUCTURADA = ConEstructurado(DE_LA_NOTA, {
"nota_medica.estadio_clinico": "nm_estadio_clinico", "nota_medica.m": "nm_metastasis",
})
# The biopsy's sample: the breast and the site it was taken from, dated by its request or, without one, its report.
LA_TOMA_DE_LA_BIOPSIA = Hija(
"biopsia", "toma", solo_si=("bx_lateralidad", "bx_localizacion"), fecha="bx_fecha_toma",
resultados={"bx_lateralidad": "biopsia.lateralidad", "bx_localizacion": "biopsia.localizacion"},
)
DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
@@ -51,17 +79,62 @@ DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
derivadas=DE_LA_INTERPRETACION.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
fuentes=DE_LA_INTERPRETACION.fuentes,
derivadas=DE_LA_MASTOGRAFIA.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_MASTOGRAFIA.resultados},
fuentes=DE_LA_MASTOGRAFIA.fuentes, hijas=LOS_HALLAZGOS,
),
DeStaging(
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
derivadas={**DE_LA_PATOLOGIA.derivadas,
"bx_fecha_toma": lambda f: f.bx_fecha_solicitud or f.bx_fecha_reporte},
fuentes=DE_LA_PATOLOGIA.fuentes,
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
resultados={"bx_grado_histologico": "biopsia.grado", **DE_LA_PATOLOGIA.resultados}),
LA_TOMA_DE_LA_BIOPSIA),
),
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA_ESTRUCTURADA),
# Facts of the patient with no date of their own: dated at her birth, known as of the load.
DeStaging(
Paciente, "pac_id", "parte", estudio_id="sociodemografico", fecha="pac_fecha_nacimiento",
resultados={"pac_estado_civil": "sociodemografico.estado_civil", "pac_raza": "sociodemografico.raza",
"pac_estado_menopausico": "sociodemografico.estado_menopausico",
"pac_fuente": "sociodemografico.fuente"},
),
DeStaging(
Paciente, "pac_id", "reporte", estudio_id="prueba_genetica", fecha="pac_fecha_nacimiento",
solo_si=lambda f: f.pac_brca1 is not None or f.pac_brca2 is not None,
resultados={"pac_brca1": "prueba_genetica.brca1", "pac_brca2": "prueba_genetica.brca2"},
),
*(
DeStaging(
TratamientoMama, "trat_id", "encuentro", estudio_id=estudio, fecha="trat_fecha",
solo_si=lambda f, e=estudio: f.trat_tipo == e,
resultados={"trat_detalle": resultado, **({"trat_lateralidad": "cirugia.lateralidad"} if estudio == "cirugia" else {})},
)
for estudio, resultado in (
("cirugia", "cirugia.tipo_cirugia"), ("radioterapia", "radioterapia.intencion"),
("quimioterapia", "quimioterapia.intencion"), ("hormonoterapia", "hormonoterapia.intencion"),
("anti_her2", "anti_her2.intencion"),
)
),
*(
DeStaging(
SeguimientoMama, "seg_id", "encuentro", estudio_id=estudio, fecha="seg_fecha",
solo_si=lambda f, e=estudio: f.seg_tipo == e, resultados={"seg_detalle": resultado},
)
for estudio, resultado in (("recurrencia", "recurrencia.sitio"), ("ultimo_contacto", "ultimo_contacto.estado"))
),
DeStaging(
Paciente, "pac_id", "parte", estudio_id="perfil_molecular", fecha="pac_fecha_nacimiento",
solo_si=lambda f: any(getattr(f, c) is not None for c in (
"pac_pam50", "pac_subtipo_clinico", "pac_cluster_integrativo", "pac_celularidad", "pac_carga_mutacional",
"pac_ki67_categoria")),
resultados={"pac_pam50": "perfil_molecular.pam50", "pac_subtipo_clinico": "perfil_molecular.subtipo_clinico",
"pac_cluster_integrativo": "perfil_molecular.cluster_integrativo",
"pac_celularidad": "perfil_molecular.celularidad",
"pac_carga_mutacional": "perfil_molecular.carga_mutacional",
"pac_ki67_categoria": "perfil_molecular.ki67_categoria"},
),
)
+39
View File
@@ -117,3 +117,42 @@ def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
if texto is not None and str(texto.value).strip():
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
return None, None
@dataclass(frozen=True)
class ConEstructurado:
"""`DesdeTexto` whose results the row may carry already structured: a structured column wins over what the text
gives, and a column with no text twin is a result of its own. `estructurados`: result -> staging column;
each result keeps the text reading as its fallback when `lector` has it."""
lector: DesdeTexto | None
estructurados: dict[str, str]
@property
def derivadas(self) -> dict[str, Callable]:
columnas = dict(self.lector.derivadas) if self.lector else {}
leidos = set(self.lector.resultado_ids) if self.lector else set()
for resultado_id, columna in self.estructurados.items():
clave = _columna(resultado_id)
texto = self.lector.derivadas[clave] if resultado_id in leidos else (lambda f: None)
fuente = self.lector.derivadas[clave + "_fuente"] if resultado_id in leidos else (lambda f: None)
columnas[clave] = lambda f, c=columna, t=texto: _con_valor(getattr(f, c, None), t(f))
columnas[clave + "_fuente"] = lambda f, c=columna, t=fuente: (
None if _vacio(getattr(f, c, None)) else t(f))
return columnas
@property
def resultados(self) -> dict[str, str]:
return {_columna(r): r for r in {*(self.lector.resultado_ids if self.lector else ()), *self.estructurados}}
@property
def fuentes(self) -> dict[str, str]:
return {columna: columna + "_fuente" for columna in self.resultados}
def _vacio(valor) -> bool:
return valor is None or (isinstance(valor, str) and not valor.strip())
def _con_valor(estructurado, leido):
return leido if _vacio(estructurado) else estructurado
+1
View File
@@ -22,6 +22,7 @@ def de_derechohabiente(paciente) -> dict:
"dependencia": texto_limpio(paciente.pac_dependencia),
"parentesco": texto_limpio(paciente.pac_parentesco),
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
"fecha_defuncion": paciente.pac_fecha_defuncion,
}
-49
View File
@@ -1,49 +0,0 @@
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
removed or renamed, only added.
"""
from datetime import timezone
from flask import Blueprint, jsonify
COHORT_URL = "cacu/cohorte_vigilancia"
COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
def patient_risk_blueprint(repositories) -> Blueprint:
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("cacu_patient_risk", __name__)
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
def get_patient_risk(pac_id: int):
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
if repositories.persona_repository.get(pac_id) is None:
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
membership = repositories.cohort_repository.membership(pac_id, COHORT_URL)
risk = repositories.cohort_repository.current_risk(pac_id)
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
return blueprint
def _cohort(membership) -> dict | None:
if membership is None:
return None
return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(),
**{name: membership.variables.get(name) for name in COHORT_VARIABLES}}
def _risk(risk) -> dict | None:
if risk is None:
return None
evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc)
return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version,
"evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"estado_lote": risk.estado_lote,
"horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
"ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}
+3 -2
View File
@@ -1,7 +1,8 @@
"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
confirm one (`preliminary` -> `final`, visible on `/cacu/pacientes/<id>/riesgo`) or void it (`entered-in-error`).
confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`,
`/cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`) or void it (`entered-in-error`).
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
to be defined, as `patient_risk.py` notes for reads.
to be defined.
"""
from flask import Blueprint, jsonify, request