From 229659889626153dc7c43ff7986fdf6d0c65e111 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 01/24] CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is //indicadores --- tests/conftest.py | 43 +- .../casos_confirmacion_citologia.toml | 114 + tests/fixtures/casos_riesgo_banda.toml | 87 + tests/fixtures/kit_cacu_snapshot.json | 1264 +++ tests/fixtures/kit_cacu_timeline.json | 387 + tests/fixtures/kit_oracle_cacu.json | 7735 +++++++++++++++++ tests/fixtures/kit_oracle_cama.json | 6242 +++++++++++++ tests/test_cama_measures.py | 87 + tests/test_imports_endpoints.py | 13 + tests/test_indicadores_cacu.py | 338 - tests/test_indicadores_cama.py | 229 - tests/test_indicadores_tea.py | 169 - tests/test_kpis_route.py | 135 + tests/test_measure_cases.py | 100 + tests/test_metrics_on_request.py | 461 + tests/test_orquestacion_ciclo.py | 64 +- tests/test_orquestacion_oro.py | 111 +- tests/test_orquestacion_pasos.py | 8 +- tests/test_orquestacion_plata.py | 23 +- tests/test_orquestacion_regla_repositorios.py | 2 +- tests/test_orquestacion_riesgos.py | 20 +- tests/test_orquestacion_timeline.py | 102 +- tests/test_reportes.py | 6 +- tests/test_schemas.py | 20 +- tests/test_schemas_registry.py | 2 + webapi/__init__.py | 14 +- webapi/blueprints/cacu.py | 4 - webapi/blueprints/cama.py | 7 - webapi/blueprints/imports.py | 4 +- webapi/blueprints/tea.py | 7 - webapi/compositions.py | 329 + webapi/durations.py | 291 + webapi/indicadores.py | 231 - webapi/indicadores_vivos.py | 2 +- webapi/kpis.py | 111 + webapi/metrics.py | 502 ++ webapi/orquestacion/__main__.py | 2 +- webapi/orquestacion/ciclo.py | 78 +- webapi/orquestacion/contexto.py | 10 + webapi/orquestacion/proyecto.py | 12 +- webapi/orquestacion/repositorios.py | 17 +- webapi/orquestacion/semantic_layer.py | 78 + 42 files changed, 18123 insertions(+), 1338 deletions(-) create mode 100644 tests/fixtures/casos_confirmacion_citologia.toml create mode 100644 tests/fixtures/casos_riesgo_banda.toml create mode 100644 tests/fixtures/kit_cacu_snapshot.json create mode 100644 tests/fixtures/kit_cacu_timeline.json create mode 100644 tests/fixtures/kit_oracle_cacu.json create mode 100644 tests/fixtures/kit_oracle_cama.json create mode 100644 tests/test_cama_measures.py delete mode 100644 tests/test_indicadores_cacu.py delete mode 100644 tests/test_indicadores_cama.py delete mode 100644 tests/test_indicadores_tea.py create mode 100644 tests/test_kpis_route.py create mode 100644 tests/test_measure_cases.py create mode 100644 tests/test_metrics_on_request.py delete mode 100644 webapi/blueprints/cama.py delete mode 100644 webapi/blueprints/tea.py create mode 100644 webapi/compositions.py create mode 100644 webapi/durations.py delete mode 100644 webapi/indicadores.py create mode 100644 webapi/kpis.py create mode 100644 webapi/metrics.py create mode 100644 webapi/orquestacion/semantic_layer.py diff --git a/tests/conftest.py b/tests/conftest.py index 8be4fce..48973e4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -53,19 +53,21 @@ class Base: return Session(self.motor) -def base_de(proyecto: str, carpeta) -> Base: +def base_de(proyecto: str, carpeta, datos=None) -> Base: + """A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts.""" url = f"sqlite:///{carpeta / f'{proyecto}.db'}" apuntar(proyecto, url) - ctx = Contexto(proyecto, ANIO, ANIO, repos=repositorios_de(proyecto)) + manifest = os.environ.get("DBT_MANIFEST") + ctx = Contexto(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositorios_de(proyecto)) correr(ctx, solo=["migrar"]) motor = create_engine(url) with Session(motor) as sesion: - import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) + (datos or import_module(f"indicadores_kit.{proyecto}.fixtures").insertar)(sesion) sesion.commit() return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor) -@pytest.fixture(params=["cacu", "cama", "tea"]) +@pytest.fixture(params=["cacu", "cama"]) def proyecto(request): return request.param @@ -132,25 +134,16 @@ MESES = ["2025-01", "2025-02", "2025-03"] def cliente_de(proyecto: str, tmp_path_factory): - """Yields a client over a temporary SQLite database seeded with the kit's demonstration data.""" - from indicadores_kit.demostracion import base_de_prueba - from persistance import db - from persistance.settings import settings + """Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging.""" + carpeta = tmp_path_factory.mktemp(proyecto) + base = base_de(proyecto, carpeta) + base.correr("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos", permitir_sin_definir=True) + try: + from webapi import create_app - ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db" - obtener_motor = getattr(db, f"get_{proyecto}_engine") - with pytest.MonkeyPatch.context() as mp: - mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}") - obtener_motor.cache_clear() - try: - base_de_prueba(obtener_motor(), proyecto) - - from webapi import create_app - - app = create_app() - app.config.update(TESTING=True) - with app.test_client() as cliente: - yield cliente - finally: - obtener_motor().dispose() - obtener_motor.cache_clear() + app = create_app() + app.config.update(TESTING=True) + with app.test_client() as cliente: + yield cliente + finally: + base.motor.dispose() diff --git a/tests/fixtures/casos_confirmacion_citologia.toml b/tests/fixtures/casos_confirmacion_citologia.toml new file mode 100644 index 0000000..396d329 --- /dev/null +++ b/tests/fixtures/casos_confirmacion_citologia.toml @@ -0,0 +1,114 @@ +# Casos de CACU_CONFIRMACION_CITOLOGIA (confirmación por biopsia según resultado citológico, C2). +# La unidad es la paciente cuya última citología válida del periodo es de alto grado +# (`cacu.citologia_alto_grado`); la última válida es la de EU7 (`cacu.calidad_insatisfactoria`). +# Cada categoría es `cat:` de la biopsia más grave que originó esa citología (ligada por +# `cit_id`); sin biopsia reportada al corte, `cat:SIN_BIOPSIA`; con biopsia sin grado, `cat:SIN_DATO`. +# `estratos` dice el valor de cada paciente en `citologia_alto_grado`: la fila del panel. Sin `corte`, +# es el día de la carga del caso (2026-01-01). + +measure = "cacu/CACU_CONFIRMACION_CITOLOGIA" + +[[caso]] +nombre = "una paciente con ASC-H y biopsia LIEAG cuenta en LIEAG dentro de la fila ASC-H" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-H" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" }, +] +espera."2025-S1" = { "cat:LIEAG" = 1, "cat:NORMAL" = 1 } +unidades."2025-S1" = { "cat:LIEAG" = ["1"], "cat:NORMAL" = ["2"] } # la 2 es un falso positivo de la fila LIEAG +estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H", "2" = "LIEAG" } + +[[caso]] +nombre = "la última citología válida manda y no la peor" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 2, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEBG" }, +] +espera."2025-S1" = { "cat:LIEBG" = 1 } +estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" } + +[[caso]] +nombre = "con varias biopsias de la toma cuenta la más grave y no la más reciente" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01, bx_cin_grado = "LIEBG" }, + { tabla = "biopsiacervical", bx_id = 3, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-05-01, bx_cin_grado = "NORMAL" }, +] +espera."2025-S1" = { "cat:CIS" = 1, "cat:LIEBG" = 0, "cat:NORMAL" = 0 } + +[[caso]] +nombre = "una biopsia con grado gana a una sin grado; solo sin grado es sin dato" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01 }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" }, + { tabla = "biopsiacervical", bx_id = 3, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01 }, +] +espera."2025-S1" = { "cat:NORMAL" = 1, "cat:SIN_DATO" = 1, "cat:SIN_BIOPSIA" = 0 } +unidades."2025-S1" = { "cat:SIN_DATO" = ["2"] } + +[[caso]] +nombre = "una biopsia reportada después del corte todavía no existe: sin biopsia aún" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" }, +] +corte = 2025-07-31 +espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:LIEAG" = 0 } +estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" } + +[[caso]] +nombre = "el día del corte la biopsia ya existe" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" }, +] +corte = 2025-08-01 +espera."2025-S1" = { "cat:SIN_BIOPSIA" = 0, "cat:LIEAG" = 1 } + +[[caso]] +nombre = "una biopsia de otra toma no cuenta" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 1, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEAG" }, +] +espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:CIS" = 0, "cat:LIEAG" = 0 } +estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" } + +[[caso]] +nombre = "una insatisfactoria posterior no es la última válida" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "INSATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" }, +] +espera."2025-S1" = { "cat:LIEAG" = 1 } +estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" } + +[[caso]] +nombre = "una paciente cuya última citología es NORMAL no entra aunque antes tuviera LIEAG" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" }, + { tabla = "citologiacervical", cit_id = 3, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-US" }, +] +espera."2025-S1" = { "cat:CIS" = 0, "cat:SIN_BIOPSIA" = 0, "cat:NORMAL" = 0 } +estratos."2025-S1".citologia_alto_grado = {} + +[[caso]] +nombre = "la citología cuenta en el periodo de su toma y no en el del reporte de la biopsia" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-20, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-25, cit_celulas_escamosas = "CIS" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "CARCINOMA" }, +] +espera."2025-S1" = { "cat:CARCINOMA" = 1 } +espera."2025-S2" = { "cat:CARCINOMA" = 0 } +estratos."2025-S1".citologia_alto_grado = { "1" = "CIS" } diff --git a/tests/fixtures/casos_riesgo_banda.toml b/tests/fixtures/casos_riesgo_banda.toml new file mode 100644 index 0000000..bd715d3 --- /dev/null +++ b/tests/fixtures/casos_riesgo_banda.toml @@ -0,0 +1,87 @@ +# Casos de CACU_RIESGO_BANDA (pacientes en vigilancia por banda de riesgo, C2). PROPUESTA (MD-Q5). +# Cuenta a las miembros del armado del lote vigente (el mayor con alguna evaluación `final` al +# horizonte) con fecha índice en el periodo, por la banda de la versión más reciente de su +# evaluación. Con los parámetros de `parametros.toml`: BAJO < 0.04 <= INTERMEDIO < 0.25 <= ALTO, +# horizonte 0. `cat:SIN_DATO`: sin evaluación `final` en el lote. + +measure = "cacu/CACU_RIESGO_BANDA" + +[plantillas] +armado = [ + { tabla = "cohorte_armado", armado_id = 1, url = "cacu/cohorte_vigilancia", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 4, 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 = "cohorte_miembro", armado_id = 1, pac_id = 2, fecha_indice = 2025-03-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "2" }, + { tabla = "cohorte_miembro", armado_id = 1, pac_id = 3, fecha_indice = 2025-04-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "3" }, + { tabla = "cohorte_miembro", armado_id = 1, pac_id = 4, fecha_indice = 2025-08-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "4" }, +] +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 }, +] + +[[caso]] +nombre = "cada paciente en la banda de su riesgo; sin evaluación es sin dato" +incluye = ["armado", "lote_final"] +filas = [] +espera."2025-S1" = { "cat:BAJO" = 1, "cat:INTERMEDIO" = 1, "cat:ALTO" = 0, "cat:SIN_DATO" = 1 } +unidades."2025-S1" = { "cat:SIN_DATO" = [3] } + +[[caso]] +nombre = "el periodo es el de la fecha índice" +incluye = ["armado", "lote_final"] +filas = [] +espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 } + +[[caso]] +nombre = "los cortes son parámetros" +incluye = ["armado", "lote_final"] +filas = [] +parametros = { "comun.riesgos.corte_intermedio" = 0.01, "comun.riesgos.corte_alto" = 0.05 } +espera."2025-S1" = { "cat:BAJO" = 0, "cat:INTERMEDIO" = 1, "cat:ALTO" = 1 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 } + +[[caso]] +nombre = "el lote de otra cohorte no cuenta" +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 0 } diff --git a/tests/fixtures/kit_cacu_snapshot.json b/tests/fixtures/kit_cacu_snapshot.json new file mode 100644 index 0000000..10312e7 --- /dev/null +++ b/tests/fixtures/kit_cacu_snapshot.json @@ -0,0 +1,1264 @@ +{ + "cacu/CACU_EU13": { + "2025-01": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null + ] + ] + }, + "2025-02": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-03": { + "grupo_edad": [ + [ + "2", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null + ] + ] + }, + "2025-04": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null + ] + ] + }, + "2025-05": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-06": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-07": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-08": { + "grupo_edad": [ + [ + "5", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null + ] + ] + }, + "2025-09": { + "grupo_edad": [ + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null + ] + ] + }, + "2025-10": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-11": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-12": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-S1": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "2", + "45-54" + ], + [ + "3", + "45-54" + ], + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 4 + ], + "total|total": [ + 0, + 4 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-S2": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "4", + "45-54" + ], + [ + "5", + "45-54" + ], + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 4 + ], + "total|total": [ + 0, + 4 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null + ] + ] + } + }, + "cacu/CACU_EU7": { + "2025-01": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "SIN_DATO" + ] + ] + }, + "2025-02": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|NEGATIVO": 1, + "total|total|NEGATIVO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO" + ] + ] + }, + "2025-03": { + "grupo_edad": [ + [ + "2", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO" + ] + ] + }, + "2025-04": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEBG": 1, + "total|total|LIEBG": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG" + ] + ] + }, + "2025-05": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|NEGATIVO": 1, + "total|total|NEGATIVO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO" + ] + ] + }, + "2025-06": { + "grupo_edad": [], + "published": {}, + "units": [] + }, + "2025-07": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEAG": 1, + "total|total|LIEAG": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG" + ] + ] + }, + "2025-08": { + "grupo_edad": [ + [ + "5", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|NEGATIVO": 1, + "total|total|NEGATIVO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO" + ] + ] + }, + "2025-09": { + "grupo_edad": [ + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO" + ] + ] + }, + "2025-10": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO" + ] + ] + }, + "2025-11": { + "grupo_edad": [], + "published": {}, + "units": [] + }, + "2025-12": { + "grupo_edad": [], + "published": {}, + "units": [] + }, + "2025-S1": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "2", + "45-54" + ], + [ + "3", + "45-54" + ], + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEBG": 1, + "grupo_edad|45-54|NEGATIVO": 2, + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|LIEBG": 1, + "total|total|NEGATIVO": 2, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO" + ] + ] + }, + "2025-S2": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "4", + "45-54" + ], + [ + "5", + "45-54" + ], + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEAG": 1, + "grupo_edad|45-54|NEGATIVO": 1, + "grupo_edad|45-54|SIN_DATO": 2, + "total|total|LIEAG": 1, + "total|total|NEGATIVO": 1, + "total|total|SIN_DATO": 2 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO" + ] + ] + } + }, + "cacu/IND1": { + "2025-01": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null + ] + ] + }, + "2025-02": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-03": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "2", + 2, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null + ] + ] + }, + "2025-04": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null + ] + ] + }, + "2025-05": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-06": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-07": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null + ] + ] + }, + "2025-08": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "5", + 5, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null + ] + ] + }, + "2025-09": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "6", + 6, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null + ] + ] + }, + "2025-10": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-11": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-12": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-S1": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 4 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.denominator", + "2", + 2, + null + ], + [ + "principal", + "IND1.denominator", + "3", + 3, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null + ] + ] + }, + "2025-S2": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 4 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.denominator", + "5", + 5, + null + ], + [ + "principal", + "IND1.denominator", + "6", + 6, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null + ] + ] + } + } +} \ No newline at end of file diff --git a/tests/fixtures/kit_cacu_timeline.json b/tests/fixtures/kit_cacu_timeline.json new file mode 100644 index 0000000..47a8246 --- /dev/null +++ b/tests/fixtures/kit_cacu_timeline.json @@ -0,0 +1,387 @@ +[ + { + "pac_id": "1", + "fecha": "2025-02-03", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "1" + }, + { + "pac_id": "1", + "fecha": "2025-02-10", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "1" + }, + { + "pac_id": "1", + "fecha": "2025-02-20", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "1" + }, + { + "pac_id": "1", + "fecha": "2025-03-01", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "N871", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "3" + }, + { + "pac_id": "1", + "fecha": "2025-10-02", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "9" + }, + { + "pac_id": "2", + "fecha": "2025-03-05", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "INSATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "2" + }, + { + "pac_id": "2", + "fecha": "2025-09-15", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "C53", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2024-12-01", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "C539", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "2" + }, + { + "pac_id": "3", + "fecha": "2025-01-20", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "INSATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-02-01", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "ASC-US", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-02-01", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "POSITIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-02-01", + "clase": "medicion", + "tipo": "vph_genotipo_16_18", + "codigo": "vph_genotipo_16_18", + "valor_codigo": null, + "valor_numerico": "1.0", + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-04-10", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "2" + }, + { + "pac_id": "3", + "fecha": "2025-04-15", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-04-25", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "LIEBG", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-04-25", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "POSITIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-04-25", + "clase": "medicion", + "tipo": "vph_genotipo_16_18", + "codigo": "vph_genotipo_16_18", + "valor_codigo": null, + "valor_numerico": "0.0", + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-05-01", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": null, + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "1" + }, + { + "pac_id": "3", + "fecha": "2025-05-20", + "clase": "medicion", + "tipo": "biopsia", + "codigo": "cin", + "valor_codigo": "CIN1", + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "1" + }, + { + "pac_id": "4", + "fecha": "2025-05-30", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "5" + }, + { + "pac_id": "4", + "fecha": "2025-06-09", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "5" + }, + { + "pac_id": "4", + "fecha": "2025-06-25", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "3" + }, + { + "pac_id": "4", + "fecha": "2025-07-01", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-11", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "LIEAG", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-11", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "POSITIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-11", + "clase": "medicion", + "tipo": "vph_genotipo_16_18", + "codigo": "vph_genotipo_16_18", + "valor_codigo": null, + "valor_numerico": "1.0", + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-15", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": null, + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "2" + }, + { + "pac_id": "4", + "fecha": "2025-08-01", + "clase": "medicion", + "tipo": "biopsia", + "codigo": "cin", + "valor_codigo": "CIN2", + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "2" + }, + { + "pac_id": "4", + "fecha": "2025-08-10", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "D069", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "1" + }, + { + "pac_id": "5", + "fecha": "2025-08-12", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "7" + }, + { + "pac_id": "5", + "fecha": "2025-08-22", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "7" + }, + { + "pac_id": "5", + "fecha": "2025-08-22", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "7" + }, + { + "pac_id": "5", + "fecha": "2025-09-01", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": null, + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "3" + }, + { + "pac_id": "5", + "fecha": "2025-12-01", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "4" + }, + { + "pac_id": "6", + "fecha": "2025-09-01", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "INSATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "8" + } +] diff --git a/tests/fixtures/kit_oracle_cacu.json b/tests/fixtures/kit_oracle_cacu.json new file mode 100644 index 0000000..d33961c --- /dev/null +++ b/tests/fixtures/kit_oracle_cacu.json @@ -0,0 +1,7735 @@ +{ + "cacu/CACU_CONFIRMACION_CITOLOGIA": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "citologia_alto_grado", + "LIEAG" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_CONFIRMACION_CITOLOGIA.measure-observation", + "4", + 4, + "CIN2", + null + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "citologia_alto_grado", + "LIEAG" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_CONFIRMACION_CITOLOGIA.measure-observation", + "4", + 4, + "CIN2", + null + ] + ] + } + } + }, + "cacu/CACU_DIAS_TOMA_DIAGNOSTICO": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 72.0, + 72.0, + 72.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 72.0 + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 40.0, + 40.0, + 40.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 40.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 161.0, + 161.0, + 161.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "7", + null, + null, + 161.0 + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "9", + null, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 72.0, + 72.0, + 72.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 72.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 2, + 100.5, + 70.25, + 130.75, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "9", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 40.0 + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "7", + null, + null, + 161.0 + ] + ] + } + } + }, + "cacu/CACU_EU13": { + "contrato": "C1", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null, + null + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null, + null + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null, + null + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ], + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ], + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ], + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null, + null + ] + ] + } + } + }, + "cacu/CACU_EU7": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "SIN_DATO", + null + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO", + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO", + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG", + null + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO", + null + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "ASC-H", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG", + null + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO", + null + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO", + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO", + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "ASC-H", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "ASC-H", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 2, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 2, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 2, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ], + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 2, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 2, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 2, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ], + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ], + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO", + null + ] + ] + } + } + }, + "cacu/CACU_EU_TIEMPO_REPORTE": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 12.0, + 12.0, + 12.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "3", + null, + null, + 12.0 + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "1", + null, + null, + 10.0 + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "2", + null, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "4", + null, + null, + 10.0 + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "5", + null, + null, + 10.0 + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "6", + null, + null, + 10.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "7", + null, + null, + 10.0 + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "8", + null, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "9", + null, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 4, + 10.0, + 10.0, + 10.5, + 0, + 1, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "1", + null, + null, + 10.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "3", + null, + null, + 12.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "4", + null, + null, + 10.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "5", + null, + null, + 10.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 2, + 10.0, + 10.0, + 10.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "9", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "6", + null, + null, + 10.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "7", + null, + null, + 10.0 + ] + ] + } + } + }, + "cacu/CACU_RIESGO_BANDA": { + "contrato": "C2", + "periodos": { + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "ALTO", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "BAJO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "INTERMEDIO", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "ALTO", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "BAJO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "INTERMEDIO", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + } + } + }, + "cacu/IND1": { + "contrato": "C1", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null, + null + ] + ] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null, + null + ] + ] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null, + null + ] + ] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null, + null + ] + ] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 4, + 25.0, + 4.55872603, + 69.93581599, + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "IND1.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null, + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 4, + 25.0, + 4.55872603, + 69.93581599, + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "IND1.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null, + null + ] + ] + } + } + } +} \ No newline at end of file diff --git a/tests/fixtures/kit_oracle_cama.json b/tests/fixtures/kit_oracle_cama.json new file mode 100644 index 0000000..ea67468 --- /dev/null +++ b/tests/fixtures/kit_oracle_cama.json @@ -0,0 +1,6242 @@ +{ + "cama/CAMA_BIOPSIAS": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "1", + null, + "BENIGNO", + null + ] + ] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "2", + null, + "CARCINOMA_INVASOR", + null + ] + ] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "1", + null, + "BENIGNO", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "2", + null, + "CARCINOMA_INVASOR", + null + ] + ] + } + } + }, + "cama/CAMA_BIRADS": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "1", + 1, + "B1", + null + ] + ] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "B2", + null + ] + ] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "3", + 3, + "B0", + null + ] + ] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "3", + 3, + "B1", + null + ] + ] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B1", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B2", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B3", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 6, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 7, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 8, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 9, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "5", + 5, + "B1", + null + ] + ] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B1", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B2", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B3", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 6, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 7, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 8, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 9, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "5", + 5, + "SIN_DATO", + null + ] + ] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B1", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B2", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B3", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 6, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 7, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 8, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 9, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "6", + 6, + "B0", + null + ] + ] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "SIN_DATO", + null + ] + ] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "1", + 1, + "B1", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "B2", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "3", + 3, + "B0", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "SIN_DATO", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "5", + 5, + "B1", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "6", + 6, + "B0", + null + ] + ] + } + } + }, + "cama/CAMA_BIRADS456_MASTOGRAFIA": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_MASTOGRAFIA.measure-observation", + "5", + null, + "B4A", + null + ] + ] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_MASTOGRAFIA.measure-observation", + "5", + null, + "B4A", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + } + } + }, + "cama/CAMA_BIRADS456_PACIENTE": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_PACIENTE.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_PACIENTE.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + } + } + }, + "cama/CAMA_CONFIRMACION_BIRADS45": { + "contrato": "C1", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.denominator", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.initial-population", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.numerator", + "5", + null, + null, + null + ] + ] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.denominator", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.initial-population", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.numerator", + "5", + null, + null, + null + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + } + } + }, + "cama/CAMA_DIAS_TOMA_DIAGNOSTICO": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 35.0, + 35.0, + 35.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 35.0 + ] + ] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 19.0, + 19.0, + 19.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 19.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ] + ] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 35.0, + 35.0, + 35.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 35.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 19.0, + 19.0, + 19.0, + 0, + 1, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 19.0 + ] + ] + } + } + }, + "cama/CAMA_EU38A": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "1", + null, + null, + 7.0 + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "2", + null, + null, + 7.0 + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "3", + null, + null, + 7.0 + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "4", + null, + null, + 7.0 + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "5", + null, + null, + 7.0 + ] + ] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "6", + null, + null, + 7.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "7", + null, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "8", + null, + null, + 7.0 + ] + ] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "9", + null, + null, + null + ] + ] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 5, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "1", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "2", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "3", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "4", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "5", + null, + null, + 7.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 2, + 7.0, + 7.0, + 7.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "9", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "6", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "8", + null, + null, + 7.0 + ] + ] + } + } + } +} \ No newline at end of file diff --git a/tests/test_cama_measures.py b/tests/test_cama_measures.py new file mode 100644 index 0000000..0f1b7f4 --- /dev/null +++ b/tests/test_cama_measures.py @@ -0,0 +1,87 @@ +"""What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit +computed on the same fixture data: every measure, every period, its units and its numbers. + +Fixtures: `base`, the CaMa fixture database through the cycle up to `modelos` (dbt's views); `manifest`, dbt's +`manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published +numbers for each measure and period (counts only; suppression off). +""" + +import json +import os +from dataclasses import replace +from pathlib import Path + +import pytest +from sqlalchemy import text + +from conftest import base_de +from webapi.compositions import answer_composition, composition_definitions +from webapi.durations import answer_duration, duration_definitions +from webapi.metrics import Question, answer, measure_definitions + +ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8")) +UNTIL_MODELS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture +def base(tmp_path, sin_supresion, manifest): + base = base_de("cama", tmp_path) + base.correr(*UNTIL_MODELS, parametros=sin_supresion, permitir_sin_definir=True) + yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.motor.dispose() + + +def repositories(base) -> dict: + d = base.dominio + return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, + "history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True} + + +def units(base, report_id: int) -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad " + "where report_id = :r"), {"r": report_id}).all())) + + +def published_rows(expected) -> list[dict]: + return [dict(zip(expected["published_columns"], row)) for row in expected["published"]] + + +@pytest.mark.parametrize("url", sorted(ORACLE)) +def test_each_measure_is_the_kit_s_in_every_period(base, manifest, url): + """Pins down every CaMa measure in every period: the kit's units (with each one's category or days) and its + numbers: a composition's count per category, a proportion's numerator and denominator, a duration's n, median, + quartiles and excluded where the kit didn't suppress them. Fails if an event model, a semantic definition or the + construct it uses drifts from what the kit meant.""" + for kind, of in (("proportion", measure_definitions), ("composition", composition_definitions), + ("duration", duration_definitions)): + if url in of(manifest): + definition = of(manifest)[url] + break + for period_id, expected in ORACLE[url]["periodos"].items(): + question = Question(url, period_id) + rows = published_rows(expected) + if kind == "composition": + result = answer_composition("cama", definition, question, **repositories(base)) + assert {k: v for k, v in result.categories.items() if v} == { + r["categoria"]: r["n"] for r in rows if r["estrato_id"] == "total" and r["n"]}, period_id + elif kind == "proportion": + result = answer("cama", definition, question, **repositories(base)) + (total,) = [r for r in rows if r["estrato_id"] == "total"] or [{"numerador": 0, "denominador": 0}] + assert (result.numerator, result.denominator) == (total["numerador"] or 0, total["denominador"] or 0), period_id + else: + result = answer_duration("cama", definition, question, **repositories(base)) + (total,) = [r for r in rows if r["estrato_id"] == "total"] + if not total["suprimido"]: + assert (result.n, result.median, result.q1, result.q3, result.excluded) == ( + total["n"], total["mediana"], total["q1"], total["q3"], total["n_excluido"]), period_id + assert units(base, result.report_id) == expected["units"], period_id diff --git a/tests/test_imports_endpoints.py b/tests/test_imports_endpoints.py index 9a18a0d..1ab9b57 100644 --- a/tests/test_imports_endpoints.py +++ b/tests/test_imports_endpoints.py @@ -183,6 +183,19 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client): assert paciente["pac_sexo"] == "M" +def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client): + """The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation. + + Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500. + """ + source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes") + response = client.post("/imports/commit", json={"sources": [source]}) + assert response.status_code == 200 + body = response.get_json() + assert body["results"][0]["created"] == 1 + assert body["indicadores_en_recalculo"] is False + + @pytest.fixture def sql_source_db(tmp_path): db_path = tmp_path / "external_source.db" diff --git a/tests/test_indicadores_cacu.py b/tests/test_indicadores_cacu.py deleted file mode 100644 index c2011b0..0000000 --- a/tests/test_indicadores_cacu.py +++ /dev/null @@ -1,338 +0,0 @@ -"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit.""" - -import pytest -from conftest import MESES, SEMESTRES, cliente_de -from indicadores_kit.registry.measures import RAIZ, measures_de -from indicadores_kit.serving.figuras import figuras_de - -PROYECTO = "cacu" -INDICADOR = "ind1" -DEFINICIONES = measures_de(PROYECTO) -(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR]) - - -@pytest.fixture(scope="module") -def client(tmp_path_factory): - yield from cliente_de(PROYECTO, tmp_path_factory) - - -def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}") - - -def _x(respuesta) -> list[str]: - return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]] - - -def test_listar_indicadores(client): - response = client.get(f"/{PROYECTO}/indicadores") - - assert response.status_code == 200 - lista = response.get_json() - visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto] - assert [fila["id"] for fila in lista] == sorted(visibles) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert fila["titulo"] == medida.title - assert fila["contrato"] == medida.extension.contrato - assert fila["figuras"] == figuras_de(medida) - assert fila["tipos_periodo"] == ["semestre", "mes"] - - -def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client): - """Los que su TOML marca `oculto` (p. ej. cacu_riesgo_banda hasta MD-Q5) no salen en el catálogo, pero responden.""" - ocultos = {nombre for nombre, medida in DEFINICIONES.items() if medida.extension.publicacion.oculto} - - assert ocultos - ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()} - - assert ids == set(DEFINICIONES) - ocultos - for indicador in ocultos: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200 - - -def test_un_indicador_retirado_da_404(client): - """T-22a (ADR-MD-009): los retirados (`/retirados/` del kit) ni se calculan ni se sirven.""" - retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")] - - assert retirados - for indicador in retirados: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404 - - -def test_figura_con_semestres(client): - response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro") - - assert response.status_code == 200 - assert response.mimetype == "application/json" - assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title - assert set(_x(response)) == set(SEMESTRES) - - -def test_figura_sin_periodos_usa_los_semestres_con_reporte(client): - response = _figura(client) - - assert response.status_code == 200 - assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran - - -def test_figura_con_meses(client): - response = _figura(client, query=f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert set(_x(response)) == set(MESES) - - -@pytest.mark.parametrize( - "query", - [ - "?tema=rojo", - "?periodos=2025-1", - "?periodos=2025-S3", - "?periodos=2025-13x", - "?periodos=2025-S1,", - "?periodos=abc", - "?periodos=2025-T1", # un tipo que el indicador no publica - "?periodos=2025-S1,2025-03", # tipos mezclados - ], -) -def test_figura_con_parametros_mal_formados_da_400(client, query): - response = _figura(client, query=query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "figura", "query"), - [ - ("CACU_NO_EXISTE", FIGURA, ""), - (INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato - (INDICADOR, "fig_no_existe", ""), - (INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte - (INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"), - (INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte - ], -) -def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query): - response = _figura(client, indicador, figura, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch): - from webapi import indicadores - - def falla(*args, **kwargs): - raise KeyError("columna") - - monkeypatch.setattr(indicadores, "figura_json", falla) - with pytest.raises(KeyError): - _figura(client, query="?periodos=2025-S1") - - -# --- Todos los indicadores del proyecto --- - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_figura_de_cada_indicador(client, indicador): - for figura in figuras_de(DEFINICIONES[indicador]): - response = _figura(client, indicador, figura) - - assert response.status_code == 200, (indicador, figura) - assert set(response.get_json()) >= {"data", "layout"} - - -def test_una_distribucion_sin_periodos_es_la_del_semestre_mas_reciente(client): - assert figuras_de(DEFINICIONES["cacu_eu7"]) == ["fig_c2_barras", "fig_c2_donas"] - - por_defecto = _figura(client, "cacu_eu7", "fig_c2_donas") - del_ultimo = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={SEMESTRES[-1]}") - de_todos = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={','.join(SEMESTRES)}") - - assert por_defecto.get_json() == del_ultimo.get_json() - assert len(de_todos.get_json()["data"]) == len(SEMESTRES) * len(por_defecto.get_json()["data"]) - - -# --- El catálogo, los periodos, los datos y los metadatos --- - -CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"} - - -def _ruta(client, indicador: str, ruta: str, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}") - - -def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client): - lista = client.get(f"/{PROYECTO}/indicadores").get_json() - - assert all(set(fila) == CATALOGO for fila in lista) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation) - assert fila["estratos"] == medida.extension.estratos - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador): - medida = DEFINICIONES[indicador] - - periodos = _ruta(client, indicador, "periodos") - datos = _ruta(client, indicador, "datos") - metadatos = _ruta(client, indicador, "metadatos") - - assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200) - assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos)) - assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos)) - de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"] - assert de_semestre == SEMESTRES - cuerpo = datos.get_json() - assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES) - assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"]) - assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"]) - assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura - assert metadatos.get_json()["tipo_calculo"] == medida.scoring - - -def test_datos_con_meses(client): - response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert response.get_json()["tipo_periodo"] == "mes" - assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES - - -def test_los_datos_dicen_de_que_reporte_salen(client): - cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json() - periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"] - - (reporte,) = cuerpo["reportes"] - assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1") - assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01") - assert cuerpo["version"] == DEFINICIONES[INDICADOR].version - - -@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"]) -def test_datos_con_parametros_mal_formados_da_400(client, query): - response = _ruta(client, INDICADOR, "datos", query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "ruta", "query"), - [ - ("NO_EXISTE", "datos", ""), - ("NO_EXISTE", "periodos", ""), - ("NO_EXISTE", "metadatos", ""), - (INDICADOR, "datos", "?periodos=2030-S1"), - ], -) -def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query): - response = _ruta(client, indicador, ruta, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -# --- Los filtros (T-19f) --- - - -@pytest.mark.parametrize("query", ["?filtro=grupo_edad", "?filtro=:25-34", "?filtro=grupo_edad:25-34,grupo_edad:35-44", - "?filtro=grupo_edad:25-34", "?filtro=ronda:1"]) -def test_un_filtro_mal_escrito_o_no_declarado_da_400(client, query): - """IND1 no declara filtros (EU7 y EU13 sí, desde T-24f): todo `?filtro=` da 400, en datos y en figuras.""" - for response in (_ruta(client, INDICADOR, "datos", query), _figura(client, query=query)): - assert response.status_code == 400 - assert "error" in response.get_json() - - -def test_sin_filtro_los_datos_no_traen_la_llave_filtros(client): - assert "filtros" not in _ruta(client, INDICADOR, "datos").get_json() - - -def test_los_filtros_se_leen_como_estrato_y_valor(): - from webapi.indicadores import filtros_pedidos - - assert filtros_pedidos(None) == {} and filtros_pedidos("") == {} - assert filtros_pedidos("grupo_edad:25-34,ronda:1") == {"grupo_edad": "25-34", "ronda": "1"} - with pytest.raises(ValueError, match="mal escrito"): - filtros_pedidos("grupo_edad") - - -# --- La ficha técnica (T-24e) --- - -# Las llaves de /metadatos antes de T-24e: no se quita ni se renombra ninguna. -METADATOS = { - "id", "titulo", "version", "estado", "contrato", "tipo_calculo", "unidad", "sentido", "descripcion", - "tipos_periodo", "figuras", "estratos", "grupos", "categorias", "grupos_de_categoria", "estandares", - "ficha", "parametros", -} # fmt: skip - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_los_metadatos_traen_referencias_poblaciones_y_figuras_sin_perder_llaves(client, indicador): - cuerpo = _ruta(client, indicador, "metadatos").get_json() - - assert set(cuerpo) == METADATOS | {"referencias", "poblaciones", "figuras_detalle"} - assert cuerpo["poblaciones"] - assert [d["figura"] for d in cuerpo["figuras_detalle"]] == cuerpo["figuras"] - if not DEFINICIONES[indicador].extension.publicacion.oculto: - assert all(d["descripcion"] and d["como_leer"] for d in cuerpo["figuras_detalle"]) - assert all(set(p) == {"grupo", "codigo", "descripcion"} and p["descripcion"] for p in cuerpo["poblaciones"]) - - -def test_la_ficha_de_eu7_cita_el_lineamiento_europeo(client): - cuerpo = _ruta(client, "cacu_eu7", "metadatos").get_json() - - assert cuerpo["referencias"] == [{ - "tipo": "citation", - "etiqueta": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)", - "ref": "indicador 7", - }] # fmt: skip - assert cuerpo["poblaciones"] == [{ - "grupo": "total", - "codigo": "measure-observation", - "descripcion": DEFINICIONES["cacu_eu7"].group[0].population[0].description, - }] # fmt: skip - - -# --- EU7 por estrato (T-24f): la dona y sus barras --- - - -def test_eu7_por_estatus_da_categoria_por_valor_con_etiquetas_y_totales(client): - cuerpo = _ruta(client, "cacu_eu7", "datos", "?estrato=estatus_seguimiento").get_json() - - assert cuerpo["estrato"] == "estatus_seguimiento" and cuerpo["valores_estrato"] - assert set(cuerpo["etiquetas_estrato"]) == set(cuerpo["valores_estrato"]) - assert {f["estrato"] for f in cuerpo["filas"]} == set(cuerpo["valores_estrato"]) - assert {t["estrato"] for t in cuerpo["totales_estrato"]} == set(cuerpo["valores_estrato"]) - - -def test_eu7_se_puede_filtrar_por_grupo_de_edad(client): - valor = _ruta(client, "cacu_eu7", "datos", "?estrato=grupo_edad").get_json()["valores_estrato"][0] - response = _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}") - - assert response.status_code == 200 - assert response.get_json()["filtros"] == {"grupo_edad": valor} - - -def test_el_catalogo_publica_los_filtros_con_sus_valores(client): - """T-24f (contrato de T-24a §3): con ellos se arma `?filtro=estrato:valor`.""" - por_id = {fila["id"]: fila for fila in client.get(f"/{PROYECTO}/indicadores").get_json()} - - assert por_id[INDICADOR]["filtros"] == [] # IND1 no declara filtros - (edad, estatus) = por_id["cacu_eu7"]["filtros"] - assert (edad["estrato"], edad["etiqueta"]) == ("grupo_edad", "Grupo de edad") - assert [v["valor"] for v in edad["valores"]][-1] == "sin_dato" - assert (estatus["estrato"], estatus["etiqueta"]) == ("estatus_seguimiento", "Estatus de seguimiento") - assert estatus["valores"] == [ - {"valor": "PRE_COLPOSCOPIA", "etiqueta": "Pre colposcopia"}, - {"valor": "POST_COLPOSCOPIA", "etiqueta": "Post colposcopia"}, - {"valor": "POST_TRATAMIENTO", "etiqueta": "Post tratamiento"}, - {"valor": "INFO_INSUFICIENTE", "etiqueta": "Información insuficiente"}, - ] - valor = edad["valores"][0]["valor"] - assert _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}").status_code == 200 diff --git a/tests/test_indicadores_cama.py b/tests/test_indicadores_cama.py deleted file mode 100644 index 0428e12..0000000 --- a/tests/test_indicadores_cama.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit.""" - -import pytest -from conftest import MESES, SEMESTRES, cliente_de -from indicadores_kit.registry.measures import RAIZ, measures_de -from indicadores_kit.serving.figuras import figuras_de - -PROYECTO = "cama" -INDICADOR = "cama_confirmacion_birads45" -DEFINICIONES = measures_de(PROYECTO) -(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR]) - - -@pytest.fixture(scope="module") -def client(tmp_path_factory): - yield from cliente_de(PROYECTO, tmp_path_factory) - - -def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}") - - -def _x(respuesta) -> list[str]: - return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]] - - -def test_listar_indicadores(client): - response = client.get(f"/{PROYECTO}/indicadores") - - assert response.status_code == 200 - lista = response.get_json() - visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto] - assert [fila["id"] for fila in lista] == sorted(visibles) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert fila["titulo"] == medida.title - assert fila["contrato"] == medida.extension.contrato - assert fila["figuras"] == figuras_de(medida) - assert fila["tipos_periodo"] == ["semestre", "mes"] - - -def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client): - """Provisional (oct 2026): cama_birads no se muestra. - - cama_birads lo sustituyen cama_birads_456_paciente y cama_birads_456_mastografia. - cama_confirmacion_birads45 vuelve a mostrarse: su tarjeta destacada y su - gráfica de tendencia (usuario, 2026-10-16). - """ - ocultos = {"cama_birads"} # cama_riesgo_banda es propuesta desde T-21h: no se calcula ni se sirve - ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()} - - assert ids == set(DEFINICIONES) - ocultos - for indicador in ocultos: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200 - - -def test_un_indicador_retirado_da_404(client): - """T-22a (ADR-MD-009): los retirados (`/retirados/` del kit) ni se calculan ni se sirven.""" - retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")] - - assert retirados - for indicador in retirados: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404 - - -def test_figura_con_semestres(client): - response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro") - - assert response.status_code == 200 - assert response.mimetype == "application/json" - assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title - assert set(_x(response)) == set(SEMESTRES) - - -def test_figura_sin_periodos_usa_los_semestres_con_reporte(client): - response = _figura(client) - - assert response.status_code == 200 - assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran - - -def test_figura_con_meses(client): - response = _figura(client, query=f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert set(_x(response)) == set(MESES) - - -@pytest.mark.parametrize( - "query", - [ - "?tema=rojo", - "?periodos=2025-1", - "?periodos=2025-S3", - "?periodos=2025-13x", - "?periodos=2025-S1,", - "?periodos=abc", - "?periodos=2025-T1", # un tipo que el indicador no publica - "?periodos=2025-S1,2025-03", # tipos mezclados - ], -) -def test_figura_con_parametros_mal_formados_da_400(client, query): - response = _figura(client, query=query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "figura", "query"), - [ - ("CAMA_NO_EXISTE", FIGURA, ""), - (INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato - (INDICADOR, "fig_no_existe", ""), - (INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte - (INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"), - (INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte - ], -) -def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query): - response = _figura(client, indicador, figura, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch): - from webapi import indicadores - - def falla(*args, **kwargs): - raise KeyError("columna") - - monkeypatch.setattr(indicadores, "figura_json", falla) - with pytest.raises(KeyError): - _figura(client, query="?periodos=2025-S1") - - -# --- Todos los indicadores del proyecto --- - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_figura_de_cada_indicador(client, indicador): - for figura in figuras_de(DEFINICIONES[indicador]): - response = _figura(client, indicador, figura) - - assert response.status_code == 200, (indicador, figura) - assert set(response.get_json()) >= {"data", "layout"} - - -# --- El catálogo, los periodos, los datos y los metadatos --- - -CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"} - - -def _ruta(client, indicador: str, ruta: str, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}") - - -def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client): - lista = client.get(f"/{PROYECTO}/indicadores").get_json() - - assert all(set(fila) == CATALOGO for fila in lista) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation) - assert fila["estratos"] == medida.extension.estratos - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador): - medida = DEFINICIONES[indicador] - - periodos = _ruta(client, indicador, "periodos") - datos = _ruta(client, indicador, "datos") - metadatos = _ruta(client, indicador, "metadatos") - - assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200) - assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos)) - assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos)) - de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"] - assert de_semestre == SEMESTRES - cuerpo = datos.get_json() - assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES) - assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"]) - assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"]) - assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura - assert metadatos.get_json()["tipo_calculo"] == medida.scoring - - -def test_datos_con_meses(client): - response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert response.get_json()["tipo_periodo"] == "mes" - assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES - - -def test_los_datos_dicen_de_que_reporte_salen(client): - cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json() - periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"] - - (reporte,) = cuerpo["reportes"] - assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1") - assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01") - assert cuerpo["version"] == DEFINICIONES[INDICADOR].version - - -@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"]) -def test_datos_con_parametros_mal_formados_da_400(client, query): - response = _ruta(client, INDICADOR, "datos", query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "ruta", "query"), - [ - ("NO_EXISTE", "datos", ""), - ("NO_EXISTE", "periodos", ""), - ("NO_EXISTE", "metadatos", ""), - (INDICADOR, "datos", "?periodos=2030-S1"), - ], -) -def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query): - response = _ruta(client, indicador, ruta, query) - - assert response.status_code == 404 - assert "error" in response.get_json() diff --git a/tests/test_indicadores_tea.py b/tests/test_indicadores_tea.py deleted file mode 100644 index 577c102..0000000 --- a/tests/test_indicadores_tea.py +++ /dev/null @@ -1,169 +0,0 @@ -import pytest -from indicadores_kit.registry.measures import RAIZ, measures_de -from indicadores_kit.serving.figuras import figuras_de -from indicadores_kit.tea import fixtures - -DEFINICIONES = measures_de("tea") -PERIODOS = ",".join(fixtures.PERIODOS) - - -@pytest.fixture(scope="module") -def client(tmp_path_factory): - """Una base de TEA temporal, con los 20 indicadores calculados (16 en el catálogo), por `TEA_DATABASE_URL`.""" - # Dentro de la fixture: la configuración de Persistance se lee al importarla, - # y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes. - from persistance.db import get_tea_engine - from persistance.settings import settings - - ruta = tmp_path_factory.mktemp("tea") / "tea.db" - with pytest.MonkeyPatch.context() as mp: - mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}") - get_tea_engine.cache_clear() - try: - fixtures.base_de_prueba(get_tea_engine()) - - from webapi import create_app - - app = create_app() - app.config.update(TESTING=True) - with app.test_client() as cliente: - yield cliente - finally: - get_tea_engine().dispose() - get_tea_engine.cache_clear() - - -def _figura(client, indicador: str, figura: str, query: str = ""): - return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}") - - -def test_listar_indicadores(client): - response = client.get("/tea/indicadores") - assert response.status_code == 200 - - lista = response.get_json() - visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto] - assert [fila["id"] for fila in lista] == sorted(visibles) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert fila["titulo"] == medida.title - assert fila["contrato"] == medida.extension.contrato - assert fila["figuras"] == figuras_de(medida) - - -def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client): - """Provisional (oct 2026): solo se muestran M21, M22 y los tres destacados (M23 a M25).""" - visibles = { - "M21_diagnosticados_con_eeg", - "M22_diagnosticados_sin_eeg", - "M23_pacientes_evaluados", - "M24_confirmacion_diagnostico", - "M25_dias_mchat_diagnostico", - } - ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()} - - assert ids == visibles - for oculto in sorted(set(DEFINICIONES) - visibles): - assert client.get(f"/tea/indicadores/{oculto}/metadatos").status_code == 200 - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_figura_de_cada_indicador(client, indicador): - for figura in figuras_de(DEFINICIONES[indicador]): - response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro") - - assert response.status_code == 200, figura - assert response.mimetype == "application/json" - assert "data" in response.get_json() - - -def test_figura_sin_periodos_usa_todos_los_reportes(client): - (figura,) = figuras_de(DEFINICIONES["M21_diagnosticados_con_eeg"]) - - response = _figura(client, "M21_diagnosticados_con_eeg", figura) - - assert response.status_code == 200 - assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["M21_diagnosticados_con_eeg"].title - - -@pytest.mark.parametrize( - "query", - [ - "?tema=rojo", - "?periodos=2025-1", - "?periodos=2025-S1,", - "?periodos=abc", - "?periodos=,", - ], -) -def test_figura_con_parametros_mal_formados_da_400(client, query): - response = _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "figura", "query"), - [ - ("K99_no_existe", "fig_c1_grupos", ""), - ("M21_diagnosticados_con_eeg", "fig_c3r_caja", ""), # figura de otro contrato - ("M21_diagnosticados_con_eeg", "fig_no_existe", ""), - ("M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte - ("M21_diagnosticados_con_eeg", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"), - ], -) -def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query): - response = _figura(client, indicador, figura, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch): - from webapi import indicadores - - def falla(*args, **kwargs): - raise KeyError("columna") - - monkeypatch.setattr(indicadores, "figura_json", falla) - with pytest.raises(KeyError): - _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2025-S1") - - -# --- Los periodos, los datos y los metadatos --- - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador): - medida = DEFINICIONES[indicador] - - periodos = client.get(f"/tea/indicadores/{indicador}/periodos") - datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}") - metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos") - - assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200) - assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS) - cuerpo = datos.get_json() - assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato) - assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS) - assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"]) - assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura - assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo - - -def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client): - response = client.get(f"/tea/indicadores/M21_diagnosticados_con_eeg/datos?periodos={PERIODOS}") - - grupos = list(response.get_json()["grupos"]) - assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético - assert grupos[-1] == "TOTAL" - - -def test_un_indicador_retirado_da_404(client): - """T-22a (ADR-MD-009): los retirados (`tea/retirados/` del kit) ni se calculan ni se sirven.""" - retirados = [ruta.stem for ruta in (RAIZ / "tea" / "retirados").glob("*.toml")] - - assert len(retirados) == 18 - for indicador in retirados: - assert client.get(f"/tea/indicadores/{indicador}/metadatos").status_code == 404 diff --git a/tests/test_kpis_route.py b/tests/test_kpis_route.py new file mode 100644 index 0000000..5b705f5 --- /dev/null +++ b/tests/test_kpis_route.py @@ -0,0 +1,135 @@ +"""What this module covers: `webapi.kpis`, the route that answers a measure's periods on request as a FHIR `Bundle` +of `MeasureReport`s. + +Fixtures: `base`, `manifest` and `kit` from `test_metrics_on_request` (the CaCu fixture database through the cycle, +dbt's manifest, the kit's snapshot; skipped without `DBT_MANIFEST`); `client`, a Flask app with only this domain's KPI +blueprint. +""" + +import json +import os +from pathlib import Path + +import pytest +from flask import Flask + +from test_metrics_on_request import EU7, EU13, IND1, base, kit, manifest, reports # noqa: F401 +from webapi.kpis import kpis_blueprint + + +@pytest.fixture +def client(base, manifest): # noqa: F811 + app = Flask(__name__) + app.register_blueprint(kpis_blueprint("cacu", base.dominio, manifest), url_prefix="/cacu") + return app.test_client() + + +def counts(resource: dict) -> dict[str, int]: + (group,) = resource["group"] + return {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} + + +def history_entry(resource: dict) -> int: + (entry,) = [e for e in resource["extension"] if e["url"].endswith("/reporte-id")] + return entry["valueInteger"] + + +def test_a_measure_s_periods_come_as_a_bundle_of_measure_reports(base, client, kit): # noqa: F811 + """Pins down the contract: one `MeasureReport` per period asked, in order, with the kit's numbers. Fails if the + route stops answering each period, changes the shape, or the counts drift from what the cycle published.""" + response = client.get("/cacu/indicadores/IND1?periodos=2025-S1,2025-S2") + bundle = response.get_json(force=True) + + assert response.status_code == 200 and response.mimetype == "application/fhir+json" + assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 2) + for entry, period_id in zip(bundle["entry"], ("2025-S1", "2025-S2")): + report = entry["resource"] + assert report["resourceType"] == "MeasureReport" and report["measure"] == "cacu/IND1|0.3.2" + numerator, denominator = kit[IND1][period_id]["published"]["total|total"] + assert counts(report) == {"initial-population": denominator, "denominator": denominator, + "numerator": numerator} + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_ind1.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") + + +def test_without_a_knowledge_cutoff_the_last_load_makes_the_answer_stable(base, client): # noqa: F811 + """Pins down: by default the knowledge cut-off is the last load's start, so asking again before the next load + reads the stored answer. Fails if the default becomes "now", which would store a new answer per request.""" + first = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True) + before = reports(base) + second = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True) + + assert history_entry(second["entry"][0]["resource"]) == history_entry(first["entry"][0]["resource"]) + assert reports(base) == before + + +def test_a_measure_with_strata_brings_its_stratifier(client): + """Pins down: EU13's reports carry its strata, by age and by follow-up status. Fails if the route drops one.""" + bundle = client.get("/cacu/indicadores/CACU_EU13?periodos=2025-S1").get_json(force=True) + stratifiers = bundle["entry"][0]["resource"]["group"][0]["stratifier"] + + assert [s["code"][0]["text"] for s in stratifiers] == ["grupo_edad", "estatus_seguimiento"] + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu13.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") + + +def test_the_list_names_what_is_answered_on_request(client): + """Pins down: `/indicadores` lists the measures the manifest defines for the domain. Fails if one is missing.""" + listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()} + + assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE", + "CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA", + "CACU_RIESGO_BANDA"} + + +def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client): + """Pins down the route for durations: the samples measurable and measured as populations, the median as the + score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day + by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its + contract changes.""" + bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True) + (entry,) = bundle["entry"] + report = entry["resource"] + (group,) = report["group"] + assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3" + assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == { + "initial-population": 4, "measure-observation": 2} + assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d" + assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75] + assert any(e["url"].endswith("corte-evento") for e in report["extension"]) + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") + + +@pytest.mark.parametrize(("path", "status"), [ + ("/cacu/indicadores/NOPE?periodos=2025-S1", 404), + ("/cacu/indicadores/IND1", 400), + ("/cacu/indicadores/IND1?periodos=2025-S1&corte_evento=30-06-2025", 400), + ("/cacu/indicadores/IND1?periodos=2025-S1&corte_conocimiento=ayer", 400), + ("/cacu/indicadores/IND1?periodos=2031-S1", 404), +]) +def test_a_bad_question_gets_a_clear_error(client, path, status): + """Pins down the errors: an unknown measure or period is 404, a missing or misspelled parameter 400. Fails if one + of them becomes a 500.""" + response = client.get(path) + + assert response.status_code == status and "error" in response.get_json() + + +def test_a_composition_comes_with_its_categories(client, kit): + """Pins down: EU7's reports carry the categories as a `resultado` stratifier, with the kit's counts, under the + route's default knowledge cut-off (the last load). Fails if the route stops telling compositions from + proportions, or a result's knowledge date stops being compared as the type it's stored in.""" + bundle = client.get("/cacu/indicadores/CACU_EU7?periodos=2025-S1,2025-S2").get_json(force=True) + stratifiers = [e["resource"]["group"][0]["stratifier"][0] for e in bundle["entry"]] + + assert [s["code"] for s in stratifiers] == [[{"text": "resultado"}]] * 2 + for stratifier, period_id in zip(stratifiers, ("2025-S1", "2025-S2")): + expected = {k.split("|")[2]: n for k, n in kit[EU7][period_id]["published"].items() if k.startswith("total|")} + assert {s["value"]["text"]: s["population"][0]["count"] for s in stratifier["stratum"]} == expected + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu7.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") diff --git a/tests/test_measure_cases.py b/tests/test_measure_cases.py new file mode 100644 index 0000000..a0ffa77 --- /dev/null +++ b/tests/test_measure_cases.py @@ -0,0 +1,100 @@ +"""What this module covers: compositions answered from dbt's semantic layer on the hand-written cases their rules were +written with, one database per case: CACU_CONFIRMACION_CITOLOGIA (`fixtures/casos_confirmacion_citologia.toml`: the +last valid sample decides, the most severe biopsy of that sample by the cut-off is the category, a biopsy of another +sample doesn't count) and CACU_RIESGO_BANDA (`fixtures/casos_riesgo_banda.toml`: the current batch of estimates, the +latest version of each, the bands by the rules' cut points). + +Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each +`pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views +created by the cycle (`catalogos` … `modelos`; needs `DBT_MANIFEST`). +""" + +import json +import os +import tomllib +from dataclasses import replace +from datetime import date +from pathlib import Path + +import pytest +from sqlalchemy import text + +from conftest import base_de +from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, EvaluacionRiesgo, EvaluacionRiesgoLote +from core.cacu.models import BiopsiaCervical, CitologiaCervical, Paciente +from webapi.compositions import answer_composition, composition_definitions +from webapi.metrics import Question + +FIXTURES = Path(__file__).parent / "fixtures" +FILES = ("casos_confirmacion_citologia.toml", "casos_riesgo_banda.toml") +TABLES = {m.__tablename__: m for m in (CitologiaCervical, BiopsiaCervical, CohorteArmado, CohorteMiembro, + EvaluacionRiesgoLote, EvaluacionRiesgo)} +STAGING = ("citologiacervical", "biopsiacervical") +# Rows go in by their parents first. +ORDER = ("citologiacervical", "biopsiacervical", "cohorte_armado", "cohorte_miembro", "evaluacion_riesgo_lote", + "evaluacion_riesgo") + + +def cases(): + for name in FILES: + document = tomllib.loads((FIXTURES / name).read_text(encoding="utf-8")) + templates = document.get("plantillas", {}) + for case in document["caso"]: + rows = [row for t in case.get("incluye", ()) for row in templates[t]] + case["filas"] + yield pytest.param(document["measure"], {**case, "filas": rows}, id=case["nombre"]) + + +def rows_of(case: dict): + """What the case's rows insert: a patient for each `pac_id`, then every row by its parents first.""" + def insert(session): + for pac_id in sorted({row["pac_id"] for row in case["filas"] if "pac_id" in row}): + session.add(Paciente(pac_id=pac_id, pac_id_hospital=f"H-{pac_id:03d}", pac_sexo="Femenino", + pac_fecha_nacimiento=date(1980, 1, 1))) + session.flush() + for row in sorted(case["filas"], key=lambda r: ORDER.index(r["tabla"])): + data = {k: v for k, v in row.items() if k != "tabla"} + if row["tabla"] in STAGING: + data["pac_id_hospital"] = f"H-{row['pac_id']:03d}" + session.add(TABLES[row["tabla"]](**data)) + session.flush() + session.commit() + return insert + + +@pytest.mark.parametrize(("url", "case"), list(cases())) +def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case): + """Pins down each hand-written case: the count in each category it names (zero included), the patients in the + categories it lists and their stratum values, at its cut-off and with its rules. Fails if the measure stops + meaning what the case says; the case's name says which rule.""" + manifest = os.environ.get("DBT_MANIFEST") + if not manifest: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + base = base_de("cacu", tmp_path, rows_of(case)) + base.correr("catalogos", "cargar", "registro", "definiciones", "modelos", parametros=sin_supresion, + permitir_sin_definir=True) + with base.motor.begin() as connection: + for key, value in case.get("parametros", {}).items(): + connection.execute(text("update def_parametro set valor = :v where clave = :k"), + {"v": json.dumps(value), "k": key}) + definition = composition_definitions(Path(manifest))[url] + d = base.dominio + for period_id in sorted({*case.get("espera", {}), *case.get("unidades", {}), *case.get("estratos", {})}): + result = answer_composition( + "cacu", definition, Question(url, period_id, case.get("corte")), parameters=d.def_parametro_repository, + periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository, + allow_undecided=True) + for category, n in case.get("espera", {}).get(period_id, {}).items(): + assert result.categories.get(category.removeprefix("cat:"), 0) == n, (period_id, category) + with base.motor.connect() as connection: + units = connection.execute(text( + "select valor_id, unidad_id from measure_report_unidad where report_id = :r"), + {"r": result.report_id}).all() + strata = connection.execute(text( + "select estrato_id, unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r"), + {"r": result.report_id}).all() + for category, expected in case.get("unidades", {}).get(period_id, {}).items(): + assert sorted(u for v, u in units if v == category.removeprefix("cat:")) == sorted(map(str, expected)), ( + period_id, category) + for stratum, expected in case.get("estratos", {}).get(period_id, {}).items(): + assert {u: v for s, u, v in strata if s == stratum} == expected, (period_id, stratum) + base.motor.dispose() diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py new file mode 100644 index 0000000..c93f30d --- /dev/null +++ b/tests/test_metrics_on_request.py @@ -0,0 +1,461 @@ +"""What this module covers: `webapi.metrics` and `webapi.compositions`, CaCu's measures answered on request from +dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which +keeps each answer under its key. + +Fixtures: `base`, the CaCu fixture database through the cycle up to `modelos` (which creates dbt's event models); +`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13 +and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against. +""" + +import json +import os +import time +from dataclasses import replace +from datetime import date, datetime, timezone +from pathlib import Path + +import pytest +from sqlalchemy import text +from sqlmodel import Session, select + +from conftest import base_de +from core.cacu.models import BiopsiaCervical, CitologiaCervical +from webapi.compositions import answer_composition, composition_definitions, composition_report +from webapi.metrics import Question, answer, measure_definitions, measure_report +from webapi.orquestacion import correr + +IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7" +STATUS = "estatus_seguimiento" +HASTA_MODELOS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") +PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"] +SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json" + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture +def base(tmp_path, sin_supresion, manifest): + base = base_de("cacu", tmp_path) + base.correr(*HASTA_MODELOS, parametros=sin_supresion, permitir_sin_definir=True) + yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.motor.dispose() + + +@pytest.fixture +def kit(): + return json.loads(SNAPSHOT.read_text(encoding="utf-8")) + + +@pytest.fixture +def definition(manifest): + return measure_definitions(manifest)[IND1] + + +@pytest.fixture +def eu13(manifest): + return measure_definitions(manifest)[EU13] + + +@pytest.fixture +def eu7(manifest): + return composition_definitions(manifest)[EU7] + + +def repositories(base) -> dict: + d = base.dominio + return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, + "history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True} + + +def ask(base, definition, period_id, *, event_cutoff=None, knowledge_cutoff=None): + question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff) + if definition.url == EU7: + return answer_composition("cacu", definition, question, **repositories(base)) + return answer("cacu", definition, question, **repositories(base)) + + +def units(base, report_id: int) -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select grupo, resultado_id, unidad_id, pac_id, valor_id from measure_report_unidad where report_id = :r"), + {"r": report_id}).all())) + + +def strata_rows(base, report_id: int, stratum: str = "grupo_edad") -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r " + "and estrato_id = :e"), {"r": report_id, "e": stratum}).all())) + + +def proportion_cells(result) -> dict: + """An answer as the snapshot keeps what `v_c1` published: `{"stratum|value": [numerator, denominator]}`.""" + cells = {"total|total": [result.numerator, result.denominator]} + for stratum, values in result.strata.items(): + cells |= {f"{stratum}|{v}": [c.numerator, c.denominator] for v, c in values.items()} + return cells + + +def composition_cells(result) -> dict: + """An answer as the snapshot keeps what `v_c2` published: `{"stratum|value|category": n}`.""" + cells = {f"total|total|{c}": n for c, n in result.categories.items()} + for stratum, values in result.strata.items(): + cells |= {f"{stratum}|{v}|{c}": n for v, cs in values.items() for c, n in cs.items()} + return cells + + +def without(cells: dict, stratum: str) -> dict: + return {k: v for k, v in cells.items() if not k.startswith(f"{stratum}|")} + + +def reports(base) -> int: + with base.motor.connect() as connection: + return connection.execute(text("select count(*) from measure_report")).scalar_one() + + +def reload(base, change) -> None: + """Changes the staging as the ingestion would and runs `cargar`: a new load, known later than everything before.""" + time.sleep(0.01) + with Session(base.motor) as session: + change(session) + session.commit() + correr(base.ctx, solo=["cargar"]) + + +def test_ind1_answers_what_the_kit_computed(base, definition, kit): + """Pins down: with no cut-off, every period's IND1 has the kit's units and its numbers. Fails if the semantic + definition (event model, metrics, filter) stops meaning what the kit's IND1 meant.""" + for period_id in PERIODS: + result, expected = ask(base, definition, period_id), kit[IND1][period_id] + assert units(base, result.report_id) == expected["units"], period_id + assert proportion_cells(result)["total|total"] == expected["published"].get("total|total", [0, 0]), period_id + + +def test_eu13_with_its_age_strata_answers_what_the_kit_computed(base, eu13, kit): + """Pins down: EU13 gives the kit's units, each patient's age group at the period's start and the numbers by age + in every period. Fails if the event model, the report date's condition or the age from `dim_fecha` drift.""" + for period_id in PERIODS: + result, expected = ask(base, eu13, period_id), kit[EU13][period_id] + assert units(base, result.report_id) == expected["units"], period_id + assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id + assert without(proportion_cells(result), STATUS) == (expected["published"] or {"total|total": [0, 0]}), period_id + + +def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7, kit): + """Pins down EU7, a composition: each patient in the category of her last valid sample (with a result and a + satisfactory specimen) or SIN_DATO, with her age group, and the kit's counts by category, total and by age. + Fails if the ranking (validity, then the latest sample, then the source id) or the validity rule drifts.""" + for period_id in PERIODS: + result, expected = ask(base, eu7, period_id), kit[EU7][period_id] + assert units(base, result.report_id) == expected["units"], period_id + assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id + assert without(composition_cells(result), STATUS) == expected["published"], period_id + + +def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7): + """Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same + answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing.""" + for d in (definition, eu13, eu7): + first = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30)) + before = reports(base) + again = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30)) + assert (again.report_id, again.stored_before, reports(base)) == (first.report_id, True, before) + if d is eu7: + assert (again.categories, again.strata) == (first.categories, first.strata) + else: + assert proportion_cells(again) == proportion_cells(first) + + +def test_the_event_cutoff_leaves_out_later_facts(base, definition, kit): + """Pins down: S1 cut at March 31 counts the patients of January to March: the union of the kit's monthly units. + Fails if the cut-off stops filtering the event date.""" + result = ask(base, definition, "2025-S1", event_cutoff=date(2025, 3, 31)) + months = sorted({tuple(u) for m in (1, 2, 3) for u in kit[IND1][f"2025-{m:02d}"]["units"]}) + + assert units(base, result.report_id) == [list(u) for u in months] + + +def test_a_late_fact_counts_only_under_a_later_knowledge_cutoff(base, definition): + """Pins down: a cytology of S1 loaded later doesn't change what was known before its load; asked with a later + knowledge cut-off, it counts. Fails if `conocida_en` stops being a condition of the question.""" + known = datetime.now(timezone.utc) + before = ask(base, definition, "2025-S1", knowledge_cutoff=known) + + def late_cytology(session): + h005 = session.exec(select(CitologiaCervical).where(CitologiaCervical.pac_id_hospital == "H-005")).first() + session.add(CitologiaCervical(pac_id=h005.pac_id, pac_id_hospital="H-005", cit_fecha_toma=date(2025, 3, 10), + cit_calidad_especimen="SATISFACTORIO", cit_fecha_reporte=date(2025, 3, 20), + cit_celulas_escamosas="LIEAG")) + reload(base, late_cytology) + + again = ask(base, definition, "2025-S1", knowledge_cutoff=known) + fresh_then = ask(base, definition, "2025-S1", knowledge_cutoff=known, event_cutoff=date(2025, 6, 30)) + now = ask(base, definition, "2025-S1", knowledge_cutoff=datetime.now(timezone.utc)) + + assert again.report_id == before.report_id + assert (fresh_then.numerator, fresh_then.denominator) == (before.numerator, before.denominator) + assert (now.numerator, now.denominator) == (before.numerator + 1, before.denominator + 1) + + +def test_a_changed_fact_is_kept_by_the_history_not_by_the_knowledge_cutoff(base, definition): + """Pins down the limit of the knowledge cut-off: silver keeps one version of each row, so after H-004's LIEAG of + July becomes NEGATIVO, recomputing S2 as known before the change can't give the old numerator; only the stored + answer still does. Fails if silver starts keeping versions (`dbt snapshot`): then expect the old one.""" + known = datetime.now(timezone.utc) + shown = ask(base, definition, "2025-S2", knowledge_cutoff=known) + assert shown.numerator == 1 + + def corrected(session): + row = session.exec(select(CitologiaCervical).where( + CitologiaCervical.pac_id_hospital == "H-004", CitologiaCervical.cit_fecha_toma == date(2025, 7, 1))).one() + row.cit_celulas_escamosas = "NEGATIVO" + reload(base, corrected) + + stored = ask(base, definition, "2025-S2", knowledge_cutoff=known) + recomputed_then = ask(base, definition, "2025-S2", knowledge_cutoff=known, event_cutoff=date(2025, 12, 31)) + + assert (stored.report_id, stored.numerator) == (shown.report_id, 1) + assert recomputed_then.numerator == 0 # the July result now counts as known after `known`: it's left out + assert ask(base, definition, "2025-S2", knowledge_cutoff=datetime.now(timezone.utc)).numerator == 0 + + +def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base, eu13): + """Pins down EU13's numerator, which the fixture leaves at 0: once H-004's biopsy of August 1 (from the July 1 + sample) is LIEAG she counts in 2025-07 and 2025-S2, and an event cut-off before the report leaves her out. + Fails if the numerator stops following the sample's period, the grade rule, or the report's date.""" + def lieag(session): + biopsy = session.exec(select(BiopsiaCervical).where(BiopsiaCervical.pac_id_hospital == "H-004")).one() + biopsy.bx_cin_grado = "LIEAG" + reload(base, lieag) + + assert ask(base, eu13, "2025-07").numerator == 1 + assert ask(base, eu13, "2025-S2").numerator == 1 + assert ask(base, eu13, "2025-S2", event_cutoff=date(2025, 7, 31)).numerator == 0 + + +def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7): + """Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's + inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's + categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer.""" + period = base.dominio.dim_periodo_repository.get("2025-S1") + at = datetime(2026, 1, 2, tzinfo=timezone.utc) + + report = measure_report(definition, Question(IND1, "2025-S1"), ask(base, definition, "2025-S1"), period, at) + (group,) = report["group"] + assert report["measure"] == "cacu/IND1|0.3.2" + assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"} + assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == { + "initial-population": 4, "denominator": 4, "numerator": 1} + assert group["measureScore"] == {"value": 0.25} + assert report["improvementNotation"]["coding"][0]["code"] == "decrease" + + stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period, + at)["group"][0]["stratifier"] + assert [s["code"] for s in stratifiers] == [[{"text": "grupo_edad"}], [{"text": STATUS}]] + + composition = composition_report(eu7, Question(EU7, "2025-S1"), ask(base, eu7, "2025-S1"), period, at) + by_result = composition["group"][0]["stratifier"][0] + assert by_result["code"] == [{"text": "resultado"}] + assert {s["value"]["text"]: s["population"][0]["count"] for s in by_result["stratum"]} == { + "LIEBG": 1, "NEGATIVO": 2, "SIN_DATO": 1} + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8") + + +ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json" +TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE" +DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO" + + +@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO]) +def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url): + """Pins down the duration construct, for the time to the result and the time to the first note that resolves + the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the + cut-off (and, to diagnosis, unless a cervical cancer note came before it); the measured ones carry their days + (`dim_fecha.dia_num` differences); n, the median and the quartiles (inclusive, ANSI) and the excluded are the + kit's where it didn't suppress them (suppression isn't part of the prototype). Fails if the horizon, the day + arithmetic, the resolving note, the exclusion or the quartiles' interpolation drift.""" + from webapi.durations import answer_duration, duration_definitions + + expected = json.loads(ORACLE.read_text(encoding="utf-8"))[url] + definition = duration_definitions(manifest)[url] + for period_id, kit_report in expected["periodos"].items(): + result = answer_duration("cacu", definition, Question(url, period_id), **repositories(base)) + assert units_with_numbers(base, result.report_id) == kit_report["units"], period_id + published = dict(zip(kit_report["published_columns"], next( + row for row in kit_report["published"] if row[1] == "total"))) + if published["suprimido"]: + continue + assert (result.n, result.median, result.q1, result.q3, result.excluded) == ( + published["n"], published["mediana"], published["q1"], published["q3"], published["n_excluido"]), period_id + + +def units_with_numbers(base, report_id: int) -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad " + "where report_id = :r"), {"r": report_id}).all())) + + +def test_the_follow_up_status_is_the_kit_s_in_every_period(base, eu13, eu7): + """Pins down: EU13's and EU7's `estatus_seguimiento` gives each unit the kit's status at the period's start, and + the kit's published numbers by status. Fails if the timeline stratum, the procedures it infers or the order of + the values drift. The fixture's patients are all PRE_COLPOSCOPIA; the other statuses are pinned down by + `test_the_follow_up_status_follows_the_timeline`.""" + oracle = json.loads(ORACLE.read_text(encoding="utf-8")) + for period_id in PERIODS: + for definition in (eu13, eu7): + result, expected = ask(base, definition, period_id), oracle[definition.url]["periodos"][period_id] + assert strata_rows(base, result.report_id, STATUS) == sorted( + [u, v] for u, s, v in expected["strata"] if s == STATUS), (definition.url, period_id) + rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]] + if definition is eu13: + published = {f"{STATUS}|{r['estrato_valor']}": [r["numerador"], r["denominador"]] + for r in rows if r["estrato_id"] == STATUS} + ours = {k: v for k, v in proportion_cells(result).items() if k.startswith(f"{STATUS}|")} + else: + published = {f"{STATUS}|{r['estrato_valor']}|{r['categoria']}": r["n"] + for r in rows if r["estrato_id"] == STATUS and r["n"]} + ours = {k: v for k, v in composition_cells(result).items() if k.startswith(f"{STATUS}|")} + assert ours == published, (definition.url, period_id) + + +def kit_status(base, reference: str) -> dict[str, str]: + """What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules.""" + import tomllib + + from indicadores_kit.cacu.seguimiento import estatus_al, reglas_de + from indicadores_kit.registry.parametros import RUTA_PARAMETROS + from indicadores_kit.serving.seguimiento import leer_estrato + from sqlalchemy import bindparam + + rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8")) + + def rule(key): + node = rules + for part in key.split("."): + node = node[part] + return node["valor"] + + values = {name: rule(key) for name, key in leer_estrato("cacu", STATUS).parametros.items()} + status = estatus_al(bindparam("referencia"), reglas_de(values)) + query = select(status.c.pac_id, status.c.estatus) + named = set(query.compile().params) + with base.motor.connect() as connection: + rows = connection.execute(query, {n: v for n, v in {**values, "referencia": reference}.items() if n in named}) + return {str(pac_id): value for pac_id, value in rows} + + +def follow_up(session) -> None: + """Notes and orders that move three of the fixture's patients along follow-up, in a load of their own. + + Patient 1 (sampled 2025-02-10): a valuation visit, a colposcopy note by its reason (with an accent) and a biopsy + order that day, then a treatment note: POST_TRATAMIENTO from then on. Patient 4 (sampled 2025-05-30): a + valuation visit, then a colposcopy note whose ICD-10 came «S/C» but whose diagnosis text names HPV: + POST_COLPOSCOPIA. Patient 3 (sampled 2025-01-20): a colposcopy note with no valuation before it, which doesn't + count, and her first cytology ordered by a specialty outside surveillance: no status holds, INFO_INSUFICIENTE. + """ + from core.cacu.indicadores.models import Carga, Observacion, Procedimiento + + load = Carga(fuente="seguimiento", inicio=datetime.now(timezone.utc)) + session.add(load) + session.flush() + + def procedure(pac_id, study, kind, when, key, **observed) -> Procedimiento: + p = Procedimiento(fuente_tabla="seguimiento", fuente_id=key, carga_id=load.carga_id, pac_id=pac_id, + estudio_id=study, clase=kind, fecha=date.fromisoformat(when)) + session.add(p) + session.flush() + for result, (column_name, value) in observed.items(): + session.add(Observacion(procedimiento_id=p.procedimiento_id, carga_id=load.carga_id, pac_id=pac_id, + resultado_id=result.replace("__", "."), **{column_name: value})) + return p + + def note(pac_id, when, key, *, cie, specialty="CLINICA_MUJER_COLPOSCOPIA", reason=None, text_dx=None): + observed = {"nota_medica__diagnostico": ("valor_texto", cie), + "nota_medica__especialidad": ("valor_id", specialty)} + if reason: + observed["nota_medica__motivo"] = ("valor_texto", reason) + if text_dx: + observed["nota_medica__diagnostico_texto"] = ("valor_texto", text_dx) + procedure(pac_id, "nota_medica", "encuentro", when, key, **observed) + + note(1, "2025-02-20", "n1a", cie="R876") + note(1, "2025-03-03", "n1b", cie="Z000", reason="Acude a colposcopía") + procedure(1, "biopsia", "orden", "2025-03-03", "o1") + note(1, "2025-04-01", "n1c", cie="D06", specialty="CIRUGIA_ONCOLOGICA") + note(4, "2025-06-05", "n4a", cie="R876") + note(4, "2025-06-10", "n4b", cie="S/C", text_dx="Virus del papiloma humano") + note(3, "2025-01-25", "n3a", cie="Z000", reason="COLPOSCOPIA") + order = procedure(3, "citologia", "orden", "2025-01-19", "c3", + orden__especialidad=("valor_id", "CIRUGIA_ONCOLOGICA")) + (sample,) = session.exec(select(Procedimiento).where( + Procedimiento.pac_id == 3, Procedimiento.estudio_id == "citologia", Procedimiento.clase == "toma", + Procedimiento.fecha == date(2025, 1, 20))).all() + sample.padre_id = order.procedimiento_id + + +def test_the_follow_up_status_follows_the_timeline(base, eu13, eu7): + """Pins down: with colposcopies and a treatment on the timeline, every unit of EU13 and EU7 in every period gets + the status the kit's `estatus_al` gives her at the period's start, and all four statuses come out; asked with a + knowledge cut-off before those facts arrived, they're PRE_COLPOSCOPIA again. Fails if an inferred procedure + (the valuation requirement, the same-day order, the accent-blind reason, the diagnosis text), the timeline + stratum or the values' order stops meaning what the kit's rules mean.""" + with base.motor.connect() as connection: + before_load = connection.execute(text("select max(inicio) from carga")).scalar_one() + with Session(base.motor) as session: + follow_up(session) + session.commit() + + seen = set() + for period_id in PERIODS: + start = base.dominio.dim_periodo_repository.get(period_id).inicio.isoformat() + expected = kit_status(base, start) + for definition in (eu13, eu7): + ours = dict(strata_rows(base, ask(base, definition, period_id).report_id, STATUS)) + assert ours == {unit: expected[unit] for unit in ours}, (definition.url, period_id) + seen |= set(ours.values()) + assert seen == {"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA", "POST_TRATAMIENTO", "INFO_INSUFICIENTE"} + + known_then = datetime.fromisoformat(before_load) + earlier = ask(base, eu13, "2025-10", knowledge_cutoff=known_then) + assert set(dict(strata_rows(base, earlier.report_id, STATUS)).values()) == {"PRE_COLPOSCOPIA"} + + +def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_yet(base, manifest): + """Pins down the cut-off of the time to diagnosis: in 2025-S2 cut at September 30, the July sample resolved in + August is measured (40 days); the August sample, resolved only in January, and the September one, with no note, + are still within 180 days, so they aren't measured yet; the October sample is after the cut. Fails if a note + after the cut-off counts, or a pending sample enters the initial population.""" + from webapi.durations import answer_duration, duration_definitions + + definition = duration_definitions(manifest)[DIAS_TOMA_DIAGNOSTICO] + result = answer_duration("cacu", definition, Question(DIAS_TOMA_DIAGNOSTICO, "2025-S2", date(2025, 9, 30)), + **repositories(base)) + assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0) + + +CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA" + + +def test_the_confirmation_by_biopsy_is_the_kit_s_in_every_period(base, manifest): + """Pins down the composition that follows the chosen fact: each patient whose last valid sample of the period is + high grade, in the grade of the most severe biopsy that sample led to by the cut-off (SIN_BIOPSIA without one), + by that sample's result; units, strata and counts are the kit's in every period. Fails if the two-level ranking, + the admission on the chosen sample, the severity order or the chosen-row stratum drift.""" + oracle = json.loads(ORACLE.read_text(encoding="utf-8"))[CONFIRMACION] + definition = composition_definitions(manifest)[CONFIRMACION] + for period_id, expected in oracle["periodos"].items(): + result = answer_composition("cacu", definition, Question(CONFIRMACION, period_id), **repositories(base)) + assert units(base, result.report_id) == [u[:5] for u in expected["units"]], period_id + assert strata_rows(base, result.report_id, "citologia_alto_grado") == sorted( + [u, v] for u, s, v in expected["strata"] if s == "citologia_alto_grado"), period_id + rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]] + published = {f"{r['estrato_id']}|{r['estrato_valor']}|{r['categoria']}": r["n"] for r in rows if r["n"]} + assert {k: v for k, v in composition_cells(result).items() if v} == published, period_id diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 76c1dd7..b8cf16c 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -1,21 +1,19 @@ -"""El ciclo deja los mismos reportes que la base de demostración del kit. +"""What this module covers: the whole cycle on the CaCu fixture database, in order, once and again. -Dos bases con el mismo staging (los fixtures del kit): -- una armada por la orquestación: Alembic, carga, vistas, registro y cálculo; -- otra por `indicadores_kit.demostracion.base_de_prueba`, que es la que usa la compuerta. - -Los reportes tienen que coincidir valor por valor. Volver a correr el ciclo no -agrega reportes. +Fixtures: `bases`, one database loaded by the cycle from the kit's synthetic staging, with dbt's manifest +(`DBT_MANIFEST`) for the definitions and the event models. The cycle computes no measure: they're answered on request +(`test_metrics_on_request`), so running it again adds no report. """ +import os from datetime import date +from pathlib import Path from importlib import import_module import pytest from sqlalchemy import create_engine, text from sqlmodel import Session -from indicadores_kit.demostracion import base_de_prueba from webapi.orquestacion import Contexto, correr from webapi.orquestacion.conexion import apuntar @@ -27,12 +25,9 @@ CONSULTA = text(""" FROM measure_report_unidad u JOIN measure_report r USING (report_id)""") -def valores(motor) -> list[tuple]: - with motor.connect() as con: - return sorted(tuple(str(x) for x in fila) for fila in con.execute(CONSULTA)) -@pytest.fixture(scope="module", params=["cacu", "cama", "tea"]) +@pytest.fixture(scope="module", params=["cacu", "cama"]) def bases(request, tmp_path_factory): proyecto = request.param carpeta = tmp_path_factory.mktemp(proyecto) @@ -40,16 +35,14 @@ def bases(request, tmp_path_factory): apuntar(proyecto, url) # `observar` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de # dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo. - ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True) + ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"])) correr(ctx, solo=["migrar"]) motor = create_engine(url) with Session(motor) as sesion: import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) sesion.commit() pasos = correr(ctx) - demostracion = create_engine(f"sqlite:///{carpeta / 'demostracion.db'}") - base_de_prueba(demostracion, proyecto) - return proyecto, ctx, motor, demostracion, pasos + return proyecto, ctx, motor, None, pasos def test_corre_todos_los_pasos_en_orden(bases): @@ -57,17 +50,13 @@ def test_corre_todos_los_pasos_en_orden(bases): nombres = [p.nombre for p in pasos] # `migrar` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9). assert nombres[0] == "migrar" and nombres.index("catalogos") < nombres.index("cargar") - assert nombres.index("calcular") < nombres.index("observar") + assert nombres.index("cargar") < nombres.index("modelos") and "calcular" not in nombres -def test_los_reportes_son_los_de_la_base_de_demostracion(bases): - _, _, motor, demostracion, _ = bases - orquestados, esperados = valores(motor), valores(demostracion) - assert orquestados, "el ciclo no calculó nada" - assert orquestados == esperados def test_volver_a_correr_no_agrega_reportes(bases): + """Pins down: the cycle computes no measure (they're answered on request): running it adds no report.""" _, ctx, motor, _, _ = bases with motor.connect() as con: antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() @@ -88,37 +77,6 @@ def test_en_cacu_arma_su_cohorte_una_vez(bases): text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one() -def test_cada_reporte_guarda_sus_unidades(bases): - """Todo reporte lleva la huella de sus unidades de §6f (T-19b, T-19e): sin ella, las vistas lo darían en 0.""" - _, _, motor, _, _ = bases - with motor.connect() as con: - sin = con.execute(text("SELECT COUNT(*) FROM measure_report WHERE huella IS NULL")).scalar_one() - con_unidades = con.execute(text("SELECT COUNT(DISTINCT report_id) FROM measure_report_unidad")).scalar_one() - assert sin == 0 and con_unidades > 0 -def test_cada_reporte_se_mide_y_se_guarda_en_una_sola_sesion(bases): - """La regla de §6 en `calcular`: antes eran dos sesiones (medir y guardar).""" - from functools import partial - - from indicadores_kit.oro.calculo import medir_con_unidades - from indicadores_kit.registry.measures import measures_de - from indicadores_kit.tablas import tablas_de - from persistance.aristas.oro import CalculoRepository - - proyecto, _, motor, _, _ = bases - tablas = tablas_de(proyecto) - abiertas = [] - - def fabrica(): - abiertas.append(1) - return Session(motor) - - calculo = CalculoRepository(fabrica, tablas.MeasureReport, periodo=tablas.DimPeriodo) - medida = next(iter(measures_de(proyecto).values())) - tipo = medida.extension.publicacion.tipos_periodo[0] - periodo_id = calculo.periodos(tipo, date(ANIO, 1, 1), date(ANIO + 1, 1, 1))[0] - abiertas.clear() - calculo.calcular(partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas)) - assert len(abiertas) == 1 diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index ccc3392..fbaf427 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -1,4 +1,4 @@ -"""Los pasos de oro sobre la base del dominio: el registro, las definiciones y el cálculo. +"""Los pasos de oro sobre la base del dominio: el registro y las definiciones (el catálogo, del manifiesto de dbt). Vienen del kit (`test_pasos` y `test_produccion`, MD-16). El reporte se lee por los repositorios de Persistance, como lo leería `WebApi`. @@ -7,91 +7,34 @@ repositorios de Persistance, como lo leería `WebApi`. from datetime import date import pytest -from sqlalchemy import text -from sqlmodel import select -from indicadores_kit.cacu import fixtures as fixtures_cacu -from indicadores_kit.cama import fixtures as fixtures_cama from indicadores_kit.plata.carga import tablas_de_staging -from indicadores_kit.registry.measures import leer_measure, measures_de, ruta_de_measure from indicadores_kit.registry.edades import grupos_de_cortes from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.serving.contratos import ultimo_reporte from indicadores_kit.tablas import tablas_de -from indicadores_kit.tea import fixtures as fixtures_tea from webapi.orquestacion.proyecto import tipos_de_periodo from conftest import ANIO # El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}. -EJEMPLO = {"cacu": "ind1", "cama": "cama_confirmacion_birads45", "tea": "M24_confirmacion_diagnostico"} -TOTAL = {"cacu": "principal", "cama": "principal", "tea": "TOTAL"} -ESPERADO = { - "cacu": fixtures_cacu.ESPERADO_IND1, - "cama": fixtures_cama.ESPERADO_CAMA_CONFIRMACION_BIRADS45, - "tea": {p: v["TOTAL"][:2] for p, v in fixtures_tea.ESPERADO["M24_confirmacion_diagnostico"].items()}, -} -# Un dato de staging que cambia el numerador del ejemplo: (tabla de STAGING, columna con que se busca, su valor, -# columna que cambia, valor nuevo). CaCu: la citología NEGATIVO de H-001 pasa a LIEAG (anómala). CaMa: la -# mastografía B0 del 10 de marzo, que ya tiene biopsia, pasa a B4A (de sospecha). TEA: la nota R62.0 de T-03 pasa -# a F84.0 (confirma el diagnóstico). -CAMBIO = { - "cacu": ("citologiacervical", "cit_fecha_toma", date(2025, 2, 10), "cit_celulas_escamosas", "LIEAG"), - "cama": ("mastografia", "mast_fecha_toma", date(2025, 3, 10), "mast_birads", "B4A"), - "tea": ("nota_medica", "nm_id", "nm-03", "nm_cie_codigo", "F84.0"), -} - - def cargas(proyecto) -> tuple[str, ...]: """El paso que lleva el staging a la plata (staging directo, T-20c).""" return ("cargar",) -def hasta_calcular(proyecto) -> tuple[str, ...]: - return ("catalogos", *cargas(proyecto), "vistas", "registro", "definiciones", "calcular") -def cambiar_staging(base) -> None: - tabla, llave, valor_llave, columna, nuevo = CAMBIO[base.proyecto] - modelo = {m.__tablename__: m for m in tablas_de_staging(base.proyecto)}[tabla] - with base.staging() as sesion: - (fila,) = sesion.exec(select(modelo).where(getattr(modelo, llave) == valor_llave)).all() - setattr(fila, columna, nuevo) - sesion.commit() -def ejemplo(proyecto): - return leer_measure(ruta_de_measure(proyecto, EJEMPLO[proyecto])) -def conteos(base, report_id: int) -> tuple[int, int]: - """(denominador sin exclusiones, numerador) del grupo total, de lo que publica `v_c1` (T-19e).""" - with base.motor.connect() as con: - return tuple(con.execute(text( - "SELECT denominador, numerador FROM v_c1 WHERE report_id = :r AND grupo = :g AND estrato_id = 'total'"), - {"r": report_id, "g": TOTAL[base.proyecto]}).one()) -def reportes_del_ejemplo(base, periodo_id="2025-S1", nombre=None) -> list: - measure = leer_measure(ruta_de_measure(base.proyecto, nombre)) if nombre else ejemplo(base.proyecto) - return [r for r in base.dominio.measure_report_repository.list(limit=10_000) - if r.measure_url == measure.url and r.periodo_id == periodo_id] -def ultimo(base, periodo_id="2025-S1") -> int: - with base.staging() as sesion: - return ultimo_reporte(sesion, ejemplo(base.proyecto), periodo_id, tablas=tablas_de(base.proyecto)) -def test_de_staging_al_reporte_leido_por_repository(base, sin_supresion): - reportes = base.correr(*hasta_calcular(base.proyecto), parametros=sin_supresion, permitir_sin_definir=True)["calcular"] - - assert set(reportes) == set(measures_de(base.proyecto)) - for periodo, esperado in ESPERADO[base.proyecto].items(): - (reporte,) = reportes_del_ejemplo(base, periodo) - assert reporte.report_id in reportes[EJEMPLO[base.proyecto]] - assert conteos(base, reporte.report_id) == esperado def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base): @@ -99,7 +42,7 @@ def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base): base.correr("registro", anio_inicio=ANIO - 1) tablas = tablas_de(base.proyecto) - esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO - 1, ANIO, tablas=tablas) + esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas) assert base.dominio.dim_periodo_repository.count() == len(esperados) assert base.dominio.measure_report_repository.count() == 0 @@ -120,18 +63,6 @@ def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base): assert sorted(grupos) == sorted(esperados) # TEA no tiene cortes: vacía -def test_con_reportes_guardados_se_cambia_un_parametro_y_se_agrega_un_anio(base, sin_supresion): - """Antes (I-K54) esto fallaba: reemplazar dim_periodo violaba la llave de measure_report.""" - base.correr(*hasta_calcular(base.proyecto), permitir_sin_definir=True) - reportes = base.dominio.measure_report_repository.count() - - base.correr("registro", anio_fin=ANIO + 1, parametros=sin_supresion) - - assert base.dominio.def_parametro_repository.get("comun.umbral_supresion").valor == "1" - tablas = tablas_de(base.proyecto) - esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO, ANIO + 1, tablas=tablas) - assert base.dominio.dim_periodo_repository.count() == len(esperados) - assert base.dominio.measure_report_repository.count() == reportes def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): @@ -148,45 +79,19 @@ def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): assert base.dominio.dim_periodo_repository.count() == periodos -def test_las_definiciones_son_las_de_los_toml(base): +def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): + """Pins down: `definiciones` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a + measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.correr("definiciones")["definiciones"] - assert resumen["definiciones"] == len(measures_de(base.proyecto)) + # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata. + assert resumen["definiciones"] == {"cacu": 10, "cama": 7}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == len(measures_de(base.proyecto)) + assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain assert base.correr("definiciones")["definiciones"]["borradas"] == 0 -def test_recalcular_tras_una_carga_sin_cambios_no_agrega_reportes(base): - """T-2 de v0.4.0 (D-5): lo idéntico no se guarda otra vez.""" - base.correr(*hasta_calcular(base.proyecto), permitir_sin_definir=True) - antes = base.dominio.measure_report_repository.count() - - base.correr(*cargas(base.proyecto), "calcular", permitir_sin_definir=True) - - assert base.dominio.measure_report_repository.count() == antes - (reporte,) = reportes_del_ejemplo(base) - assert ultimo(base) == reporte.report_id and reporte.parametros_sha is not None -def test_con_un_dato_nuevo_recalcular_agrega_un_reporte_y_se_lee_el_ultimo(base, sin_supresion): - base.correr(*hasta_calcular(base.proyecto), parametros=sin_supresion, permitir_sin_definir=True) - (primero,) = reportes_del_ejemplo(base) - - cambiar_staging(base) - base.correr(*cargas(base.proyecto), "calcular", parametros=sin_supresion, permitir_sin_definir=True) - - reportes = sorted(reportes_del_ejemplo(base), key=lambda r: r.report_id) - assert [r.report_id for r in reportes][0] == primero.report_id and len(reportes) == 2 - assert ultimo(base) == reportes[1].report_id - assert conteos(base, reportes[0].report_id)[1] != conteos(base, reportes[1].report_id)[1] -def test_el_corte_no_distingue_los_reportes_de_un_indicador_que_no_lo_usa(base): - """MV-3: `measure_report.fecha_corte` existe tras migrar; un indicador que no la usa la deja nula.""" - base.correr(*hasta_calcular(base.proyecto), corte=date(2025, 3, 31), permitir_sin_definir=True) - base.correr("calcular", corte=date(2025, 12, 31), permitir_sin_definir=True) - - # El ejemplo de CaMa usa el corte (`:fecha_corte`); ahí se mira otro que no lo usa. - (reporte,) = reportes_del_ejemplo(base, nombre={"cama": "cama_biopsias"}.get(base.proyecto)) - assert reporte.fecha_corte is None diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index f6af8e8..b4bc39c 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -23,14 +23,14 @@ def antes(deps: dict[str, set[str]], paso: str) -> set[str]: return previos -@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) +@pytest.mark.parametrize("proyecto", ["cacu", "cama"]) def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto): deps = dependencias(proyecto) assert deps["migrar"] == set() assert {"migrar", "catalogos"} <= antes(deps, "cargar") # decisión 6 de §9 - assert {"cargar", "vistas", "registro", "definiciones"} <= antes(deps, "calcular") - assert {"registro", "calcular"} <= antes(deps, "observar") - assert {"cargar", "calcular"} <= antes(deps, "verificar_plata") + assert {"cargar"} <= antes(deps, "modelos") + assert {"registro"} <= antes(deps, "observar") + assert {"cargar", "catalogos"} <= antes(deps, "verificar_plata") def test_solo_cacu_arma_cohortes_y_estima_por_ahora(): diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 529edfa..9631914 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -19,7 +19,6 @@ from indicadores_kit.plata.periodo_observacion import ( from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo from indicadores_kit.registry.parametros import RUTA_PARAMETROS, ParametroSinDefinir from indicadores_kit.tablas import tablas_de -from indicadores_kit.tea import fixtures as fixtures_tea from sqlalchemy import inspect, text from sqlmodel import select @@ -27,7 +26,6 @@ from sqlmodel import select CAMBIO = { "cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"), "cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"), - "tea": ("evaluacion_psicologica", "psi_fecha_ados2", date(2024, 12, 1)), } CORTE = date(2025, 12, 31) @@ -107,13 +105,6 @@ def test_cargar_lleva_el_staging_a_persona_y_la_plata(base): assert contar(base, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'orden_estudio_servicio'") == 0 -@pytest.mark.parametrize("proyecto", ["tea"]) -def test_los_descartes_y_los_huerfanos_quedan_en_la_carga(base): - base.correr("catalogos", "cargar") - - descartes = json.loads(ultima_carga(base).descartes) - assert {m: n for m, n in descartes.items() if m.startswith("eeg")} == fixtures_tea.DESCARTES - assert descartes["huerfanos"] > 0 # los segmentos de los EEG que no entraron (I-MD17) def test_volver_a_cargar_sin_cambios_no_toca_nada(base): @@ -137,16 +128,6 @@ def test_un_cambio_en_staging_toca_un_procedimiento(base): assert plata_de(base) == antes -def test_cada_proyecto_carga_con_su_base_en_el_mismo_proceso(tmp_path): - fuentes = {} - for proyecto in ("cacu", "cama", "tea"): - base = base_de(proyecto, tmp_path) - base.correr("catalogos", "cargar") - fuentes[proyecto] = ultima_carga(base).fuente - base.motor.dispose() - - assert fuentes["cacu"].startswith("citologiacervical") and fuentes["cama"].startswith("mastografia") - assert "eeg_estudio" in fuentes["tea"] # --- vistas --- @@ -156,8 +137,8 @@ def test_las_vistas_se_construyen_y_se_pueden_repetir(base): primera = base.correr("vistas")["vistas"] assert base.correr("vistas")["vistas"] == primera - # Desde F6 (ADR-MD-009) no hay vistas por tipo: `v_persona` y, desde MD-19, las del número publicado. - assert sorted(inspect(base.motor).get_view_names()) == ["v_c1", "v_c2", "v_c3r", "v_measure_report_vigente", "v_persona"] + # Only `v_persona`: the published numbers are answered on request, so the publication views aren't built. + assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"] # --- observar --- diff --git a/tests/test_orquestacion_regla_repositorios.py b/tests/test_orquestacion_regla_repositorios.py index cc601b7..f13c068 100644 --- a/tests/test_orquestacion_regla_repositorios.py +++ b/tests/test_orquestacion_regla_repositorios.py @@ -23,7 +23,7 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo): assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos" -@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)]) +@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)]) def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes): repos = repositorios_de(proyecto) assert (repos.oro.cohorte is not None) == con_cohortes diff --git a/tests/test_orquestacion_riesgos.py b/tests/test_orquestacion_riesgos.py index 55dac31..5cb1a4c 100644 --- a/tests/test_orquestacion_riesgos.py +++ b/tests/test_orquestacion_riesgos.py @@ -43,7 +43,7 @@ class EstimadorFijo: @pytest.fixture def cacu(base): - base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True) + base.correr("catalogos", "cargar", "modelos", "cohortes", permitir_sin_definir=True) return base @@ -95,21 +95,3 @@ DE_PUNTA_A_PUNTA = { } -@pytest.mark.parametrize("proyecto", sorted(DE_PUNTA_A_PUNTA)) -def test_el_lote_confirmado_sale_en_el_resumen_por_banda(base, proyecto, sin_supresion): - """De punta a punta: la cohorte, estimar a su horizonte, confirmar y el resumen por banda.""" - url, horizonte, measure = DE_PUNTA_A_PUNTA[proyecto] - base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True) - estimador = EstimadorFijo(url, horizonte=horizonte, probabilidad=0.3) # 0.3 >= corte_alto: ALTO - (lote_id, _) = base.correr("estimar", estimadores={url: estimador})["estimar"][url] - confirmar_riesgos(proyecto, lote_id, "revisado") - # Sin supresión: los fixtures tienen menos miembros por semestre que el umbral (CaMa la tiene activa). - base.correr("vistas", "registro", "definiciones", "calcular", parametros=sin_supresion, permitir_sin_definir=True) - - en_el_anio = cuenta(base, f"""SELECT COUNT(*) FROM cohorte_miembro - WHERE strftime('%Y', fecha_indice) = '{base.ctx.anio_inicio}'""") - altos = cuenta(base, f"""SELECT COALESCE(SUM(v.n), 0) FROM v_c2 v - JOIN v_measure_report_vigente r ON r.report_id = v.report_id - WHERE r.measure_url = '{measure}' AND r.periodo_id LIKE '%-S_' - AND v.categoria = 'ALTO' AND v.estrato_id = 'total'""") - assert en_el_anio > 0 and altos == en_el_anio diff --git a/tests/test_orquestacion_timeline.py b/tests/test_orquestacion_timeline.py index 0d6e638..8d07c93 100644 --- a/tests/test_orquestacion_timeline.py +++ b/tests/test_orquestacion_timeline.py @@ -1,64 +1,72 @@ -"""What this module covers: the timeline repository that `repositorios_de` wires into `ctx.repos.plata` -reads the same rows as the kit's own query, in each project. +"""What this module covers: the timeline `repositorios_de` wires into `ctx.repos.plata` is dbt's view +`cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's +facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them. -Fixtures: `base` (from `conftest.py`), a project database for each of CaCu, CaMa and TEA; each test loads -its catalogs and data with `base.correr("catalogos", "cargar")`. `kit_rows` reads the same timeline -straight through the kit (`filas_de_linea`) to compare against. +Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created +(`catalogos`, `cargar`, `modelos`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on +that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time). """ +import json +import os from datetime import date, datetime, timedelta, timezone -from importlib import import_module +from pathlib import Path -from indicadores_kit.oro.cohortes.armado import filas_de_linea -from indicadores_kit.tablas import tablas_de -from sqlmodel import Session +import pytest CORTE = date(2025, 12, 31) +INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"} +KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json" -def kit_rows(base, **filters): - """The project's timeline read through the kit with `filters` (the kit's Spanish keywords).""" - fuentes = import_module(f"indicadores_kit.{base.proyecto}.linea_de_tiempo").FUENTES_PLATA - with Session(base.motor) as session: - return filas_de_linea(session, tablas_de(base.proyecto), fuentes, **filters) +@pytest.fixture +def proyecto(): + return "cacu" -def test_the_whole_timeline_matches_the_kit(base): - """Pins down: with only a clinical cut-off, the wired repository returns exactly the kit's rows, and - there are some. - - Fails if the orchestration binds another query, another project's tables or sources, or `until` - stops reaching the kit as `hasta`. - """ - base.correr("catalogos", "cargar") - rows = base.ctx.repos.plata.timeline.read(until=CORTE) - assert rows - assert rows == kit_rows(base, hasta=CORTE) +@pytest.fixture +def loaded(base): + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + base.correr("catalogos", "cargar", "modelos") + return base -def test_the_patient_filter_matches_the_kit(base): - """Pins down: `patients` reaches the kit as `pacientes`: only those patients come back, with the - kit's rows. +@pytest.fixture +def kit_rows(): + return json.loads(KIT_ROWS.read_text(encoding="utf-8")) - Fails if the patient filter is dropped or renamed on the way to the kit's query. - """ - base.correr("catalogos", "cargar") - patients = sorted({row["pac_id"] for row in kit_rows(base)})[:2] - rows = base.ctx.repos.plata.timeline.read(patients=patients, until=CORTE) + +def as_kit(rows) -> list[dict]: + """Rows as the snapshot keeps them: text values, no load time, without the inferred procedures.""" + return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"} + for row in rows if row["tipo"] not in INFERRED] + + +def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows): + """Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its + order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or + the view stops giving one of the kit's rows.""" + rows = loaded.ctx.repos.plata.timeline.read(until=CORTE) + assert as_kit(rows) == kit_rows + assert {row["tipo"] for row in rows} & INFERRED + assert all(isinstance(row["fecha"], date) for row in rows) + + +def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows): + """Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied.""" + patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2] + rows = loaded.ctx.repos.plata.timeline.read(patients=patients, until=CORTE) assert {row["pac_id"] for row in rows} == set(patients) - assert rows == kit_rows(base, pacientes=patients, hasta=CORTE) + assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients] -def test_known_until_cuts_at_what_was_loaded(base): - """Pins down: `known_until` reaches the kit as `conocida_hasta`: before the load nothing is known, - after it everything is, the same as reading without the cut. - - Fails if the load cut-off is ignored, or applied to the clinical date instead of the load time. - """ - before = datetime.now(timezone.utc) - timedelta(days=1) - base.correr("catalogos", "cargar") - after = datetime.now(timezone.utc) + timedelta(days=1) - timeline = base.ctx.repos.plata.timeline - assert timeline.read(until=CORTE, known_until=before) == [] - assert timeline.read(until=CORTE, known_until=after) == kit_rows(base, hasta=CORTE, conocida_hasta=after) - assert timeline.read(until=CORTE, known_until=after) == timeline.read(until=CORTE) +def test_known_until_cuts_at_what_was_loaded(loaded): + """Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known, + after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text.""" + timeline = loaded.ctx.repos.plata.timeline + everything = timeline.read(until=CORTE) + known = {row["conocida_en"] for row in everything} + assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known) + assert timeline.read(until=CORTE, known_until=min(known) - timedelta(seconds=1)) == [] + assert timeline.read(until=CORTE, known_until=datetime.now(timezone.utc) + timedelta(days=1)) == everything diff --git a/tests/test_reportes.py b/tests/test_reportes.py index da18b06..93078f8 100644 --- a/tests/test_reportes.py +++ b/tests/test_reportes.py @@ -105,8 +105,10 @@ def test_indicators_recompute_from_imported_rows(client): estado = client.get("/reportes/indicadores").get_json()["cacu"] assert estado["estado"] == "ok", estado assert estado["pendiente"] is False - assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "calcular"} - assert client.get("/cacu/indicadores").get_json() + assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "modelos"} + assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == { + "IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE", + "CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"} assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202 assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404 diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 6c07d11..d02f5fb 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -142,6 +142,16 @@ def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns() catalog.coerce("X") + + +def test_postal_code_restores_leading_zero_from_numeric_sources(): + from webapi.imports.schemas.coercion import coerce_postal_code + + assert coerce_postal_code(1000) == "01000" + assert coerce_postal_code(64000.0) == "64000" + assert coerce_postal_code(" 01000 ") == "01000" + assert coerce_postal_code("") is None + def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog(): """`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C from narrative text (a standard ACR BI-RADS subcategory), but the schema @@ -154,16 +164,6 @@ def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog(): for value in ("4A", "BI-RADS 4B", "bi-rads 4c"): assert catalog.coerce(value) == "B4" - -def test_postal_code_restores_leading_zero_from_numeric_sources(): - from webapi.imports.schemas.coercion import coerce_postal_code - - assert coerce_postal_code(1000) == "01000" - assert coerce_postal_code(64000.0) == "64000" - assert coerce_postal_code(" 01000 ") == "01000" - assert coerce_postal_code("") is None - - def test_column_matcher_handles_accents_prefixes_and_global_one_to_one(): targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"] by_source = { diff --git a/tests/test_schemas_registry.py b/tests/test_schemas_registry.py index cf0208e..bdef2e5 100644 --- a/tests/test_schemas_registry.py +++ b/tests/test_schemas_registry.py @@ -34,6 +34,8 @@ def test_every_registered_schema_is_constructible(entity_key): # --- Spot checks ----------------------------------------------------------- # CaMa entity with a required, unique integer ord_numero_hospital and an # *_ALIAS-backed enum field. + + def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio(): with pytest.raises(ValidationError) as excinfo: CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1") diff --git a/webapi/__init__.py b/webapi/__init__.py index b77c6a2..12af8a3 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -6,12 +6,10 @@ from flask import Flask, jsonify from flask.json.provider import DefaultJSONProvider from webapi.blueprints.cacu import cacu_bp -from webapi.blueprints.cama import cama_bp from webapi.blueprints.data import data_bp from webapi.blueprints.governance import governance_bp from webapi.blueprints.imports import imports_bp from webapi.blueprints.reportes import reportes_bp -from webapi.blueprints.tea import tea_bp from webapi.seguimiento import blueprint_de_seguimiento, en_dev @@ -71,12 +69,20 @@ def create_app() -> Flask: return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413 app.register_blueprint(cacu_bp, url_prefix="/cacu") - app.register_blueprint(cama_bp, url_prefix="/cama") - app.register_blueprint(tea_bp, url_prefix="/tea") app.register_blueprint(imports_bp, url_prefix="/imports") app.register_blueprint(data_bp, url_prefix="/data") app.register_blueprint(governance_bp, url_prefix="/governance") app.register_blueprint(reportes_bp, url_prefix="/reportes") + # The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest. + if os.environ.get("DBT_MANIFEST"): + from importlib import import_module + from pathlib import Path + + from webapi.kpis import kpis_blueprint + + for domain in ("cacu", "cama"): + app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"), + Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}") # Patient-level follow-up list and individual risk: only in DEV, with simulated data. if en_dev(): from persistance.db import get_cacu_session diff --git a/webapi/blueprints/cacu.py b/webapi/blueprints/cacu.py index ba72d75..38d532a 100644 --- a/webapi/blueprints/cacu.py +++ b/webapi/blueprints/cacu.py @@ -1,7 +1,3 @@ from flask import Blueprint -from persistance.db import get_cacu_session -from webapi.indicadores import registrar_indicadores - cacu_bp = Blueprint("cacu", __name__) -registrar_indicadores(cacu_bp, "cacu", get_cacu_session) diff --git a/webapi/blueprints/cama.py b/webapi/blueprints/cama.py deleted file mode 100644 index f8a39c4..0000000 --- a/webapi/blueprints/cama.py +++ /dev/null @@ -1,7 +0,0 @@ -from flask import Blueprint - -from persistance.db import get_cama_session -from webapi.indicadores import registrar_indicadores - -cama_bp = Blueprint("cama", __name__) -registrar_indicadores(cama_bp, "cama", get_cama_session) diff --git a/webapi/blueprints/imports.py b/webapi/blueprints/imports.py index fabf3c0..47410a6 100644 --- a/webapi/blueprints/imports.py +++ b/webapi/blueprints/imports.py @@ -21,7 +21,7 @@ from webapi.imports.services.import_service import ( serialize_errors, validate_source, ) -from webapi.indicadores_vivos import ColaDeRecalculo +from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo from webapi.imports.services.introspection_service import ( detect_pdf, document_report, @@ -321,7 +321,7 @@ def commit(): finally: import_audit.record(audit) recalculating = False - if audit.domain and any(r.created or r.updated for r in results): + if audit.domain in DOMINIOS and any(r.created or r.updated for r in results): try: ColaDeRecalculo().solicitar(audit.domain) recalculating = True diff --git a/webapi/blueprints/tea.py b/webapi/blueprints/tea.py deleted file mode 100644 index bc0c8cc..0000000 --- a/webapi/blueprints/tea.py +++ /dev/null @@ -1,7 +0,0 @@ -from flask import Blueprint -from persistance.db import get_tea_session - -from webapi.indicadores import registrar_indicadores - -tea_bp = Blueprint("tea", __name__) -registrar_indicadores(tea_bp, "tea", get_tea_session) diff --git a/webapi/compositions.py b/webapi/compositions.py new file mode 100644 index 0000000..91322b8 --- /dev/null +++ b/webapi/compositions.py @@ -0,0 +1,329 @@ +"""A composition answered on request: how a period's units split across the categories of their latest valid fact. + +The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring: +composition` and gives the category rule (`categoria`): which column is the category, what makes a fact valid +(a template like a metric's `filter`), the dates the event and knowledge cut-offs apply to, and the order that picks +each unit's latest fact. Which fact is a unit's latest depends on the question (its period and cut-offs), so it's +computed in the answer, with `ROW_NUMBER()`, not stored in the model. The rest (the question, the history, strata +by age at the period's start) is `webapi.metrics`'. +""" + +import dataclasses +import hashlib +import json +from collections.abc import Iterable +from datetime import datetime, timedelta, timezone +from importlib import import_module +from pathlib import Path + +from core.indicadores.tipos import FechaHoraUTC +from jinja2 import Environment +from sqlalchemy import Select, String, and_, bindparam, case, cast, column, desc, distinct, func, literal, select, table, text + +from webapi.metrics import ( + AGGREGATION_VERSION, + HISTORY_ENTRY, + EVENT_CUTOFF, + KNOWLEDGE_CUTOFF, + POPULATION_SYSTEM, + MeasureQueries, + Population, + Question, + Stratum, + _population, + _semantic_model_of, + key_of, + rule_values, +) + + +@dataclasses.dataclass(frozen=True) +class FollowUp: + """A fact that follows the chosen one (a biopsy of the chosen sample): the category comes from the first of + them by `order`, among those that exist and were dated and known by the cut-offs; `none` if there's none.""" + + exists: str + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + order: tuple[str, ...] + none: str + + +@dataclasses.dataclass(frozen=True) +class Category: + value: str + no_data: str + valid_sql: str + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + order: tuple[str, ...] + admits_sql: str | None = None # which units count, judged on their chosen fact + follow_up: FollowUp | None = None + # A number's band instead of the value itself: (band, rule of its upper bound), in order; the last has no bound. + bands: tuple[tuple[str, str | None], ...] = () + + +@dataclasses.dataclass(frozen=True) +class CompositionDefinition: + """A composition, shaped so `MeasureQueries` can build its period, cut-offs and strata.""" + + url: str + version: str + metric: str + relation: str + model_checksum: str + time_dimension: str + dimensions: dict[str, str] + units: Population + category: Category + group: str + basis: str + rules: dict[str, str] + strata: tuple[Stratum, ...] + + @property + def measure_id(self) -> str: + return self.url.rsplit("/", 1)[-1] + + @property + def numerator(self) -> Population: + return self.units + + @property + def denominator(self) -> Population: + return self.units + + improvement_notation = None + + +def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]: + """The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`.""" + m = json.loads(manifest.read_text(encoding="utf-8")) + semantic = {node["name"]: node for node in m["semantic_models"].values()} + models = {node["unique_id"]: node for node in m["nodes"].values()} + definitions = {} + for metric in m["metrics"].values(): + meta = metric["config"].get("meta", {}) + if metric["type"] != "simple" or meta.get("scoring") != "composition": + continue + model = _semantic_model_of(metric, semantic) + node = models[model["depends_on"]["nodes"][0]] + rule = meta["categoria"] + definitions[meta["measure_url"]] = CompositionDefinition( + url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"], + model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"], + dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]}, + **{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}}, + units=_population(metric, model), + category=Category(rule["valor"], rule["sin_dato"], rule["valido"], tuple(rule.get("fechada_en", ())), + tuple(rule.get("conocida_en", ())), tuple(rule["orden"]), rule.get("admite"), + _follow_up(rule.get("seguimiento")), + tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))), + group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), + strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), + ) + return definitions + + +def _follow_up(rule: dict | None) -> FollowUp | None: + if rule is None: + return None + return FollowUp(rule["existe"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())), + tuple(rule["orden"]), rule["sin_seguimiento"]) + + +class CompositionQueries(MeasureQueries): + """Each unit's category in the period, from the latest of its facts, valid ones first.""" + + def __init__(self, definition: CompositionDefinition, question: Question, rule_values: dict, period_table): + super().__init__(definition, question, rule_values, period_table) + c, f = definition.category, definition.category.follow_up + names = [c.value, *c.order, *c.dated_at, *c.known_at, + *((f.exists, *f.order, *f.dated_at, *f.known_at) if f else ()), + *(s.spec["valor"] for s in definition.strata if s.kind == "del_elegido")] + known = {definition.dimensions[n] for n in (*c.known_at, *(f.known_at if f else ()))} + for name in {definition.dimensions[n] for n in names} - set(self.events.c.keys()): + self.events.append_column(column(name, FechaHoraUTC) if name in known else column(name)) + + def _template(self, sql: str): + """A `meta` condition, rendered like a metric's `filter`, with the rules it names bound (a list as `in`).""" + rendered = Environment().from_string(sql).render( + Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}") + names = [n for n in self.values if f":{n}" in rendered] + return text(f"({rendered})").bindparams(*( + bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names)) + + def _value(self): + """The category's value: the column's, or the band its number falls in, by the question's rules.""" + c = self.d.category + if not c.bands: + return self._column(c.value) + number = self._column(c.value) + *bounded, (last, _) = c.bands + return case(*((number < self.values[rule], literal(band)) for band, rule in bounded), else_=literal(last)) + + def _counted(self): + """The follow-up fact of this row exists and was dated and known by the cut-offs.""" + f = self.d.category.follow_up + conditions = [self._column(f.exists).is_not(None)] + if self.q.event_cutoff is not None: + conditions += [self._column(n) <= self.q.event_cutoff.isoformat() for n in f.dated_at] + if self.q.knowledge_cutoff is not None: + conditions += [self._column(n) <= self.q.knowledge_cutoff for n in f.known_at] + return and_(*conditions) + + def _valid(self): + c = self.d.category + conditions = [self._template(c.valid_sql)] + for name in c.dated_at: + conditions.append(self._column(name).is_not(None)) + if self.q.event_cutoff is not None: + conditions.append(self._column(name) <= self.q.event_cutoff.isoformat()) + if self.q.knowledge_cutoff is not None: + conditions += [self._column(name) <= self.q.knowledge_cutoff for name in c.known_at] + return and_(*conditions) + + def latest(self, *, with_strata: bool = False): + """One row per unit: its category (`categoria`) and, with strata, its value of each (`estrato_`).""" + unit = self.events.c[self.d.units.measure_expr] + c, f = self.d.category, self.d.category.follow_up + valid = self._valid() + order = [desc(case((valid, 1), else_=0)), *(desc(self._column(n)) for n in c.order)] + value = self._value() + category = case((valid, value)) + if f is not None: + counted = self._counted() + order += [desc(case((counted, 1), else_=0)), *(desc(self._column(n)) for n in f.order)] + category = case((valid & ~counted, literal(f.none)), (valid, value)) + admitted = valid if c.admits_sql is None else and_(valid, self._template(c.admits_sql)) + where = self._in_question() + units = self._filter(self.d.units) + if units is not None: + where = and_(where, units) + strata = [self.stratum_value(s).label(f"estrato_{s.name}") for s in self.d.strata] if with_strata else [] + ranked = (select(unit.label("unidad"), category.label("categoria"), case((admitted, 1), else_=0).label("admitida"), + *strata, func.row_number().over(partition_by=unit, order_by=order).label("lugar")) + .select_from(self._from(with_strata=with_strata)).where(where).subquery("por_unidad")) + chosen = [ranked.c.lugar == 1] + ([ranked.c.admitida == 1] if c.admits_sql is not None else []) + return (select(ranked.c.unidad, func.coalesce(ranked.c.categoria, c.no_data).label("categoria"), + *(ranked.c[f"estrato_{s.name}"] for s in self.d.strata if with_strata)) + .where(*chosen).subquery("ultima")) + + def category_counts(self) -> Select: + latest = self.latest() + return (select(latest.c.categoria, func.count(distinct(latest.c.unidad))) + .group_by(latest.c.categoria).order_by(latest.c.categoria)) + + def counts_by_stratum(self, stratum: Stratum) -> Select: + latest = self.latest(with_strata=True) + value = latest.c[f"estrato_{stratum.name}"] + return (select(value, latest.c.categoria, func.count(distinct(latest.c.unidad))) + .group_by(value, latest.c.categoria)) + + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: + latest = self.latest(with_strata=True) + (code,) = self.d.units.codes + yield unit_model, select( + literal(report_id).label("report_id"), literal(self.d.group).label("grupo"), + cast(latest.c.unidad, String(64)).label("unidad_id"), + literal(f"{self.d.measure_id}.{code}").label("resultado_id"), + (latest.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"), + latest.c.categoria.label("valor_id"), + ) + for stratum in self.d.strata: + yield stratum_model, select( + literal(report_id).label("report_id"), cast(latest.c.unidad, String(64)).label("unidad_id"), + literal(stratum.name).label("estrato_id"), latest.c[f"estrato_{stratum.name}"].label("estrato_valor"), + ) + + +@dataclasses.dataclass(frozen=True) +class CompositionAnswer: + report_id: int + categories: dict[str, int] + strata: dict[str, dict[str, dict[str, int]]] + stored_before: bool + + @property + def total(self) -> int: + return sum(self.categories.values()) + + +def answer_composition(project: str, definition: CompositionDefinition, question: Question, *, parameters, periods, + history, queries, allow_undecided: bool = False, + now: datetime | None = None) -> CompositionAnswer: + """The stored answer, or a new one: the database ranks each unit's facts, counts and writes the units.""" + values = rule_values(parameters, definition, allow_undecided) + key, key_sha = key_of(definition, question, values) + stored = history.find(definition.url, key_sha) + if stored is not None: + return _from_counts(stored, history.counts(stored)) + + period = periods.get(question.period_id) + if period is None: + raise LookupError(f"dim_periodo has no period {question.period_id!r}") + sql = CompositionQueries(definition, question, values, periods.model.__table__) + _, rows = queries.rows(sql.category_counts()) + categories = {category: n for category, n in rows} + strata = {} + for stratum in definition.strata: + _, cells = queries.rows(sql.counts_by_stratum(stratum)) + for value, category, n in cells: + strata.setdefault(stratum.name, {}).setdefault(value, {})[category] = n + models = import_module(f"core.{project}.indicadores.models") + (any_rule,) = parameters.list(limit=1) + report = models.MeasureReport( + measure_url=definition.url, measure_version=definition.version, + kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha, + parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff, + periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin, + status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), + agregacion_version=AGGREGATION_VERSION, + huella=hashlib.sha256(json.dumps([key_sha, sorted(categories.items()), sorted( + (s, v, c, n) for s, by in strata.items() for v, cs in by.items() for c, n in cs.items())]).encode() + ).hexdigest(), + ) + report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, + models.MeasureReportUnidadEstrato)) + return CompositionAnswer(report_id, categories, strata, stored_before=False) + + +def _from_counts(report_id: int, counts: dict) -> CompositionAnswer: + categories, strata = {}, {} + for (stratum, value, _, category), n in counts.items(): + if stratum == "total": + categories[category] = n + else: + strata.setdefault(stratum, {}).setdefault(value, {})[category] = n + return CompositionAnswer(report_id, categories, strata, stored_before=True) + + +def composition_report(definition: CompositionDefinition, question: Question, result: CompositionAnswer, period, + generated_at: datetime) -> dict: + """The answer as a FHIR R4 `MeasureReport`: the units counted, and a stratifier by category (and by each stratum).""" + (code,) = definition.units.codes + + def stratum(value: str, n: int) -> dict: + return {"value": {"text": value}, "population": [ + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": n}]} + + stratifiers = [{"code": [{"text": definition.category.value}], + "stratum": [stratum(c, n) for c, n in sorted(result.categories.items())]}] + for name, by_value in result.strata.items(): + stratifiers.append({"code": [{"text": name}], + "stratum": [stratum(v, sum(cs.values())) for v, cs in sorted(by_value.items())]}) + group = {"id": definition.group, "population": [ + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.total}, + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": result.total}, + ], "stratifier": stratifiers} + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}] + if question.event_cutoff is not None: + extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()}) + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + return { + "resourceType": "MeasureReport", "status": "complete", "type": "summary", + "measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(), + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, "group": [group], + } diff --git a/webapi/durations.py b/webapi/durations.py new file mode 100644 index 0000000..8c8ff95 --- /dev/null +++ b/webapi/durations.py @@ -0,0 +1,291 @@ +"""A duration answered on request: the days each unit takes from one fact to the next, summarized by quartiles. + +The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring: +continuous-variable` and gives the observation rule (`observacion`): the column with each unit's days, the dates the +cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't passed by the event cut-off isn't +measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in +dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`). + +The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. +""" + +import dataclasses +import hashlib +import json +from collections.abc import Iterable +from datetime import date, datetime, timedelta, timezone +from importlib import import_module +from pathlib import Path + +from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true + +from webapi.metrics import ( + AGGREGATION_VERSION, + EVENT_CUTOFF, + HISTORY_ENTRY, + KNOWLEDGE_CUTOFF, + POPULATION_SYSTEM, + MeasureQueries, + Population, + Question, + _population, + _semantic_model_of, + key_of, + rule_values, +) + +OBSERVATION = "measure-observation" +LOADS = table("carga", column("inicio"), column("fin")) +DAYS = table("dim_fecha", column("fecha"), column("dia_num")) + + +def inclusive_quartiles(values) -> Select: + """(n, q1, median, q3) of a subquery's `numero`, by the inclusive method in ANSI SQL. + + The quartile `q` is at position `(n - 1) q` of the sorted values (from 0), interpolating between its two + neighbors, as `statistics.quantiles(method="inclusive")`; with one value, the three are it. Window functions, + `CAST` and `CASE` only: the same SQL on every engine. + """ + ranked = select(values.c.numero, + (func.row_number().over(order_by=values.c.numero) - 1).label("i"), + func.count().over().label("n")).subquery("ordenados") + cells = [] + for name, q in (("q1", 0.25), ("mediana", 0.5), ("q3", 0.75)): + position = (ranked.c.n - 1) * q + floor = cast(position, Integer) + fraction = position - floor + cells.append((func.sum(case((ranked.c.i == floor, ranked.c.numero * (1 - fraction)), else_=0.0)) + + func.sum(case((ranked.c.i == floor + 1, ranked.c.numero * fraction), else_=0.0))).label(name)) + return select(func.count(ranked.c.numero).label("n"), *cells) + + +@dataclasses.dataclass(frozen=True) +class Observation: + value: str + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + horizon_rule: str | None + start_day: str + horizon_days: int | None = None # a fixed horizon, when the model used the same one to find the next fact + + def horizon(self, values: dict) -> int: + return self.horizon_days if self.horizon_rule is None else values[self.horizon_rule] + + +@dataclasses.dataclass(frozen=True) +class DurationDefinition: + """A duration, shaped so `MeasureQueries` can build its period and cut-offs.""" + + url: str + version: str + metric: str + relation: str + model_checksum: str + time_dimension: str + dimensions: dict[str, str] + units: Population + observation: Observation + group: str + basis: str + rules: dict[str, str] + improvement_notation: str | None = None + strata: tuple = () + + @property + def measure_id(self) -> str: + return self.url.rsplit("/", 1)[-1] + + @property + def numerator(self) -> Population: + return self.units + + @property + def denominator(self) -> Population: + return self.units + + +def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]: + """The simple metrics of the manifest whose `meta` declares a duration, by `measure_url`.""" + m = json.loads(manifest.read_text(encoding="utf-8")) + semantic = {node["name"]: node for node in m["semantic_models"].values()} + models = {node["unique_id"]: node for node in m["nodes"].values()} + definitions = {} + for metric in m["metrics"].values(): + meta = metric["config"].get("meta", {}) + if metric["type"] != "simple" or meta.get("scoring") != "continuous-variable": + continue + model = _semantic_model_of(metric, semantic) + node = models[model["depends_on"]["nodes"][0]] + rule = meta["observacion"] + definitions[meta["measure_url"]] = DurationDefinition( + url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"], + model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"], + dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]}, + **{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}}, + units=_population(metric, model), + observation=Observation(rule["valor"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())), + rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"], + int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None), + group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), + improvement_notation=meta.get("improvement_notation"), + ) + return definitions + + +class DurationQueries(MeasureQueries): + """Each unit of the period: measured or not yet, and its days if it has them.""" + + def __init__(self, definition: DurationDefinition, question: Question, rule_values: dict, period_table): + super().__init__(definition, question, rule_values, period_table) + o = definition.observation + for name in {definition.dimensions[n] for n in (o.value, o.start_day, *o.dated_at)} - set(self.events.c.keys()): + self.events.append_column(column(name)) + + def _has_value(self): + o, q = self.d.observation, self.q + conditions = [self._column(o.value).is_not(None)] + conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at] + if q.knowledge_cutoff is not None: + conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at] + return and_(*conditions) + + def per_unit(self): + """One row per unit in the period: `unidad`, `numero` (its days, or null) and whether it's still `pendiente`.""" + o = self.d.observation + cutoff_day = select(DAYS.c.dia_num).where(DAYS.c.fecha == self.q.event_cutoff.isoformat()).scalar_subquery() + has_value = self._has_value() + pending = and_(not_(has_value), + cutoff_day - self._column(o.start_day) < o.horizon(self.values)) + where = self._in_question() + units = self._filter(self.d.units) + if units is not None: + where = and_(where, units) + unit = self.events.c[self.d.units.measure_expr] + return (select(unit.label("unidad"), case((has_value, self._column(o.value)), else_=null()).label("numero"), + case((pending, 1), else_=0).label("pendiente")) + .select_from(self._from(with_strata=False)).where(where).distinct().subquery("por_unidad")) + + def summary(self) -> Select: + units = self.per_unit() + measured = select(units.c.numero).where(units.c.numero.is_not(None)).subquery("medidos") + quartiles = inclusive_quartiles(measured).subquery("cuartiles") + initial = select(func.count(units.c.unidad).label("inicial")).where(units.c.pendiente == 0).subquery("inicial") + # Two one-row subqueries side by side. + return (select(initial.c.inicial, quartiles.c.n, quartiles.c.q1, quartiles.c.mediana, quartiles.c.q3) + .select_from(initial.join(quartiles, true()))) + + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: + units = self.per_unit() + (initial,) = self.d.units.codes + for code, where, number in ((initial, units.c.pendiente == 0, null()), + (OBSERVATION, units.c.numero.is_not(None), units.c.numero)): + yield unit_model, select( + literal(report_id).label("report_id"), literal(self.d.group).label("grupo"), + cast(units.c.unidad, String(64)).label("unidad_id"), + literal(f"{self.d.measure_id}.{code}").label("resultado_id"), + (units.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"), + cast(number, unit_model.__table__.c.numero.type).label("numero"), + ).where(where) + + +@dataclasses.dataclass(frozen=True) +class DurationAnswer: + report_id: int + initial: int + n: int + q1: float | None + median: float | None + q3: float | None + stored_before: bool + event_cutoff: date | None = None # the one it was computed at: the question's, or the last load's day + + @property + def excluded(self) -> int: + return self.initial - self.n + + +def last_load_day(queries) -> date | None: + """The day of the latest load: its `fin`, or its `inicio` if it didn't finish.""" + _, ((last,),) = queries.rows(select(func.max(func.coalesce(LOADS.c.fin, LOADS.c.inicio)))) + return None if last is None else date.fromisoformat(str(last)[:10]) + + +def answer_duration(project: str, definition: DurationDefinition, question: Question, *, parameters, periods, + history, queries, allow_undecided: bool = False, now: datetime | None = None) -> DurationAnswer: + """The stored answer, or a new one: the database decides each unit, counts, takes the quartiles and stores.""" + if question.event_cutoff is None: + question = dataclasses.replace(question, event_cutoff=last_load_day(queries)) + values = rule_values(parameters, definition, allow_undecided) + if definition.observation.horizon_rule is None: + values["horizonte_dias"] = definition.observation.horizon_days + key, key_sha = key_of(definition, question, values) + models = import_module(f"core.{project}.indicadores.models") + stored = history.find(definition.url, key_sha) + if stored is not None: + return dataclasses.replace(_from_stored(definition, stored, queries, models.MeasureReportUnidad), + event_cutoff=question.event_cutoff) + + period = periods.get(question.period_id) + if period is None: + raise LookupError(f"dim_periodo has no period {question.period_id!r}") + sql = DurationQueries(definition, question, values, periods.model.__table__) + _, ((initial, n, q1, median, q3),) = queries.rows(sql.summary()) + (any_rule,) = parameters.list(limit=1) + report = models.MeasureReport( + measure_url=definition.url, measure_version=definition.version, + kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha, + parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff, + periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin, + status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), + agregacion_version=AGGREGATION_VERSION, + huella=hashlib.sha256(json.dumps([key_sha, initial, n, q1, median, q3]).encode()).hexdigest(), + ) + report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, + models.MeasureReportUnidadEstrato)) + return DurationAnswer(report_id, initial, n, *_numbers(n, q1, median, q3), stored_before=False, + event_cutoff=question.event_cutoff) + + +def _numbers(n, q1, median, q3): + return (None, None, None) if not n else (float(q1), float(median), float(q3)) + + +def _from_stored(definition: DurationDefinition, report_id: int, queries, unit_model) -> DurationAnswer: + """A stored duration read back from its units: the initial ones counted, the quartiles of their days.""" + u = unit_model.__table__.c + initial = f"{definition.measure_id}.{definition.units.codes[0]}" + observed = select(u.numero).where(u.report_id == report_id, u.resultado_id == f"{definition.measure_id}.{OBSERVATION}") + _, ((n, q1, median, q3),) = queries.rows(inclusive_quartiles(observed.subquery("medidos"))) + _, ((count,),) = queries.rows(select(func.count()).where(u.report_id == report_id, u.resultado_id == initial)) + return DurationAnswer(report_id, count, n, *_numbers(n, q1, median, q3), stored_before=True) + + +def duration_report(definition: DurationDefinition, question: Question, result: DurationAnswer, period, + generated_at: datetime) -> dict: + """The answer as a FHIR R4 `MeasureReport`: the units measurable and measured, the median as the score, and the + quartiles as its components.""" + group = {"id": definition.group, "population": [ + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.initial}, + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": OBSERVATION}]}, "count": result.n}, + ]} + if result.median is not None: + group["measureScore"] = {"value": result.median, "unit": "d", + "extension": [{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", + "valueDecimal": result.q1}, + {"url": "https://isssteleon.org/fhir/StructureDefinition/q3", + "valueDecimal": result.q3}]} + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}, + {"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or question.event_cutoff).isoformat()}] + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + report = { + "resourceType": "MeasureReport", "status": "complete", "type": "summary", + "measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(), + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, "group": [group], + } + if definition.improvement_notation: + report["improvementNotation"] = {"coding": [{ + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": definition.improvement_notation}]} + return report diff --git a/webapi/indicadores.py b/webapi/indicadores.py deleted file mode 100644 index f1fe055..0000000 --- a/webapi/indicadores.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA). - -`registrar_indicadores` agrega a un blueprint: - - GET /indicadores catálogo de indicadores (con sus `filtros`) - GET /indicadores//periodos periodos con reporte - GET /indicadores//datos?periodos=&estrato=&filtro= los números, sin figura - GET /indicadores//metadatos ficha metodológica - GET /indicadores//figuras/?periodos=&tema=&filtro= - -Las definiciones salen del kit (`measures_de`), los datos de -`indicadores_kit.serving.datos` y las figuras de -`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y -se traducen los errores a códigos HTTP. La forma de cada respuesta es un -contrato con el frontend: no se quita ni se renombra un campo. - -`?filtro=estrato:valor[,estrato:valor]` (T-19f) cuenta lo mismo solo con las -unidades que tienen esos valores: el mismo contrato, y en `/datos` la llave -`filtros`. Solo se aceptan los filtros que el indicador declara -(`extension.filtros`) y los valores de su catálogo; si no, 400. -""" - -import json -import re -from collections.abc import Callable - -from flask import Blueprint, Response, jsonify, request -from indicadores_kit.registry.measures import Measure, measures_de -from indicadores_kit.serving.contratos import FiltroNoDeclarado -from indicadores_kit.serving.datos import datos_de, filtros_de, metadatos_de, periodos_de, resumen_de -from indicadores_kit.serving.figuras import ( - TEMAS, - figura_json, - figuras_de, - periodos_con_reporte, - periodos_por_defecto, -) -from indicadores_kit.tablas import tablas_de -from sqlmodel import Session - -# Cómo se escribe un periodo de cada tipo (`registry/periodos.py`) y un ejemplo para el mensaje. -FORMATOS = { - "dia": (re.compile(r"\d{4}-\d{2}-\d{2}"), "AAAA-MM-DD"), - "semana_epidemiologica": (re.compile(r"\d{4}-SE\d{2}"), "AAAA-SEnn"), - "semana_habil": (re.compile(r"\d{4}-SH\d{2}"), "AAAA-SHnn"), - "semana_iso": (re.compile(r"\d{4}-W\d{2}"), "AAAA-Wnn"), - "mes": (re.compile(r"\d{4}-\d{2}"), "AAAA-MM"), - "bimestre": (re.compile(r"\d{4}-B[1-6]"), "AAAA-B1 a AAAA-B6"), - "trimestre": (re.compile(r"\d{4}-T[1-4]"), "AAAA-T1 a AAAA-T4"), - "semestre": (re.compile(r"\d{4}-S[12]"), "AAAA-S1 o AAAA-S2"), -} - - -def _error(mensaje: str, codigo: int): - return jsonify({"error": mensaje}), codigo - - -def _json(contenido) -> Response: - """Sin `jsonify`, que ordena las llaves: grupos y categorías van en su orden de presentación.""" - return Response(json.dumps(contenido, ensure_ascii=False), mimetype="application/json") - - -def _tipo_de(periodo: str, tipos: list[str]) -> str | None: - """El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`).""" - return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None) - - -def filtros_pedidos(texto: str | None) -> dict[str, str]: - """`estrato:valor[,estrato:valor]` -> `{estrato: valor}`. Vacío si no se pidió; `ValueError` si viene mal escrito.""" - if not texto: - return {} - filtros = {} - for parte in texto.split(","): - estrato, separador, valor = parte.partition(":") - if not separador or not estrato or not valor: - raise ValueError(f"filtro mal escrito {parte!r}; use estrato:valor") - if estrato in filtros: - raise ValueError(f"el filtro {estrato!r} va dos veces") - filtros[estrato] = valor - return filtros - - -def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]: - """Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`. - - Raises: - ValueError: un periodo mal formado, de un tipo que el indicador no - publica (`extension.publicacion.tipos_periodo`), o de tipos mezclados. - """ - if not texto: - return [], None - tipos = medida.extension.publicacion.tipos_periodo - periodos = list(dict.fromkeys(texto.split(","))) - encontrados = {_tipo_de(periodo, tipos) for periodo in periodos} - if None in encontrados: - formatos = "; ".join(FORMATOS[tipo][1] for tipo in tipos) - raise ValueError(f"Periodos mal formados: {texto!r}; este indicador publica {formatos}.") - if len(encontrados) > 1: - raise ValueError(f"Periodos de tipos distintos: {texto!r}; pida un solo tipo a la vez.") - return periodos, encontrados.pop() - - -def registrar_indicadores( - blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session] -) -> None: - """Agrega las rutas de indicadores de `proyecto` al blueprint. - - `get_session` es la fábrica de `Persistance` (`get__session`): - se llama en cada petición, no al registrar. - """ - definiciones = measures_de(proyecto) # fijas: se leen una vez - tablas = tablas_de(proyecto) - - def listar_indicadores(): - # Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo. - # `filtros` (T-24f): los que admite cada uno, con sus valores del catálogo, para armar `?filtro=`. - sesion = get_session() - try: - return _json([ - {**resumen_de(id_, medida), "filtros": filtros_de(sesion, medida)} - for id_, medida in definiciones.items() - if not medida.extension.publicacion.oculto - ]) - finally: - sesion.close() - - def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]: - """Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica.""" - if periodos: - return periodos - tipo = medida.extension.publicacion.tipos_periodo[0] - return periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo) - - def get_periodos(indicador: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - sesion = get_session() - try: - periodos = periodos_de(sesion, medida, tablas=tablas) - finally: - sesion.close() - return _json({"id": indicador, "version": medida.version, "periodos": periodos}) - - def get_metadatos(indicador: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - sesion = get_session() - try: - metadatos = metadatos_de(sesion, medida, tablas=tablas) - finally: - sesion.close() - return _json({"id": indicador, **metadatos}) - - def get_datos(indicador: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - estrato = request.args.get("estrato") or None - if estrato is not None and estrato not in medida.extension.estratos: - return _error( - f"estrato desconocido {estrato!r}; este indicador tiene {medida.extension.estratos}", - 400, - ) - try: - periodos, _ = periodos_pedidos(request.args.get("periodos"), medida) - filtros = filtros_pedidos(request.args.get("filtro")) - except ValueError as error: - return _error(str(error), 400) - - sesion = get_session() - try: - periodos = _periodos_o_los_que_haya(sesion, medida, periodos) - if not periodos: - return _error("el indicador no tiene reportes calculados", 404) - datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato, filtros=filtros or None) - except FiltroNoDeclarado as error: - return _error(str(error), 400) - except KeyError: - # KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte. - raise - except LookupError as error: - return _error(str(error), 404) - finally: - sesion.close() - return _json({"id": indicador, **datos}) - - def get_figura(indicador: str, figura: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - if figura not in figuras_de(medida): - return _error( - f"figura {figura!r} no es del contrato {medida.extension.contrato}", 404 - ) - - tema = request.args.get("tema", "claro") - if tema not in TEMAS: - return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400) - try: - periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida) - filtros = filtros_pedidos(request.args.get("filtro")) - except ValueError as error: - return _error(str(error), 400) - - sesion = get_session() - try: - # Sin pedir ninguno: todos, o solo el más reciente si la figura se lee en un periodo. - periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas) - if not periodos: - return _error("el indicador no tiene reportes calculados", 404) - texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros or None) - except FiltroNoDeclarado as error: - return _error(str(error), 400) - except KeyError: - # KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte. - raise - except LookupError as error: - return _error(str(error), 404) - finally: - sesion.close() - return Response(texto, mimetype="application/json") - - blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores) - blueprint.add_url_rule("/indicadores//periodos", "get_periodos", get_periodos) - blueprint.add_url_rule("/indicadores//datos", "get_datos", get_datos) - blueprint.add_url_rule("/indicadores//metadatos", "get_metadatos", get_metadatos) - blueprint.add_url_rule( - "/indicadores//figuras/", "get_figura", get_figura - ) diff --git a/webapi/indicadores_vivos.py b/webapi/indicadores_vivos.py index ee6b0e8..0b38ccc 100644 --- a/webapi/indicadores_vivos.py +++ b/webapi/indicadores_vivos.py @@ -26,7 +26,7 @@ from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message -DOMINIOS = ("cacu", "cama", "tea") +DOMINIOS = ("cacu", "cama") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) diff --git a/webapi/kpis.py b/webapi/kpis.py new file mode 100644 index 0000000..abf497e --- /dev/null +++ b/webapi/kpis.py @@ -0,0 +1,111 @@ +"""`GET //indicadores/`: a measure's periods answered on request, as a FHIR `Bundle` of `MeasureReport`s. + +Query: `periodos` (comma-separated `dim_periodo` ids, required), `corte_evento` (`YYYY-MM-DD`, optional: facts dated +after it don't count) and `corte_conocimiento` (ISO date-time, optional: facts known after it don't count; by default +the start of the last load, so the same question asked before the next load reads the stored answer). The definitions +come from dbt's manifest (`DBT_MANIFEST`): proportions (`webapi.metrics`), compositions (`webapi.compositions`) and +durations (`webapi.durations`; without `corte_evento`, the day of the last load). +""" + +import json +from collections.abc import Callable +from datetime import date, datetime, timezone +from pathlib import Path + +from core.indicadores.tipos import FechaHoraUTC +from flask import Blueprint, Response, jsonify, request +from sqlalchemy import column, func, select, table + +from webapi.compositions import CompositionDefinition, answer_composition, composition_definitions, composition_report +from webapi.durations import DurationDefinition, answer_duration, duration_definitions, duration_report +from webapi.metrics import Question, UndecidedRule, answer, measure_definitions, measure_report + +LOADS = table("carga", column("inicio", FechaHoraUTC)) + + +def definitions_of(project: str, manifest: Path) -> dict: + """Every measure the manifest defines for the domain, by its id (the end of its url).""" + every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)} + return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")} + + +def kpis_blueprint(project: str, repositories, manifest: Path, *, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: + """The blueprint of a domain, to register with `url_prefix="/"`. `repositories` is the domain's + `persistance.` module.""" + blueprint = Blueprint(f"{project}_kpis", __name__) + definitions = definitions_of(project, manifest) + + @blueprint.get("/indicadores") + def list_kpis(): + """The measures answered on request: id, url, version and scoring.""" + return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)} + for i, d in sorted(definitions.items())]) + + @blueprint.get("/indicadores/") + def get_kpi(measure_id: str): + """A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history.""" + definition = definitions.get(measure_id) + if definition is None: + return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404 + try: + periods = [p for p in request.args.get("periodos", "").split(",") if p] + if not periods: + raise ValueError("falta `periodos`") + event_cutoff = _date(request.args.get("corte_evento")) + knowledge_cutoff = _datetime(request.args.get("corte_conocimiento")) or _last_load(repositories) + except ValueError as error: + return jsonify({"error": str(error)}), 400 + ask, serialize = ANSWERS[scoring_of(definition)] + entries = [] + for period_id in periods: + period = repositories.dim_periodo_repository.get(period_id) + if period is None: + return jsonify({"error": f"no hay un periodo {period_id!r}"}), 404 + question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff) + try: + result = ask(project, definition, question, parameters=repositories.def_parametro_repository, + periods=repositories.dim_periodo_repository, history=repositories.history_repository, + queries=repositories.dbt_query_repository) + except UndecidedRule as error: + return jsonify({"error": str(error)}), 409 + entries.append({"resource": serialize(definition, question, result, period, now())}) + bundle = {"resourceType": "Bundle", "type": "searchset", "total": len(entries), "entry": entries} + return Response(json.dumps(bundle, ensure_ascii=False), mimetype="application/fhir+json") + + return blueprint + + +ANSWERS = {"proportion": (answer, measure_report), "composition": (answer_composition, composition_report), + "continuous-variable": (answer_duration, duration_report)} + + +def scoring_of(definition) -> str: + if isinstance(definition, CompositionDefinition): + return "composition" + return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion" + + +def _date(value: str | None) -> date | None: + if not value: + return None + try: + return date.fromisoformat(value) + except ValueError: + raise ValueError(f"`corte_evento` no es una fecha AAAA-MM-DD: {value!r}") from None + + +def _datetime(value: str | None) -> datetime | None: + if not value: + return None + try: + moment = datetime.fromisoformat(value) + except ValueError: + raise ValueError(f"`corte_conocimiento` no es una fecha y hora ISO: {value!r}") from None + return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc) + + +def _last_load(repositories) -> datetime | None: + """The start of the domain's last load: what's known now, and stable until the next load.""" + _, ((last,),) = repositories.dbt_query_repository.rows(select(func.max(LOADS.c.inicio))) + return last diff --git a/webapi/metrics.py b/webapi/metrics.py new file mode 100644 index 0000000..23b3574 --- /dev/null +++ b/webapi/metrics.py @@ -0,0 +1,502 @@ +"""A measure answered on request: the question carries the period and both cut-offs, the definition is dbt's. + +The definition lives in dbt's semantic layer (`manifest.json`): a semantic model over an event-grain model (one row +per fact, with its date and when it became known), simple metrics for each population and a `ratio` metric whose +`meta` holds the rest of the measure, its strata included. dbt validates it; nothing here runs MetricFlow, which +doesn't support the project's engines. What runs instead is the small part of it these measures use: +`count_distinct` measures with a categorical filter, over a period of `dim_periodo`, broken down by strata, as +SQLAlchemy Core so every engine gets its own SQL. + +A question is a measure, a period, an event cut-off (facts dated after it don't count) and a knowledge cut-off (facts +known after it don't count). Its answer is stored once (`MeasureHistoryRepository`); asking again reads it. The +database counts and writes the units and their strata; only the counts reach Python. +""" + +import dataclasses +import hashlib +import json +from collections.abc import Callable, Iterable +from datetime import date, datetime, timedelta, timezone +from importlib import import_module +from pathlib import Path + +from core.indicadores.tipos import FechaHoraUTC +from jinja2 import Environment +from sqlalchemy import ( + Select, + String, + and_, + bindparam, + case, + cast, + column, + distinct, + func, + literal, + or_, + select, + table, + text, +) + +AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read +TOTAL = "total" +NO_DATA = "sin_dato" +AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo" +TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" +OF_THE_CHOSEN = "del_elegido" + + +class UndecidedRule(ValueError): + """A rule a measure needs is still `sin_definir`.""" + + +@dataclasses.dataclass(frozen=True) +class Population: + """A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates. + + `dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the + dates the knowledge cut-off applies to. + """ + + metric: str + measure_expr: str + filter_sql: str | None + codes: tuple[str, ...] + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + + +@dataclasses.dataclass(frozen=True) +class Stratum: + """A breakdown of the measure, as its `meta.estratos` entry declares it. `kind` says how its value is computed: + + - `edad_al_inicio_del_periodo`: the age group at the period's start, from the model's `nacimiento` column; + - `linea_de_tiempo_al_inicio_del_periodo`: what the patient's timeline (`linea`, a model with `pac_id`, `tipo`, + `fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose + condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a + timeline `tipo` to whether there was one; + - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category. + """ + + name: str + kind: str + spec: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) + + @property + def birth(self) -> str: + return self.spec["nacimiento"] + + @classmethod + def of(cls, name: str, spec: dict) -> "Stratum": + if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN): + raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered") + return cls(name, spec["tipo"], spec) + + +@dataclasses.dataclass(frozen=True) +class MeasureDefinition: + """A `ratio` metric with its numerator and denominator, the event model they count over, and its `meta`.""" + + url: str + version: str + metric: str + relation: str + model_checksum: str + time_dimension: str + dimensions: dict[str, str] + numerator: Population + denominator: Population + group: str + basis: str + rules: dict[str, str] + strata: tuple[Stratum, ...] + improvement_notation: str | None = None + + @property + def measure_id(self) -> str: + return self.url.rsplit("/", 1)[-1] + + +def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]: + """The ratio metrics of the manifest that declare a `measure_url`, by that url.""" + m = json.loads(manifest.read_text(encoding="utf-8")) + metrics = {node["name"]: node for node in m["metrics"].values()} + semantic = {node["name"]: node for node in m["semantic_models"].values()} + models = {node["unique_id"]: node for node in m["nodes"].values()} + definitions = {} + for metric in metrics.values(): + meta = metric["config"].get("meta", {}) + if metric["type"] != "ratio" or "measure_url" not in meta: + continue + params = metric["type_params"] + numerator, denominator = metrics[params["numerator"]["name"]], metrics[params["denominator"]["name"]] + model = _semantic_model_of(numerator, semantic) + node = models[model["depends_on"]["nodes"][0]] + definitions[meta["measure_url"]] = MeasureDefinition( + url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], + relation=node["alias"], model_checksum=node["checksum"]["checksum"], + time_dimension=model["defaults"]["agg_time_dimension"], + dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]}, + **{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}}, + numerator=_population(numerator, model), denominator=_population(denominator, model), + group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), + strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), + improvement_notation=meta.get("improvement_notation"), + ) + return definitions + + +def _semantic_model_of(metric: dict, semantic: dict) -> dict: + measure = metric["type_params"]["measure"]["name"] + for model in semantic.values(): + if any(m["name"] == measure for m in model["measures"]): + return model + raise LookupError(f"no semantic model has the measure {measure!r} of {metric['name']}") + + +def _population(metric: dict, model: dict) -> Population: + measure_name = metric["type_params"]["measure"]["name"] + (measure,) = [m for m in model["measures"] if m["name"] == measure_name] + if measure["agg"] != "count_distinct": + raise NotImplementedError(f"{metric['name']}: only count_distinct measures are answered, not {measure['agg']}") + filters = (metric.get("filter") or {}).get("where_filters", []) + meta = metric["config"].get("meta", {}) + return Population( + metric=metric["name"], measure_expr=measure["expr"] or measure["name"], + filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None, + codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())), + known_at=tuple(meta.get("conocida_en", ())), + ) + + +# --- the question and its SQL ---------------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class Question: + """What is asked: a measure in a period, with what was dated and known up to the cut-offs.""" + + measure_url: str + period_id: str + event_cutoff: date | None = None + knowledge_cutoff: datetime | None = None + + +DIM_FECHA = ("fecha", "anio", "mes", "dia") +DIM_GRUPO_EDAD = ("etiqueta", "edad_min", "edad_max") + + +class MeasureQueries: + """The SQL of one definition for one question: counts per population and stratum, and the rows to store.""" + + def __init__(self, definition: MeasureDefinition, question: Question, rule_values: dict, period_table): + self.d, self.q, self.values = definition, question, rule_values + names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr} + # When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in. + known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at} + for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)): + known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())} + self.events = table(definition.relation, *( + column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) + if name.isidentifier())) + self.periods = period_table + self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") + self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio") + self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD)) + self._timelines: dict[str, object] = {} + + def _column(self, dimension: str): + return self.events.c[self.d.dimensions[dimension]] + + def _filter(self, population: Population): + conditions = [] + if population.filter_sql: + rendered = Environment().from_string(population.filter_sql).render( + Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}") + names = [n for n in self.values if f":{n}" in rendered] + conditions.append(text(rendered).bindparams(*( + bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names))) + if self.q.event_cutoff is not None: + conditions += [self._column(name) <= self.q.event_cutoff.isoformat() for name in population.dated_at] + conditions += [self._column(name).is_not(None) for name in population.dated_at] + if self.q.knowledge_cutoff is not None: + conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at] + conditions += [self._column(name).is_not(None) for name in population.known_at] + return and_(*conditions) if conditions else None + + def _in_question(self): + when, p = self.events.c[self.d.time_dimension], self.periods.c + conditions = [p.periodo_id == self.q.period_id] + if self.q.event_cutoff is not None: + conditions.append(when <= self.q.event_cutoff.isoformat()) + return and_(*conditions) + + def _from(self, *, with_strata: bool): + when, p = self.events.c[self.d.time_dimension], self.periods.c + joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin)) + if not with_strata: + return joined + for stratum in self.d.strata: + if stratum.kind == OF_THE_CHOSEN: + continue + if stratum.kind == AGE_AT_PERIOD_START: + joined = (joined + .join(self.start_day, self.start_day.c.fecha == p.inicio) + .outerjoin(self.birth_day, self.birth_day.c.fecha == self._column(stratum.birth)) + .outerjoin(self.age_groups, and_(self._age() >= self.age_groups.c.edad_min, + self._age() <= self.age_groups.c.edad_max))) + else: + had = self._timeline(stratum) + joined = joined.outerjoin(had, had.c.pac_id == self._column("paciente")) + return joined + + def _timeline(self, stratum: Stratum): + """Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start. + + Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped + by on every engine. + """ + if stratum.name in self._timelines: + return self._timelines[stratum.name] + kinds = sorted({k for v in stratum.spec["valores"] for alternative in v["si"] for k in alternative}) + line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"), + column("conocida_en", FechaHoraUTC)) + period = self.periods.alias(f"periodo_{stratum.name}") + conditions = [line.c.tipo.in_(kinds), line.c.fecha < period.c.inicio] + if self.q.knowledge_cutoff is not None: + conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff) + had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds)) + .select_from(line.join(period, period.c.periodo_id == self.q.period_id)) + .where(*conditions).group_by(line.c.pac_id).subquery(f"linea_{stratum.name}")) + self._timelines[stratum.name] = had + return had + + def _age(self): + """Completed years at the period's start, from the parts of `dim_fecha`: no engine date functions.""" + start, birth = self.start_day.c, self.birth_day.c + not_yet = or_(start.mes < birth.mes, and_(start.mes == birth.mes, start.dia < birth.dia)) + return start.anio - birth.anio - case((not_yet, 1), else_=0) + + def stratum_value(self, stratum: Stratum): + if stratum.kind == AGE_AT_PERIOD_START: + return func.coalesce(self.age_groups.c.etiqueta, NO_DATA) + if stratum.kind == OF_THE_CHOSEN: + return self._column(stratum.spec["valor"]) + had = self._timeline(stratum).c + + def holds(alternative: dict): + return and_(*(func.coalesce(had[k], 0) == (1 if wanted else 0) for k, wanted in alternative.items())) + + return case(*((or_(*map(holds, v["si"])), literal(v["valor"])) for v in stratum.spec["valores"]), + else_=literal(stratum.spec["resto"])) + + def _cells(self): + unit = self.events.c[self.d.numerator.measure_expr] + for name, population in (("numerator", self.d.numerator), ("denominator", self.d.denominator)): + condition = self._filter(population) + counted = unit if condition is None else case((condition, unit)) + yield func.count(distinct(counted)).label(name) + + def counts(self) -> Select: + return select(*self._cells()).select_from(self._from(with_strata=False)).where(self._in_question()) + + def counts_by_stratum(self, stratum: Stratum) -> Select: + value = self.stratum_value(stratum).label("valor") + return (select(value, *self._cells()).select_from(self._from(with_strata=True)) + .where(self._in_question()).group_by(value)) + + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: + """What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum.""" + for population in (self.d.denominator, self.d.numerator): + unit = self.events.c[population.measure_expr] + condition = self._filter(population) + where = self._in_question() if condition is None else and_(self._in_question(), condition) + for code in population.codes: + yield unit_model, (select( + literal(report_id).label("report_id"), literal(self.d.group).label("grupo"), + cast(unit, String(64)).label("unidad_id"), + literal(f"{self.d.measure_id}.{code}").label("resultado_id"), + (unit if self.d.basis == "paciente" else literal(None)).label("pac_id"), + ).select_from(self._from(with_strata=False)).where(where).distinct()) + unit = self.events.c[self.d.denominator.measure_expr] + condition = self._filter(self.d.denominator) + where = self._in_question() if condition is None else and_(self._in_question(), condition) + for stratum in self.d.strata: + yield stratum_model, (select( + literal(report_id).label("report_id"), cast(unit, String(64)).label("unidad_id"), + literal(stratum.name).label("estrato_id"), self.stratum_value(stratum).label("estrato_valor"), + ).select_from(self._from(with_strata=True)).where(where).distinct()) + + +# --- answering --------------------------------------------------------------------------------------------------------- + + +def rule_values(parameters, definition: MeasureDefinition, allow_undecided: bool = False) -> dict: + values = {} + for name, rule in definition.rules.items(): + row = parameters.get(rule) + if row is None: + raise KeyError(f"{definition.url}: there's no rule {rule!r} in def_parametro") + if row.estado == "sin_definir" and not allow_undecided: + raise UndecidedRule(f"{definition.url}: the rule {rule!r} is undecided ({row.fuente})") + values[name] = json.loads(row.valor) + return values + + +def key_of(definition: MeasureDefinition, question: Question, values: dict) -> tuple[str, str]: + """The full key of a question, as JSON, and its hash.""" + key = json.dumps({ + "measure": definition.url, "version": definition.version, "metric": definition.metric, + "periodo": question.period_id, + "corte_evento": question.event_cutoff.isoformat() if question.event_cutoff else None, + "corte_conocimiento": question.knowledge_cutoff.isoformat() if question.knowledge_cutoff else None, + "sql": values, "estratos": {s.name: s.spec for s in definition.strata}, + }, sort_keys=True, ensure_ascii=False) + return key, hashlib.sha256(key.encode("utf-8")).hexdigest() + + +@dataclasses.dataclass(frozen=True) +class Counts: + numerator: int + denominator: int + + @property + def proportion(self) -> float | None: + return self.numerator / self.denominator if self.denominator else None + + +@dataclasses.dataclass(frozen=True) +class Answer: + report_id: int + total: Counts + strata: dict[str, dict[str, Counts]] + stored_before: bool + + @property + def numerator(self) -> int: + return self.total.numerator + + @property + def denominator(self) -> int: + return self.total.denominator + + @property + def proportion(self) -> float | None: + return self.total.proportion + + +def answer(project: str, definition: MeasureDefinition, question: Question, *, parameters, periods, history, + queries, allow_undecided: bool = False, now: datetime | None = None) -> Answer: + """The stored answer to the question, or a new one computed by the database and stored. + + `parameters`, `periods`, `history` and `queries` are the domain's repositories (`def_parametro`, `dim_periodo`, + `MeasureHistoryRepository`, `DbtQueryRepository`). A stored answer is read back from its units' counts. + """ + values = rule_values(parameters, definition, allow_undecided) + key, key_sha = key_of(definition, question, values) + stored = history.find(definition.url, key_sha) + if stored is not None: + return _from_counts(definition, stored, history.counts(stored)) + + period = periods.get(question.period_id) + if period is None: + raise LookupError(f"dim_periodo has no period {question.period_id!r}") + sql = MeasureQueries(definition, question, values, periods.model.__table__) + _, ((numerator, denominator),) = queries.rows(sql.counts()) + strata = {} + for stratum in definition.strata: + _, cells = queries.rows(sql.counts_by_stratum(stratum)) + strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells} + models = import_module(f"core.{project}.indicadores.models") + (any_rule,) = parameters.list(limit=1) + report = models.MeasureReport( + measure_url=definition.url, measure_version=definition.version, + kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha, + parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff, + periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin, + status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), + agregacion_version=AGGREGATION_VERSION, + huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted( + (s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode() + ).hexdigest(), + ) + report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, + models.MeasureReportUnidadEstrato)) + return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False) + + +def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer: + numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0], + definition.denominator.codes[0])) + cells: dict[tuple[str, str], list[int]] = {} + for (stratum, value, resultado, _), n in counts.items(): + cell = cells.setdefault((stratum, value), [0, 0]) + if resultado == numerator: + cell[0] = n + elif resultado == denominator: + cell[1] = n + strata: dict[str, dict[str, Counts]] = {} + for (stratum, value), (n, d) in cells.items(): + if stratum != TOTAL: + strata.setdefault(stratum, {})[value] = Counts(n, d) + return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True) + + +# --- the contract -------------------------------------------------------------------------------------------------- + +POPULATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-population" +EVENT_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-evento" +KNOWLEDGE_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento" +HISTORY_ENTRY = "https://isssteleon.org/fhir/StructureDefinition/reporte-id" + + +def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]: + by_code = {**{code: counts.denominator for code in definition.denominator.codes}, + **{code: counts.numerator for code in definition.numerator.codes}} + return [{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": count} + for code, count in by_code.items()] + + +def _scored(entry: dict, counts: Counts) -> dict: + if counts.proportion is not None: + entry["measureScore"] = {"value": counts.proportion} + return entry + + +def measure_report(definition: MeasureDefinition, question: Question, result: Answer, period, + generated_at: datetime) -> dict: + """The answer as a FHIR R4 `MeasureReport` (summary): one group, its populations, its score and its strata. + + The cut-offs aren't FHIR elements: they go as extensions of the report, with the history entry it was read from. + """ + group = _scored({"id": definition.group, "population": _populations(definition, result.total)}, result.total) + if result.strata: + group["stratifier"] = [ + {"code": [{"text": name}], "stratum": [ + _scored({"value": {"text": value}, "population": _populations(definition, counts)}, counts) + for value, counts in sorted(values.items())]} + for name, values in result.strata.items() + ] + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}] + if question.event_cutoff is not None: + extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()}) + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + report = { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": f"{definition.url}|{definition.version}", + "date": generated_at.isoformat(), + # FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`. + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, + "group": [group], + } + if definition.improvement_notation: + report["improvementNotation"] = {"coding": [{ + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": definition.improvement_notation}]} + return report + diff --git a/webapi/orquestacion/__main__.py b/webapi/orquestacion/__main__.py index e84aa1e..f970967 100644 --- a/webapi/orquestacion/__main__.py +++ b/webapi/orquestacion/__main__.py @@ -15,7 +15,7 @@ from pathlib import Path from webapi.orquestacion.contexto import Contexto from webapi.orquestacion.ejecutor import correr -PROYECTOS = ("cacu", "cama", "tea") +PROYECTOS = ("cacu", "cama") def main(argv: list[str] | None = None) -> None: diff --git a/webapi/orquestacion/ciclo.py b/webapi/orquestacion/ciclo.py index 3989b80..3ac515f 100644 --- a/webapi/orquestacion/ciclo.py +++ b/webapi/orquestacion/ciclo.py @@ -11,38 +11,36 @@ Bronce lo escribe la ingesta, fuera del ciclo. """ import logging -from datetime import date +from datetime import date, datetime from functools import partial from importlib import import_module from pathlib import Path from hamilton.function_modifiers import config from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata -from indicadores_kit.esquema import ddl_de_vistas -from indicadores_kit.oro.calculo import fecha_de_ultima_carga, medir_con_unidades from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado from indicadores_kit.oro.cohortes.definicion import leer_definicion from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging from indicadores_kit.plata.periodo_observacion import periodos_de_observacion +from indicadores_kit.plata.vistas import ddl_de_vistas as ddl_de_v_persona from indicadores_kit.registry.apoyo import ( CLAVE_DIM_FECHA_DESDE, filas_de_dim_fecha, grupos_de_edad_de, ) from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.registry.measures import measures_de, rutas_de_measures from indicadores_kit.registry.parametros import ( RUTA_PARAMETROS, leer_parametros, valores_del_archivo, ) from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.registry.publicacion import semillas_de from indicadores_kit.tablas import tablas_de from persistance.aristas.plata import guardar_carga_en -from sqlmodel import SQLModel, select +from sqlmodel import SQLModel, func, select from webapi.orquestacion.contexto import Contexto +from webapi.orquestacion.semantic_layer import catalog_layers, event_views from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo registro_de_eventos = logging.getLogger(__name__) @@ -93,8 +91,8 @@ def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel: def vistas(cargar: SQLModel, ctx: Contexto) -> int: - """Las vistas de versión vigente y las del proyecto: la DDL la arma el kit y la corre el repositorio.""" - return len(ctx.repos.plata.vistas.construir(ddl_de_vistas(ctx.proyecto))) + """`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base.""" + return len(ctx.repos.plata.vistas.construir(ddl_de_v_persona(tablas_de(ctx.proyecto).Persona))) def registro(migrar: str, ctx: Contexto) -> list[str]: @@ -106,7 +104,7 @@ def registro(migrar: str, ctx: Contexto) -> list[str]: de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `.grupos_edad`, si el proyecto los tiene (TEA no). """ - tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto) + tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto, _manifest(ctx)) ruta = ctx.parametros or RUTA_PARAMETROS parametros = leer_parametros(ruta, tablas=tablas) periodos = periodos_de_tipos(tipos, ctx.anio_inicio, ctx.anio_fin, tablas=tablas) @@ -132,35 +130,26 @@ def _cubre(fechas, desde: date, hasta: date) -> bool: def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]: - """Las definiciones del proyecto -> el catálogo de publicación de §6f (`cat_measure*`, `cat_estrato*`). + """The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest. - Se sincroniza: lo que una unidad de un reporte usa no se borra (T-19b). Se leen y validan todos los - archivos antes de escribir: uno inválido no toca las tablas. + It's synchronized: what a report's unit uses isn't deleted. """ - tablas, rutas = tablas_de(ctx.proyecto), rutas_de_measures(ctx.proyecto) - semillas = semillas_de(ctx.proyecto, rutas, valores_del_archivo(ctx.parametros or RUTA_PARAMETROS), tablas=tablas) - return {"definiciones": len(semillas.measures), **ctx.repos.oro.publicacion.sincronizar(semillas.por_capas())} + capas = catalog_layers(ctx.proyecto, _manifest(ctx)) + return {"definiciones": len(capas[0]), **ctx.repos.oro.publicacion.sincronizar(capas)} -def calcular(vistas: int, registro: list[str], definiciones: dict[str, int], ctx: Contexto) -> dict[str, list[int]]: - """Cada definición en cada periodo de cada tipo que publica, dentro de los años del contexto. - - Cada reporte se mide y se guarda en una sola sesión (`CalculoRepository.calcular`). - """ - desde, hasta = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1) - calculo, tablas = ctx.repos.oro.calculo, tablas_de(ctx.proyecto) - reportes = {} - for nombre, medida in measures_de(ctx.proyecto).items(): - for tipo in medida.extension.publicacion.tipos_periodo: - for periodo_id in calculo.periodos(tipo, desde, hasta): - medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas, - corte=ctx.corte, permitir_sin_definir=ctx.permitir_sin_definir) - reportes.setdefault(nombre, []).append(calculo.calcular(medir)) - return reportes +def modelos(cargar: SQLModel, ctx: Contexto) -> int: + """The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base.""" + return len(ctx.repos.plata.vistas.construir(event_views(_manifest(ctx), ctx.proyecto))) -# `observar` y `verificar_plata` van después de `calcular` para que una regla suya sin definir no lo detenga (I-MD1). -def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int]], ctx: Contexto) -> int: +def _manifest(ctx: Contexto) -> Path: + if ctx.dbt_manifest is None: + raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there") + return ctx.dbt_manifest + + +def observar(cargar: SQLModel, registro: list[str], ctx: Contexto) -> int: """`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente.""" return ctx.repos.plata.observacion.observar(partial( periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte, @@ -168,8 +157,7 @@ def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int )) -def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[str, list[int]], - ctx: Contexto) -> dict[str, int]: +def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], ctx: Contexto) -> dict[str, int]: """Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro.""" conteos = ctx.repos.plata.vinculos.verificar(partial(calidad_de_la_plata, tablas=tablas_de(ctx.proyecto))) for nombre, n in conteos.items(): @@ -179,17 +167,19 @@ def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[ @config.when(con_cohortes=True) -def cohortes(cargar: SQLModel, ctx: Contexto) -> 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).""" +def cohortes(modelos: int, ctx: Contexto) -> 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 (`modelos` creates it), the same the models and the measures' strata read. + """ tablas = tablas_de(ctx.proyecto) tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES - fuentes = import_module(f"indicadores_kit.{ctx.proyecto}.linea_de_tiempo").FUENTES_PLATA inicio, fin = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1) def armado(definicion, sesion): - corte = ctx.corte or fecha_de_ultima_carga(sesion, tablas) - return armado_de(sesion, definicion, inicio, fin, corte, tablas=tablas, cohortes=tablas_cohorte, - fuentes=fuentes) + corte = ctx.corte or _fecha_de_ultima_carga(sesion, tablas) + return armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, + linea=ctx.repos.plata.timeline.query) armados = {} for ruta in definiciones_de_cohorte(ctx.proyecto): @@ -229,3 +219,11 @@ def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, t armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos ) return lotes + + +def _fecha_de_ultima_carga(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]) diff --git a/webapi/orquestacion/contexto.py b/webapi/orquestacion/contexto.py index 50b3e26..37e2dac 100644 --- a/webapi/orquestacion/contexto.py +++ b/webapi/orquestacion/contexto.py @@ -1,5 +1,6 @@ """Lo que recibe cada paso del ciclo.""" +import os from collections.abc import Mapping from dataclasses import dataclass, field from datetime import date @@ -7,6 +8,12 @@ from pathlib import Path from typing import Any +def manifiesto_de_dbt() -> Path | None: + """The deployment's dbt manifest, from `DBT_MANIFEST`.""" + ruta = os.environ.get("DBT_MANIFEST") + return Path(ruta) if ruta else None + + @dataclass(frozen=True) class Contexto: """Lo que recibe un paso: el proyecto y las opciones del ciclo. @@ -26,6 +33,9 @@ class Contexto: corte: date | None = None permitir_sin_definir: bool = False parametros: Path | None = None + # The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle + # creates their event models (`modelos`) and seeds the publication catalog (`definiciones`). + dbt_manifest: Path | None = field(default_factory=manifiesto_de_dbt) # Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimar(columnas, filas)`, `procedencia()` # y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimar` no hace nada. estimadores: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False) diff --git a/webapi/orquestacion/proyecto.py b/webapi/orquestacion/proyecto.py index 78086d3..5cab24e 100644 --- a/webapi/orquestacion/proyecto.py +++ b/webapi/orquestacion/proyecto.py @@ -1,14 +1,16 @@ -"""Lo que el ciclo necesita saber de las definiciones del kit para un proyecto.""" +"""Lo que el ciclo necesita saber de las definiciones de un proyecto: sus periodos (dbt) y sus cohortes (el kit).""" +import json from pathlib import Path from indicadores_kit.oro.cohortes.definicion import RAIZ -from indicadores_kit.registry.measures import measures_de -def tipos_de_periodo(proyecto: str) -> list[str]: - """Los tipos de periodo que publican las definiciones del proyecto (semestre y, en CaCu y CaMa, mes).""" - return sorted({t for m in measures_de(proyecto).values() for t in m.extension.publicacion.tipos_periodo}) +def tipos_de_periodo(proyecto: str, manifest: Path) -> list[str]: + """The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest.""" + metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() + return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", []) + if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")}) def definiciones_de_cohorte(proyecto: str) -> list[Path]: diff --git a/webapi/orquestacion/repositorios.py b/webapi/orquestacion/repositorios.py index 12cab49..68f87e6 100644 --- a/webapi/orquestacion/repositorios.py +++ b/webapi/orquestacion/repositorios.py @@ -8,8 +8,6 @@ dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión. from dataclasses import dataclass from importlib import import_module -from indicadores_kit.plata.linea_de_tiempo import linea_de_tiempo_plata -from indicadores_kit.tablas import tablas_de from persistance.aristas.bronce import StagingRepository from persistance.aristas.oro import ( CalculoRepository, @@ -21,7 +19,6 @@ from persistance.aristas.plata import ( CargaRepository, CatalogoRepository, ObservacionRepository, - TimelineQuery, TimelineRepository, VinculosRepository, VistasRepository, @@ -45,7 +42,7 @@ class Plata: vistas: VistasRepository observacion: ObservacionRepository vinculos: VinculosRepository - timeline: TimelineRepository | None = None # the patients' timeline, through the kit's query + timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it @dataclass(frozen=True) @@ -82,7 +79,7 @@ def repositorios_de(proyecto: str) -> Repositorios: vistas=dominio.vistas_repository, observacion=dominio.observar_repository, vinculos=dominio.vinculos_repository, - timeline=dominio.timeline_repository.with_query(timeline_query(proyecto)), + timeline=dominio.timeline_repository, ), materializador=dominio.materializador, oro=Oro( @@ -96,13 +93,3 @@ def repositorios_de(proyecto: str) -> Repositorios: ), ) - -def timeline_query(proyecto: str) -> TimelineQuery: - """The project's timeline query: the kit's `linea_de_tiempo_plata` over its `FUENTES_PLATA`.""" - tablas = tablas_de(proyecto) - fuentes = import_module(f"indicadores_kit.{proyecto}.linea_de_tiempo").FUENTES_PLATA - - def query(*, patients, until, known_until): - return linea_de_tiempo_plata(tablas, fuentes, pacientes=patients, hasta=until, conocida_hasta=known_until) - - return query diff --git a/webapi/orquestacion/semantic_layer.py b/webapi/orquestacion/semantic_layer.py new file mode 100644 index 0000000..9642c57 --- /dev/null +++ b/webapi/orquestacion/semantic_layer.py @@ -0,0 +1,78 @@ +"""What the cycle takes from dbt's manifest: the event models to create and the catalog the reports point to. + +The measures are defined in dbt's semantic layer (`webapi.metrics`, `webapi.compositions`). Their event models have +to exist in the database for a measure to be asked; `event_views` gives the DDL that creates them from dbt's compiled +SQL, as `dbt run` would for a view. The publication catalog (`cat_measure*`, `cat_estrato`) is what the reports' +units point to; `catalog_layers` builds it from the same definitions, parents before children. +""" + +import json +from importlib import import_module +from pathlib import Path + +from sqlalchemy import text + +from webapi.compositions import composition_definitions +from webapi.durations import OBSERVATION, duration_definitions +from webapi.kpis import scoring_of +from webapi.metrics import measure_definitions + +CONTRACTS = {"proportion": "C1", "composition": "C2", "continuous-variable": "C3r"} # the publication views +STRATUM_LABELS = {"grupo_edad": "Grupo de edad"} # unless the stratum's `etiqueta` says otherwise + + +def event_views(manifest: Path, project: str) -> list: + """`drop view if exists` and `create view … as ` for every model the project's measures read, + parents first. + + Those are the project's models semantic models count over (`models//…`) and the timelines its strata + read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined + in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here. + """ + m = json.loads(manifest.read_text(encoding="utf-8")) + nodes = {n["unique_id"]: n for n in m["nodes"].values()} + by_name = {n["name"]: uid for uid, n in nodes.items() if n["resource_type"] == "model"} + roots = {uid for uid in (s["depends_on"]["nodes"][0] for s in m["semantic_models"].values()) + if nodes[uid]["fqn"][1] == project} + roots |= {by_name[spec["linea"]] for metric in m["metrics"].values() + if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/") + for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec} + ordered: list[str] = [] + + def visit(uid: str) -> None: + if uid in ordered or uid not in nodes: + return + for parent in nodes[uid]["depends_on"]["nodes"]: + visit(parent) + if nodes[uid]["config"]["materialized"] != "ephemeral": + ordered.append(uid) + + for uid in sorted(roots): + visit(uid) + ddl = [text(f"drop view if exists {nodes[uid]['alias']}") for uid in reversed(ordered)] + return ddl + [text(f"create view {nodes[uid]['alias']} as {nodes[uid]['compiled_code']}") for uid in ordered] + + +def catalog_layers(project: str, manifest: Path) -> list[list]: + """The catalog rows of every measure the manifest defines for the project, in layers: parents first.""" + t = import_module(f"core.{project}.indicadores.models") + # The title on screen: `meta.titulo` when the label had to differ (dbt wants labels unique in the project). + labels = {n["name"]: n["config"].get("meta", {}).get("titulo") or n["label"] + for n in json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()} + definitions = [d for d in (*measure_definitions(manifest).values(), *composition_definitions(manifest).values(), + *duration_definitions(manifest).values()) if d.url.startswith(f"{project}/")] + labels_of = {s.name: s.spec.get("etiqueta") or STRATUM_LABELS.get(s.name, s.name) + for d in definitions for s in d.strata} + strata = sorted(labels_of) + measures, children = [], [] + for d in definitions: + contract = CONTRACTS[scoring_of(d)] + measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric], + contrato=contract, unidad=d.basis)) + codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()))) + children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c, + etiqueta=c) for c in codes] + children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0)) + children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata] + stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata] + return [stratum_rows + measures, children] -- 2.53.0 From 82504bd0bf80854bc044f45936272ca0a804b277 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 02/24] English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports --- Dockerfile | 2 +- README.md | 4 +- docker-entrypoint.sh | 4 +- tests/conftest.py | 24 +-- tests/test_cama_measures.py | 8 +- tests/test_measure_cases.py | 6 +- tests/test_metrics_on_request.py | 14 +- tests/test_orquestacion_ciclo.py | 28 ++-- tests/test_orquestacion_oro.py | 26 ++-- tests/test_orquestacion_pasos.py | 26 ++-- tests/test_orquestacion_plata.py | 62 ++++---- tests/test_orquestacion_regla_repositorios.py | 16 +- tests/test_orquestacion_riesgos.py | 20 +-- tests/test_orquestacion_timeline.py | 12 +- tests/test_patient_risk.py | 4 +- tests/test_reportes.py | 8 +- webapi/__init__.py | 10 +- webapi/blueprints/imports.py | 6 +- webapi/blueprints/{reportes.py => reports.py} | 26 ++-- webapi/{seguimiento.py => follow_up.py} | 12 +- webapi/imports/audit.py | 2 +- webapi/orchestration/__init__.py | 37 +++++ webapi/orchestration/__main__.py | 63 ++++++++ .../connection.py} | 2 +- .../contexto.py => orchestration/context.py} | 30 ++-- .../ciclo.py => orchestration/cycle.py} | 140 +++++++++--------- .../proyecto.py => orchestration/project.py} | 4 +- webapi/orchestration/repositories.py | 95 ++++++++++++ .../ejecutor.py => orchestration/runner.py} | 60 ++++---- .../semantic_layer.py | 0 webapi/orquestacion/__init__.py | 39 ----- webapi/orquestacion/__main__.py | 63 -------- webapi/orquestacion/repositorios.py | 95 ------------ webapi/patient_risk.py | 4 +- ...{indicadores_vivos.py => recomputation.py} | 62 ++++---- 35 files changed, 506 insertions(+), 508 deletions(-) rename webapi/blueprints/{reportes.py => reports.py} (72%) rename webapi/{seguimiento.py => follow_up.py} (88%) create mode 100644 webapi/orchestration/__init__.py create mode 100644 webapi/orchestration/__main__.py rename webapi/{orquestacion/conexion.py => orchestration/connection.py} (92%) rename webapi/{orquestacion/contexto.py => orchestration/context.py} (67%) rename webapi/{orquestacion/ciclo.py => orchestration/cycle.py} (56%) rename webapi/{orquestacion/proyecto.py => orchestration/project.py} (86%) create mode 100644 webapi/orchestration/repositories.py rename webapi/{orquestacion/ejecutor.py => orchestration/runner.py} (54%) rename webapi/{orquestacion => orchestration}/semantic_layer.py (100%) delete mode 100644 webapi/orquestacion/__init__.py delete mode 100644 webapi/orquestacion/__main__.py delete mode 100644 webapi/orquestacion/repositorios.py rename webapi/{indicadores_vivos.py => recomputation.py} (71%) diff --git a/Dockerfile b/Dockerfile index 788bc0e..9df8966 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,7 +31,7 @@ ENV MLFLOW_TRACKING_URI=sqlite:////data/mlflow.db ENV MLFLOW_ARTIFACT_ROOT=/data/mlflow-artefactos # No usage telemetry from MLflow: the server runs on a closed network. ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true -# Aggregate import log and the live indicator queue (webapi.indicadores_vivos). +# Aggregate import log and the live indicator queue (webapi.recomputation). ENV WEBAPI_REPORT_DIR=/data/reportes ENV INDICADORES_DIR=/data/indicadores ENV MLFLOW_DISABLE_AGENT_HINT=1 diff --git a/README.md b/README.md index 634df8d..75ca482 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ webapi/ │ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura │ └── audit.py bitácora agregada (sin datos de pacientes) ├── indicadores.py rutas de indicadores (del equipo de indicadores) -├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga +├── recomputation.py cola y servicio que recalcula indicadores tras cada carga └── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION) ``` @@ -79,7 +79,7 @@ for d in cacu cama tea governance; do uv run alembic -c ../Persistance/persistance/$d/alembic.ini upgrade head done uv run python main.py # http://localhost:5050 -uv run python -m webapi.indicadores_vivos # recálculo de indicadores, en otra terminal +uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal ``` Con Docker, desde la raíz del repositorio: `docker compose up --build`. La diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 1c7b230..cacf3ed 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -10,11 +10,11 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER esac done -# The live indicator worker (webapi.indicadores_vivos) shares the image; the +# The live indicator worker (webapi.recomputation) shares the image; the # API container runs the migrations, so the worker starts after it. if [ "$1" = "indicadores" ]; then cd /app/WebApi - exec uv run --no-sync python -m webapi.indicadores_vivos + exec uv run --no-sync python -m webapi.recomputation fi cd /app/WebApi diff --git a/tests/conftest.py b/tests/conftest.py index 48973e4..a0510cd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,8 +5,8 @@ `_DATABASE_URL` alone has no effect once an engine exists. `wire_domain` resets all three (env var, singleton, cache). -The `base`/`base_de` family (below `ANIO`) is for `webapi.orquestacion`: -una base del dominio por prueba, migrada por el paso `migrar`, con el staging +The `base`/`base_de` family (below `ANIO`) is for `webapi.orchestration`: +una base del dominio por prueba, migrada por el paso `migrate`, con el staging sintético del kit. """ import os @@ -20,9 +20,9 @@ from sqlalchemy import create_engine from sqlmodel import Session from indicadores_kit.registry.parametros import RUTA_PARAMETROS -from webapi.orquestacion import Contexto, correr -from webapi.orquestacion.conexion import apuntar -from webapi.orquestacion.repositorios import repositorios_de +from webapi.orchestration import Context, run +from webapi.orchestration.connection import point_to +from webapi.orchestration.repositories import repositories_of # Tests use throwaway SQLite files as "arbitrary SQL sources"; production # excludes sqlite by default (see webapi.imports.connectors.sql_policy). @@ -40,13 +40,13 @@ class Base: """El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance.""" proyecto: str - ctx: Contexto + ctx: Context dominio: object motor: object - def correr(self, *pasos: str, **cambios) -> dict: + def run(self, *pasos: str, **cambios) -> dict: """Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una.""" - return {p.nombre: p.resumen for p in correr(replace(self.ctx, **cambios), solo=pasos)} + return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)} def staging(self): """Una sesión sobre la base, para cambiar el staging como lo haría la ingesta.""" @@ -56,10 +56,10 @@ class Base: def base_de(proyecto: str, carpeta, datos=None) -> Base: """A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts.""" url = f"sqlite:///{carpeta / f'{proyecto}.db'}" - apuntar(proyecto, url) + point_to(proyecto, url) manifest = os.environ.get("DBT_MANIFEST") - ctx = Contexto(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositorios_de(proyecto)) - correr(ctx, solo=["migrar"]) + ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto)) + run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: (datos or import_module(f"indicadores_kit.{proyecto}.fixtures").insertar)(sesion) @@ -137,7 +137,7 @@ def cliente_de(proyecto: str, tmp_path_factory): """Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging.""" carpeta = tmp_path_factory.mktemp(proyecto) base = base_de(proyecto, carpeta) - base.correr("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos", permitir_sin_definir=True) + base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True) try: from webapi import create_app diff --git a/tests/test_cama_measures.py b/tests/test_cama_measures.py index 0f1b7f4..b292d3a 100644 --- a/tests/test_cama_measures.py +++ b/tests/test_cama_measures.py @@ -1,7 +1,7 @@ """What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit computed on the same fixture data: every measure, every period, its units and its numbers. -Fixtures: `base`, the CaMa fixture database through the cycle up to `modelos` (dbt's views); `manifest`, dbt's +Fixtures: `base`, the CaMa fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published numbers for each measure and period (counts only; suppression off). """ @@ -20,7 +20,7 @@ from webapi.durations import answer_duration, duration_definitions from webapi.metrics import Question, answer, measure_definitions ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8")) -UNTIL_MODELS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @pytest.fixture @@ -34,8 +34,8 @@ def manifest(): @pytest.fixture def base(tmp_path, sin_supresion, manifest): base = base_de("cama", tmp_path) - base.correr(*UNTIL_MODELS, parametros=sin_supresion, permitir_sin_definir=True) - yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True)) base.motor.dispose() diff --git a/tests/test_measure_cases.py b/tests/test_measure_cases.py index a0ffa77..73369d4 100644 --- a/tests/test_measure_cases.py +++ b/tests/test_measure_cases.py @@ -6,7 +6,7 @@ latest version of each, the bands by the rules' cut points). Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each `pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views -created by the cycle (`catalogos` … `modelos`; needs `DBT_MANIFEST`). +created by the cycle (`catalogs` … `event_models`; needs `DBT_MANIFEST`). """ import json @@ -70,8 +70,8 @@ def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case if not manifest: pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") base = base_de("cacu", tmp_path, rows_of(case)) - base.correr("catalogos", "cargar", "registro", "definiciones", "modelos", parametros=sin_supresion, - permitir_sin_definir=True) + base.run("catalogs", "load", "registry", "definitions", "event_models", parameters=sin_supresion, + allow_undecided=True) with base.motor.begin() as connection: for key, value in case.get("parametros", {}).items(): connection.execute(text("update def_parametro set valor = :v where clave = :k"), diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py index c93f30d..ea6f3e0 100644 --- a/tests/test_metrics_on_request.py +++ b/tests/test_metrics_on_request.py @@ -2,7 +2,7 @@ dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which keeps each answer under its key. -Fixtures: `base`, the CaCu fixture database through the cycle up to `modelos` (which creates dbt's event models); +Fixtures: `base`, the CaCu fixture database through the cycle up to `event_models` (which creates dbt's event models); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13 and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against. """ @@ -22,11 +22,11 @@ from conftest import base_de from core.cacu.models import BiopsiaCervical, CitologiaCervical from webapi.compositions import answer_composition, composition_definitions, composition_report from webapi.metrics import Question, answer, measure_definitions, measure_report -from webapi.orquestacion import correr +from webapi.orchestration import run IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7" STATUS = "estatus_seguimiento" -HASTA_MODELOS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") +HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models") PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"] SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json" @@ -42,8 +42,8 @@ def manifest(): @pytest.fixture def base(tmp_path, sin_supresion, manifest): base = base_de("cacu", tmp_path) - base.correr(*HASTA_MODELOS, parametros=sin_supresion, permitir_sin_definir=True) - yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True)) base.motor.dispose() @@ -120,12 +120,12 @@ def reports(base) -> int: def reload(base, change) -> None: - """Changes the staging as the ingestion would and runs `cargar`: a new load, known later than everything before.""" + """Changes the staging as the ingestion would and runs `load`: a new load, known later than everything before.""" time.sleep(0.01) with Session(base.motor) as session: change(session) session.commit() - correr(base.ctx, solo=["cargar"]) + run(base.ctx, only=["load"]) def test_ind1_answers_what_the_kit_computed(base, definition, kit): diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index b8cf16c..8ec5f4a 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -14,8 +14,8 @@ import pytest from sqlalchemy import create_engine, text from sqlmodel import Session -from webapi.orquestacion import Contexto, correr -from webapi.orquestacion.conexion import apuntar +from webapi.orchestration import Context, run +from webapi.orchestration.connection import point_to ANIO = 2025 # Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas). @@ -32,25 +32,25 @@ def bases(request, tmp_path_factory): proyecto = request.param carpeta = tmp_path_factory.mktemp(proyecto) url = f"sqlite:///{carpeta / 'orquestada.db'}" - apuntar(proyecto, url) - # `observar` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de + point_to(proyecto, url) + # `observe` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de # dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo. - ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"])) - correr(ctx, solo=["migrar"]) + ctx = Context(proyecto, ANIO, ANIO, allow_undecided=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"])) + run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) sesion.commit() - pasos = correr(ctx) + pasos = run(ctx) return proyecto, ctx, motor, None, pasos def test_corre_todos_los_pasos_en_orden(bases): proyecto, _, _, _, pasos = bases - nombres = [p.nombre for p in pasos] - # `migrar` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9). - assert nombres[0] == "migrar" and nombres.index("catalogos") < nombres.index("cargar") - assert nombres.index("cargar") < nombres.index("modelos") and "calcular" not in nombres + nombres = [p.name for p in pasos] + # `migrate` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9). + assert nombres[0] == "migrate" and nombres.index("catalogs") < nombres.index("load") + assert nombres.index("load") < nombres.index("event_models") and "calcular" not in nombres @@ -60,7 +60,7 @@ def test_volver_a_correr_no_agrega_reportes(bases): _, ctx, motor, _, _ = bases with motor.connect() as con: antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() - correr(ctx) + run(ctx) with motor.connect() as con: assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes @@ -68,9 +68,9 @@ def test_volver_a_correr_no_agrega_reportes(bases): def test_en_cacu_arma_su_cohorte_una_vez(bases): proyecto, ctx, motor, _, pasos = bases if proyecto != "cacu": - assert "cohortes" not in [p.nombre for p in pasos] # T-21h: TEA y CaMa, solo propuestas + assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas return - (armado_id, nuevo), = [p.resumen for p in pasos if p.nombre == "cohortes"][0].values() + (armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values() 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( diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index fbaf427..7bfe6ab 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -13,14 +13,14 @@ from indicadores_kit.registry.edades import grupos_de_cortes from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo from indicadores_kit.registry.periodos import periodos_de_tipos from indicadores_kit.tablas import tablas_de -from webapi.orquestacion.proyecto import tipos_de_periodo +from webapi.orchestration.project import period_types from conftest import ANIO # El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}. def cargas(proyecto) -> tuple[str, ...]: """El paso que lleva el staging a la plata (staging directo, T-20c).""" - return ("cargar",) + return ("load",) @@ -38,19 +38,19 @@ def cargas(proyecto) -> tuple[str, ...]: def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base): - base.correr("registro") - base.correr("registro", anio_inicio=ANIO - 1) + base.run("registry") + base.run("registry", year_from=ANIO - 1) tablas = tablas_de(base.proyecto) - esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas) + esperados = periodos_de_tipos(period_types(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas) assert base.dominio.dim_periodo_repository.count() == len(esperados) assert base.dominio.measure_report_repository.count() == 0 def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base): """I-MD27 (T-24f): de `comun.dim_fecha.desde` al fin del último año, y los grupos de `.grupos_edad`.""" - base.correr("registro") - base.correr("registro", anio_fin=ANIO + 1) # repetir deja la tabla igual, con el año nuevo + base.run("registry") + base.run("registry", year_to=ANIO + 1) # repetir deja la tabla igual, con el año nuevo valores = valores_del_archivo(RUTA_PARAMETROS) desde = date.fromisoformat(valores["comun.dim_fecha.desde"]) @@ -66,13 +66,13 @@ def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base): def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): - base.correr("registro") + base.run("registry") periodos = base.dominio.dim_periodo_repository.count() malo = tmp_path / "malo.toml" malo.write_text('[comun.x]\nvalor = 1\nestado = "provisional"\n', encoding="utf-8") with pytest.raises(ValueError, match="fuente"): - base.correr("registro", anio_inicio=ANIO - 1, anio_fin=ANIO + 1, parametros=malo) + base.run("registry", year_from=ANIO - 1, year_to=ANIO + 1, parameters=malo) assert base.dominio.def_parametro_repository.get("comun.x") is None assert base.dominio.def_parametro_repository.get("comun.umbral_supresion") is not None @@ -80,15 +80,15 @@ def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): - """Pins down: `definiciones` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a + """Pins down: `definitions` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" - resumen = base.correr("definiciones")["definiciones"] + resumen = base.run("definitions")["definitions"] # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata. - assert resumen["definiciones"] == {"cacu": 10, "cama": 7}[base.proyecto] + assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain - assert base.correr("definiciones")["definiciones"]["borradas"] == 0 + assert base.run("definitions")["definitions"]["borradas"] == 0 diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index b4bc39c..e8ded34 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -3,38 +3,38 @@ import pytest from hamilton import driver -from webapi.orquestacion import ciclo, pasos_de +from webapi.orchestration import cycle, steps_of def dependencias(proyecto: str) -> dict[str, set[str]]: - dr = driver.Builder().with_modules(ciclo).with_config({"con_cohortes": proyecto == "cacu"}).build() + dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build() return {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"} def antes(deps: dict[str, set[str]], paso: str) -> set[str]: """Todos los pasos que corren antes de `paso`.""" previos = set() - pendientes = list(deps[paso]) - while pendientes: - anterior = pendientes.pop() + pending = list(deps[paso]) + while pending: + anterior = pending.pop() if anterior not in previos: previos.add(anterior) - pendientes.extend(deps[anterior]) + pending.extend(deps[anterior]) return previos @pytest.mark.parametrize("proyecto", ["cacu", "cama"]) def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto): deps = dependencias(proyecto) - assert deps["migrar"] == set() - assert {"migrar", "catalogos"} <= antes(deps, "cargar") # decisión 6 de §9 - assert {"cargar"} <= antes(deps, "modelos") - assert {"registro"} <= antes(deps, "observar") - assert {"cargar", "catalogos"} <= antes(deps, "verificar_plata") + assert deps["migrate"] == set() + assert {"migrate", "catalogs"} <= antes(deps, "load") # decisión 6 de §9 + assert {"load"} <= antes(deps, "event_models") + assert {"registry"} <= antes(deps, "observe") + 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 {"cohortes", "estimar"} <= set(pasos_de("cacu")) + assert {"cohorts", "estimate"} <= set(steps_of("cacu")) for proyecto in ("cama", "tea"): - assert not {"cohortes", "estimar"} & set(pasos_de(proyecto)) + assert not {"cohorts", "estimate"} & set(steps_of(proyecto)) diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 9631914..96d743b 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -31,7 +31,7 @@ CORTE = date(2025, 12, 31) def ultima_carga(base): - return max(base.ctx.repos.plata.carga.list(limit=100), key=lambda c: c.carga_id) + return max(base.ctx.repos.silver.loads.list(limit=100), key=lambda c: c.carga_id) def contar(base, sql: str) -> int: @@ -60,7 +60,7 @@ def cambiar_staging(base) -> str: def filas_del_catalogo(base) -> dict[str, int]: """Cuántas filas tiene cada tabla de catálogo en la base.""" - plata = base.ctx.repos.plata.catalogos + plata = base.ctx.repos.silver.catalogs with base.staging() as sesion: return { "estudios": len(sesion.exec(select(plata.model)).all()), @@ -74,15 +74,15 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base): del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados), "valores": len(catalogo.valores)} - assert base.correr("catalogos")["catalogos"] == {**del_toml, "retirados": 0} + assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0} assert filas_del_catalogo(base) == del_toml def test_volver_a_correr_catalogos_no_cambia_nada(base): - base.correr("catalogos") + base.run("catalogs") antes = filas_del_catalogo(base) - assert base.correr("catalogos")["catalogos"]["retirados"] == 0 + assert base.run("catalogs")["catalogs"]["retirados"] == 0 assert filas_del_catalogo(base) == antes @@ -90,14 +90,14 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base): def test_cargar_lleva_el_staging_a_persona_y_la_plata(base): - base.correr("catalogos") - carga = base.correr("cargar")["cargar"] + base.run("catalogs") + carga = base.run("load")["load"] procedimientos, observaciones = plata_de(base) assert procedimientos and observaciones assert carga.fin is not None and (carga.filas_nuevas, carga.filas_cambiadas, carga.filas_sin_cambio) == ( procedimientos, 0, 0) - assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronce.staging.leer( + assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronze.staging.read( {"p": tablas_de_staging(base.proyecto)[0]})["p"]) # Ningún reporte ni parte sin su toma (salvo los huérfanos, que no se escriben). assert contar(base, "SELECT COUNT(*) FROM procedimiento WHERE clase IN ('reporte', 'parte') AND padre_id IS NULL") == 0 @@ -108,10 +108,10 @@ def test_cargar_lleva_el_staging_a_persona_y_la_plata(base): def test_volver_a_cargar_sin_cambios_no_toca_nada(base): - base.correr("catalogos", "cargar") + base.run("catalogs", "load") antes = plata_de(base) - segunda = base.correr("cargar")["cargar"] + segunda = base.run("load")["load"] assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 0, antes[0]) assert plata_de(base) == antes for tabla in ("procedimiento", "observacion_clinica"): @@ -119,11 +119,11 @@ def test_volver_a_cargar_sin_cambios_no_toca_nada(base): def test_un_cambio_en_staging_toca_un_procedimiento(base): - base.correr("catalogos", "cargar") + base.run("catalogs", "load") antes = plata_de(base) cambiar_staging(base) - segunda = base.correr("cargar")["cargar"] + segunda = base.run("load")["load"] assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 1, antes[0] - 1) assert plata_de(base) == antes @@ -134,9 +134,9 @@ def test_un_cambio_en_staging_toca_un_procedimiento(base): def test_las_vistas_se_construyen_y_se_pueden_repetir(base): - primera = base.correr("vistas")["vistas"] + primera = base.run("views")["views"] - assert base.correr("vistas")["vistas"] == primera + assert base.run("views")["views"] == primera # Only `v_persona`: the published numbers are answered on request, so the publication views aren't built. assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"] @@ -166,9 +166,9 @@ observables = pytest.mark.parametrize("proyecto", ["cacu", "cama"]) @observables def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla("2024-06-01")) + base.run("load", "registry", parameters=con_regla("2024-06-01")) - cuantos = base.correr("observar", corte=CORTE)["observar"] + cuantos = base.run("observe", cutoff=CORTE)["observe"] periodos = base.dominio.periodo_observacion_repository.list() assert cuantos == len(periodos) == base.dominio.persona_repository.count() @@ -178,9 +178,9 @@ def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla): @observables def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla()) + base.run("load", "registry", parameters=con_regla()) - base.correr("observar") + base.run("observe") carga = ultima_carga(base) assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == { @@ -189,10 +189,10 @@ def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_re @observables def test_observar_se_puede_repetir_sin_duplicar(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla()) + base.run("load", "registry", parameters=con_regla()) - primera = base.correr("observar", corte=date(2025, 6, 30))["observar"] - segunda = base.correr("observar", corte=CORTE)["observar"] + primera = base.run("observe", cutoff=date(2025, 6, 30))["observe"] + segunda = base.run("observe", cutoff=CORTE)["observe"] assert primera == segunda == base.dominio.periodo_observacion_repository.count() assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE} @@ -200,37 +200,37 @@ def test_observar_se_puede_repetir_sin_duplicar(base, con_regla): @observables def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base): - base.correr("cargar", "registro") + base.run("load", "registry") with pytest.raises(ParametroSinDefinir, match="inicio_datos"): - base.correr("observar", corte=CORTE) - assert base.correr("observar", corte=CORTE, permitir_sin_definir=True)["observar"] == ( + base.run("observe", cutoff=CORTE) + assert base.run("observe", cutoff=CORTE, allow_undecided=True)["observe"] == ( base.dominio.persona_repository.count()) @observables def test_sin_el_registro_observar_dice_que_falta(base): - base.correr("cargar") + base.run("load") with pytest.raises(KeyError, match="preparar_registro|registro"): - base.correr("observar", corte=CORTE) + base.run("observe", cutoff=CORTE) @observables def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla("2024-06-01")) + base.run("load", "registry", parameters=con_regla("2024-06-01")) with pytest.raises(ValueError, match="anterior al inicio"): - base.correr("observar", corte=date(2024, 5, 31)) + base.run("observe", cutoff=date(2024, 5, 31)) assert base.dominio.periodo_observacion_repository.count() == 0 @observables def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla): - base.correr("registro", parametros=con_regla()) + base.run("registry", parameters=con_regla()) with pytest.raises(ObservacionSinCorte): - base.correr("observar") + base.run("observe") # --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA --- @@ -239,7 +239,7 @@ def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla): @pytest.mark.parametrize("proyecto", ["cacu"]) def test_verificar_plata_en_cacu_cuenta_los_valores_fuera_de_catalogo_del_fixture(base): - conteos = base.correr("catalogos", "cargar", "verificar_plata")["verificar_plata"] + conteos = base.run("catalogs", "load", "check_silver")["check_silver"] # I-MD16 (textos del fixture fuera del catálogo) e I-MD18 (especialidades que el alias no reconoce): en la # plata, una observación de código sin `valor_id` y con su `valor_fuente`. diff --git a/tests/test_orquestacion_regla_repositorios.py b/tests/test_orquestacion_regla_repositorios.py index f13c068..048a27d 100644 --- a/tests/test_orquestacion_regla_repositorios.py +++ b/tests/test_orquestacion_regla_repositorios.py @@ -1,7 +1,7 @@ """La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`. -Las subclases viven en `persistance/aristas/` y Persistance las instancia con su -fábrica de sesión (ADR-MD-005). Solo `conexion.py` nombra a `persistance.db`: cambia a +Las subclases viven en `persistance/edges/` y Persistance las instancia con su +fábrica de sesión (ADR-MD-005). Solo `connection.py` nombra a `persistance.db`: cambia a qué base apunta Persistance (`_DATABASE_URL` en memoria); no es un paso. """ @@ -10,10 +10,10 @@ from pathlib import Path import pytest -from webapi.orquestacion.repositorios import repositorios_de +from webapi.orchestration.repositories import repositories_of -PAQUETE = Path(__file__).parents[1] / "webapi" / "orquestacion" -EXENTOS = {"conexion.py"} +PAQUETE = Path(__file__).parents[1] / "webapi" / "orchestration" +EXENTOS = {"connection.py"} PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db") @@ -25,6 +25,6 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo): @pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)]) def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes): - repos = repositorios_de(proyecto) - assert (repos.oro.cohorte is not None) == con_cohortes - assert repos.oro.calculo.model.__tablename__ == "measure_report" + repos = repositories_of(proyecto) + assert (repos.gold.cohorts is not None) == con_cohortes + assert repos.gold.calculation.model.__tablename__ == "measure_report" diff --git a/tests/test_orquestacion_riesgos.py b/tests/test_orquestacion_riesgos.py index 5cb1a4c..9d3f8a3 100644 --- a/tests/test_orquestacion_riesgos.py +++ b/tests/test_orquestacion_riesgos.py @@ -1,4 +1,4 @@ -"""El paso `estimar` y la orden `confirmar-riesgos` (ADR-MD-008), con un estimador de prueba. +"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba. El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow. """ @@ -8,7 +8,7 @@ from dataclasses import dataclass import pytest from sqlalchemy import text -from webapi.orquestacion.__main__ import confirmar_riesgos, main +from webapi.orchestration.__main__ import confirm_risks, main URL = "cacu/cohorte_vigilancia" @@ -43,7 +43,7 @@ class EstimadorFijo: @pytest.fixture def cacu(base): - base.correr("catalogos", "cargar", "modelos", "cohortes", permitir_sin_definir=True) + base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True) return base @@ -56,7 +56,7 @@ def cuenta(base, sql): def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu): estimador = EstimadorFijo() - (lote_id, nuevo) = cacu.correr("estimar", estimadores={URL: estimador})["estimar"][URL] + (lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL] miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1") assert nuevo and miembros > 0 @@ -68,23 +68,23 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu): @pytest.mark.parametrize("proyecto", ["cacu"]) def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu): - (primero, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] + (primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] - assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False) - assert cacu.correr("estimar")["estimar"] == {} + assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False) + assert cacu.run("estimate")["estimate"] == {} assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1 @pytest.mark.parametrize("proyecto", ["cacu"]) def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys): - (lote_id, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] + (lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}") - main(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "revisado"]) + main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"]) assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros - assert confirmar_riesgos("cacu", lote_id, "error de captura", anular=True) == miembros + assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros diff --git a/tests/test_orquestacion_timeline.py b/tests/test_orquestacion_timeline.py index 8d07c93..eda31fa 100644 --- a/tests/test_orquestacion_timeline.py +++ b/tests/test_orquestacion_timeline.py @@ -1,9 +1,9 @@ -"""What this module covers: the timeline `repositorios_de` wires into `ctx.repos.plata` is dbt's view +"""What this module covers: the timeline `repositories_of` wires into `ctx.repos.silver` is dbt's view `cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them. Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created -(`catalogos`, `cargar`, `modelos`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on +(`catalogs`, `load`, `event_models`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time). """ @@ -28,7 +28,7 @@ def proyecto(): def loaded(base): if not os.environ.get("DBT_MANIFEST"): pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") - base.correr("catalogos", "cargar", "modelos") + base.run("catalogs", "load", "event_models") return base @@ -47,7 +47,7 @@ def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows """Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or the view stops giving one of the kit's rows.""" - rows = loaded.ctx.repos.plata.timeline.read(until=CORTE) + rows = loaded.ctx.repos.silver.timeline.read(until=CORTE) assert as_kit(rows) == kit_rows assert {row["tipo"] for row in rows} & INFERRED assert all(isinstance(row["fecha"], date) for row in rows) @@ -56,7 +56,7 @@ def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows): """Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied.""" patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2] - rows = loaded.ctx.repos.plata.timeline.read(patients=patients, until=CORTE) + rows = loaded.ctx.repos.silver.timeline.read(patients=patients, until=CORTE) assert {row["pac_id"] for row in rows} == set(patients) assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients] @@ -64,7 +64,7 @@ def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows): def test_known_until_cuts_at_what_was_loaded(loaded): """Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known, after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text.""" - timeline = loaded.ctx.repos.plata.timeline + timeline = loaded.ctx.repos.silver.timeline everything = timeline.read(until=CORTE) known = {row["conocida_en"] for row in everything} assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known) diff --git a/tests/test_patient_risk.py b/tests/test_patient_risk.py index 8cd6f9b..b244d52 100644 --- a/tests/test_patient_risk.py +++ b/tests/test_patient_risk.py @@ -47,11 +47,11 @@ def seeded(client): CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)]) session.commit() build_id = build.armado_id - batch, _ = cacu.cohorte_repository.guardar_lote( + 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.cohorte_repository.cambiar_estado(batch, "final", "revisado") + cacu.cohort_repository.change_state(batch, "final", "revisado") return scored, unscored, outside diff --git a/tests/test_reportes.py b/tests/test_reportes.py index 93078f8..ebf0949 100644 --- a/tests/test_reportes.py +++ b/tests/test_reportes.py @@ -97,15 +97,15 @@ def test_report_endpoints(client): def test_indicators_recompute_from_imported_rows(client): - from webapi.indicadores_vivos import ColaDeRecalculo + from webapi.recomputation import RecomputationQueue - cola = ColaDeRecalculo() + cola = RecomputationQueue() assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True - assert cola.atender() == ["cacu"] + assert cola.serve() == ["cacu"] estado = client.get("/reportes/indicadores").get_json()["cacu"] assert estado["estado"] == "ok", estado assert estado["pendiente"] is False - assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "modelos"} + assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"} assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == { "IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE", "CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"} diff --git a/webapi/__init__.py b/webapi/__init__.py index 12af8a3..eca46bf 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -9,8 +9,8 @@ from webapi.blueprints.cacu import cacu_bp from webapi.blueprints.data import data_bp from webapi.blueprints.governance import governance_bp from webapi.blueprints.imports import imports_bp -from webapi.blueprints.reportes import reportes_bp -from webapi.seguimiento import blueprint_de_seguimiento, en_dev +from webapi.blueprints.reports import reports_bp +from webapi.follow_up import follow_up_blueprint, in_dev class IsoJSONProvider(DefaultJSONProvider): @@ -72,7 +72,7 @@ def create_app() -> Flask: app.register_blueprint(imports_bp, url_prefix="/imports") app.register_blueprint(data_bp, url_prefix="/data") app.register_blueprint(governance_bp, url_prefix="/governance") - app.register_blueprint(reportes_bp, url_prefix="/reportes") + app.register_blueprint(reports_bp, url_prefix="/reportes") # The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest. if os.environ.get("DBT_MANIFEST"): from importlib import import_module @@ -84,10 +84,10 @@ def create_app() -> Flask: app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}") # Patient-level follow-up list and individual risk: only in DEV, with simulated data. - if en_dev(): + if in_dev(): from persistance.db import get_cacu_session - app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu") + app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") from persistance import cacu as cacu_repositories from webapi.patient_risk import patient_risk_blueprint diff --git a/webapi/blueprints/imports.py b/webapi/blueprints/imports.py index 47410a6..9587d98 100644 --- a/webapi/blueprints/imports.py +++ b/webapi/blueprints/imports.py @@ -21,7 +21,7 @@ from webapi.imports.services.import_service import ( serialize_errors, validate_source, ) -from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo +from webapi.recomputation import DOMAINS, RecomputationQueue from webapi.imports.services.introspection_service import ( detect_pdf, document_report, @@ -321,9 +321,9 @@ def commit(): finally: import_audit.record(audit) recalculating = False - if audit.domain in DOMINIOS and any(r.created or r.updated for r in results): + if audit.domain in DOMAINS and any(r.created or r.updated for r in results): try: - ColaDeRecalculo().solicitar(audit.domain) + RecomputationQueue().request_run(audit.domain) recalculating = True except OSError: # The rows are already saved; failing here would invite a duplicate retry. diff --git a/webapi/blueprints/reportes.py b/webapi/blueprints/reports.py similarity index 72% rename from webapi/blueprints/reportes.py rename to webapi/blueprints/reports.py index e1ee8a0..74a587a 100644 --- a/webapi/blueprints/reportes.py +++ b/webapi/blueprints/reports.py @@ -3,13 +3,13 @@ indicator recomputation. Nothing here returns row-level data.""" from flask import Blueprint, Response, jsonify, request from webapi.imports import audit as import_audit -from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo +from webapi.recomputation import DOMAINS, RecomputationQueue -reportes_bp = Blueprint("reportes", __name__) +reports_bp = Blueprint("reportes", __name__) -@reportes_bp.get("/importaciones") -def importaciones(): +@reports_bp.get("/importaciones") +def import_log(): """Totals per target over every logged attempt, plus the latest attempts (`?limite=50`, newest first; `?dominio=cacu` to filter).""" records = import_audit.default_sink().read() @@ -23,8 +23,8 @@ def importaciones(): return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]}) -@reportes_bp.get("/importaciones/descarga") -def importaciones_descarga(): +@reports_bp.get("/importaciones/descarga") +def import_log_download(): """The raw log, one JSON object per line.""" sink = import_audit.default_sink() body = sink.path.read_bytes() if sink.path.exists() else b"" @@ -35,15 +35,15 @@ def importaciones_descarga(): ) -@reportes_bp.get("/indicadores") -def indicadores_estado(): +@reports_bp.get("/indicadores") +def recomputation_status(): """Per domain: state of the last recomputation and whether another is pending.""" - return jsonify(ColaDeRecalculo().estado()) + return jsonify(RecomputationQueue().status()) -@reportes_bp.post("/indicadores//recalcular") -def indicadores_recalcular(dominio: str): - if dominio not in DOMINIOS: +@reports_bp.post("/indicadores//recalcular") +def recompute(dominio: str): + if dominio not in DOMAINS: return jsonify({"error": f"dominio desconocido: {dominio}"}), 404 - ColaDeRecalculo().solicitar(dominio) + RecomputationQueue().request_run(dominio) return jsonify({"pendiente": True}), 202 diff --git a/webapi/seguimiento.py b/webapi/follow_up.py similarity index 88% rename from webapi/seguimiento.py rename to webapi/follow_up.py index 3c68c09..ba66fec 100644 --- a/webapi/seguimiento.py +++ b/webapi/follow_up.py @@ -19,27 +19,27 @@ from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seg from sqlmodel import Session FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") -SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno +DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno -def en_dev() -> bool: +def in_dev() -> bool: """Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`).""" return bool(os.environ.get("DEV_REVISION")) -def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint: +def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint: """El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV.""" blueprint = Blueprint("cacu_seguimiento", __name__) @blueprint.get("/seguimiento") def get_seguimiento(): try: - pedido = _pedido(request.args) + pedido = _requested(request.args) except ValueError as error: return jsonify({"error": str(error)}), 400 sesion = get_session() try: - cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido) + cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido) except PedidoInvalido as error: return jsonify({"error": str(error)}), 400 except PaginaFuera as error: @@ -51,7 +51,7 @@ def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint: return blueprint -def _pedido(args) -> dict: +def _requested(args) -> dict: """Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito.""" pedido = {} if corte := args.get("corte"): diff --git a/webapi/imports/audit.py b/webapi/imports/audit.py index db45c5c..f96ae00 100644 --- a/webapi/imports/audit.py +++ b/webapi/imports/audit.py @@ -1,6 +1,6 @@ """Aggregate log of every import attempt (validations and commits). -Each attempt becomes one JSON line in `importaciones.jsonl` under +Each attempt becomes one JSON line in `import_log.jsonl` under `WEBAPI_REPORT_DIR`. A record only carries counts, field names, source column names and value *shapes* ("9999-99-99" for a date in an unexpected format): never a row, a file name, a connection string or an identifier. diff --git a/webapi/orchestration/__init__.py b/webapi/orchestration/__init__.py new file mode 100644 index 0000000..ca609c7 --- /dev/null +++ b/webapi/orchestration/__init__.py @@ -0,0 +1,37 @@ +"""Each domain's cycle (CaCu, CaMa): from the staging the import leaves to the silver tables, the reference tables, the +publication catalog and the views dbt compiled, which the measures are answered over. [Hamilton](https://hamilton.apache.org/) +runs it. + +Each step is a function of `cycle.py`. It takes the `Context` and, as parameters, the steps that must run before it; +Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by +Persistance's repositories (`ctx.repos`), so each one can run on its own. + + migrate -> catalogs, registry, definitions + catalogs -> load, check_silver + load -> views, event_models, observe, check_silver + registry -> observe + event_models -> cohorts (only where there are cohorts: CaCu) + cohorts -> estimate + + uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026 + uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models + uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica" + +The `indicadores` service (`webapi.recomputation`) runs the same cycle, without `migrate`, each time an import writes +data. + +Module | What it does +------------------|------------- +`cycle.py` | The steps +`runner.py` | `run(ctx, only=...)`: builds Hamilton's driver and runs the steps asked, in order +`context.py` | The `Context`: project, years, cut-off, rules file and repositories +`repositories.py` | `repositories_of(project)`: Persistance's repositories, by layer +`project.py` | A project's period types and cohort definitions +`connection.py` | Points Persistance at another database in the same process (tests) +`semantic_layer.py` | dbt's views a project's measures read, and the publication catalog +""" + +from webapi.orchestration.context import Context +from webapi.orchestration.runner import Step, run, steps_of + +__all__ = ["Context", "Step", "run", "steps_of"] diff --git a/webapi/orchestration/__main__.py b/webapi/orchestration/__main__.py new file mode 100644 index 0000000..b6dca89 --- /dev/null +++ b/webapi/orchestration/__main__.py @@ -0,0 +1,63 @@ +"""La línea de comandos de la orquestación. + + uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026 [--cutoff 2026-01-01] [--allow-undecided] + uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models + uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica" [--void] + +La base es la de `_DATABASE_URL`, como en Persistance. +""" + +import argparse +import logging +from datetime import date +from pathlib import Path + +from webapi.orchestration.context import Context +from webapi.orchestration.runner import run + +PROJECTS = ("cacu", "cama") + + +def main(argv: list[str] | None = None) -> None: + lector = argparse.ArgumentParser(prog="orchestration", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ordenes = lector.add_subparsers(dest="orden", required=True) + c = ordenes.add_parser("cycle", help="corre los pasos del proyecto en orden") + c.add_argument("project", choices=PROJECTS) + c.add_argument("--from", dest="year_from", type=int, required=True, help="primer año de periodos") + c.add_argument("--to", dest="year_to", type=int, required=True, help="último año de periodos") + c.add_argument("--cutoff", type=date.fromisoformat, default=None) + c.add_argument("--allow-undecided", action="store_true") + c.add_argument("--parameters", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)") + c.add_argument("--only", nargs="+", default=None, help="solo estos pasos") + r = ordenes.add_parser("confirm-risks", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)") + r.add_argument("project", choices=PROJECTS) + r.add_argument("lote_id", type=int) + r.add_argument("--reason", required=True, help="por qué se confirma o se anula; queda en cada evaluación") + r.add_argument("--void", action="store_true", help="anular (entered-in-error) en vez de confirmar") + args = lector.parse_args(argv) + + if args.orden == "confirm-risks": + cambiadas = confirm_risks(args.project, args.lote_id, args.reason, void=args.void) + print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}") + return + logging.basicConfig(level=logging.INFO, format="%(message)s") + ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters) + for paso in run(ctx, only=args.only): + print(f"{paso.name:20} {paso.seconds:6.1f} s") + + +def confirm_risks(project: str, lote_id: int, reason: str, *, void: bool = False) -> int: + """Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva. + + No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008). + """ + from persistance.edges.gold import ERROR, FINAL + + from webapi.orchestration.repositories import repositories_of + + return repositories_of(project).gold.cohorts.change_state(lote_id, ERROR if void else FINAL, reason) + + +if __name__ == "__main__": + main() diff --git a/webapi/orquestacion/conexion.py b/webapi/orchestration/connection.py similarity index 92% rename from webapi/orquestacion/conexion.py rename to webapi/orchestration/connection.py index ba1d205..99af46b 100644 --- a/webapi/orquestacion/conexion.py +++ b/webapi/orchestration/connection.py @@ -10,7 +10,7 @@ from persistance.settings import settings from persistance import db -def apuntar(proyecto: str, url: str) -> None: +def point_to(proyecto: str, url: str) -> None: motor = getattr(db, f"get_{proyecto}_engine") if motor.cache_info().currsize: motor().dispose() diff --git a/webapi/orquestacion/contexto.py b/webapi/orchestration/context.py similarity index 67% rename from webapi/orquestacion/contexto.py rename to webapi/orchestration/context.py index 37e2dac..0eab721 100644 --- a/webapi/orquestacion/contexto.py +++ b/webapi/orchestration/context.py @@ -8,36 +8,36 @@ from pathlib import Path from typing import Any -def manifiesto_de_dbt() -> Path | None: +def dbt_manifest_path() -> Path | None: """The deployment's dbt manifest, from `DBT_MANIFEST`.""" ruta = os.environ.get("DBT_MANIFEST") return Path(ruta) if ruta else None @dataclass(frozen=True) -class Contexto: +class Context: """Lo que recibe un paso: el proyecto y las opciones del ciclo. `anio_inicio` y `anio_fin` son los años de los periodos que se registran y calculan. `corte` es la fecha hasta la que llegan los datos; sin ella, cada paso del kit toma la de la última carga. `permitir_sin_definir` deja correr con parámetros que nadie ha decidido: hay que pedirlo a propósito, como en - el kit. `parametros` es el archivo de parámetros que carga `registro`; sin + el kit. `parametros` es el archivo de parámetros que carga `registry`; sin él, el `parametros.toml` del kit. `repos` es todo lo que el paso usa - para tocar la base: nunca abre una sesión por su cuenta (`repositorios.py`). + para tocar la base: nunca abre una sesión por su cuenta (`repositories.py`). """ - proyecto: str - anio_inicio: int - anio_fin: int - corte: date | None = None - permitir_sin_definir: bool = False - parametros: Path | None = None + project: str + year_from: int + year_to: int + cutoff: date | None = None + allow_undecided: bool = False + parameters: Path | None = None # The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle - # creates their event models (`modelos`) and seeds the publication catalog (`definiciones`). - dbt_manifest: Path | None = field(default_factory=manifiesto_de_dbt) - # Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimar(columnas, filas)`, `procedencia()` - # y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimar` no hace nada. - estimadores: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False) + # creates their event models (`event_models`) and seeds the publication catalog (`definitions`). + dbt_manifest: Path | None = field(default_factory=dbt_manifest_path) + # Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()` + # y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada. + estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False) # Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan. repos: Any = field(default=None, compare=False, repr=False) diff --git a/webapi/orquestacion/ciclo.py b/webapi/orchestration/cycle.py similarity index 56% rename from webapi/orquestacion/ciclo.py rename to webapi/orchestration/cycle.py index 3ac515f..2fe7003 100644 --- a/webapi/orquestacion/ciclo.py +++ b/webapi/orchestration/cycle.py @@ -1,12 +1,12 @@ """Los pasos del ciclo de un proyecto, como funciones de Hamilton. -Cada paso recibe el `Contexto` y, como parámetros, los pasos que tienen que +Cada paso recibe el `Context` y, como parámetros, los pasos que tienen que correr antes; de esos nombres sale el grafo. Los pasos no se pasan datos entre sí: todo va por la base, a través de `ctx.repos`, así que cada uno se puede correr solo (`ejecutor.correr(ctx, solo=[...])`). El kit calcula (funciones puras, o funciones de una sesión) y los repositorios -de `persistance.aristas` escriben, cada operación en una sesión (ADR-MD-005). +de `persistance.edges` escriben, cada operación en una sesión (ADR-MD-005). Bronce lo escribe la ingesta, fuera del ciclo. """ @@ -36,24 +36,24 @@ from indicadores_kit.registry.parametros import ( ) from indicadores_kit.registry.periodos import periodos_de_tipos from indicadores_kit.tablas import tablas_de -from persistance.aristas.plata import guardar_carga_en +from persistance.edges.silver import save_load_in from sqlmodel import SQLModel, func, select -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.semantic_layer import catalog_layers, event_views -from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo +from webapi.orchestration.context import Context +from webapi.orchestration.semantic_layer import catalog_layers, event_views +from webapi.orchestration.project import cohort_definitions, period_types -registro_de_eventos = logging.getLogger(__name__) +log = logging.getLogger(__name__) -def migrar(ctx: Contexto) -> str: +def migrate(ctx: Context) -> str: """`alembic upgrade head` del dominio, con el `alembic.ini` de Persistance.""" from alembic import command from alembic.config import Config import persistance - ini = Path(persistance.__file__).parent / ctx.proyecto / "alembic.ini" + ini = Path(persistance.__file__).parent / ctx.project / "alembic.ini" raiz = logging.getLogger() manejadores, nivel = raiz.handlers[:], raiz.level estado = [(r, r.disabled) for r in logging.root.manager.loggerDict.values() if isinstance(r, logging.Logger)] @@ -65,144 +65,144 @@ def migrar(ctx: Contexto) -> str: return "head" -def catalogos(migrar: str, ctx: Contexto) -> dict[str, int]: +def catalogs(migrate: str, ctx: Context) -> dict[str, int]: """`core/catalogos/.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra.""" - catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.proyecto), tablas=tablas_de(ctx.proyecto)) - return ctx.repos.plata.catalogos.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores) + catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project)) + return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores) -def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel: +def load(catalogs: dict[str, int], ctx: Context) -> SQLModel: """`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c). - Incremental por la llave lógica de cada procedimiento (`guardar_carga_en`): repetir no cambia nada. + Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada. """ - tablas, staging = tablas_de(ctx.proyecto), tablas_de_staging(ctx.proyecto) + tablas, staging = tablas_de(ctx.project), tablas_de_staging(ctx.project) def leer(sesion): filas = {modelo.__tablename__: list(sesion.exec(select(modelo))) for modelo in staging} - return carga_desde_staging(filas, proyecto=ctx.proyecto) + return carga_desde_staging(filas, proyecto=ctx.project) def escribir(sesion, datos): - return guardar_carga_en(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento, + return save_load_in(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento, observacion=tablas.Observacion, fuente=datos.fuente, personas=datos.personas, plata=datos.plata) - return ctx.repos.materializador.materializar(leer, escribir) + return ctx.repos.materializer.materialize(leer, escribir) -def vistas(cargar: SQLModel, ctx: Contexto) -> int: +def views(load: SQLModel, ctx: Context) -> int: """`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base.""" - return len(ctx.repos.plata.vistas.construir(ddl_de_v_persona(tablas_de(ctx.proyecto).Persona))) + return len(ctx.repos.silver.views.build_all(ddl_de_v_persona(tablas_de(ctx.project).Persona))) -def registro(migrar: str, ctx: Contexto) -> list[str]: - """`parametros.toml` (o `ctx.parametros`) -> `def_parametro` (se reemplaza), los periodos que falten en +def registry(migrate: str, ctx: Context) -> list[str]: + """`parametros.toml` (o `ctx.parameters`) -> `def_parametro` (se reemplaza), los periodos que falten en `dim_periodo` y las tablas de apoyo `dim_fecha` y `dim_grupo_edad` (se reemplazan; I-MD27). El archivo se lee y valida antes de escribir. Los periodos no se reemplazan: los reportes guardados apuntan a ellos. `dim_fecha` va de `comun.dim_fecha.desde` al fin - de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `.grupos_edad`, si el + de `ctx.year_to` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `.grupos_edad`, si el proyecto los tiene (TEA no). """ - tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto, _manifest(ctx)) - ruta = ctx.parametros or RUTA_PARAMETROS + tablas, tipos = tablas_de(ctx.project), period_types(ctx.project, _manifest(ctx)) + ruta = ctx.parameters or RUTA_PARAMETROS parametros = leer_parametros(ruta, tablas=tablas) - periodos = periodos_de_tipos(tipos, ctx.anio_inicio, ctx.anio_fin, tablas=tablas) + periodos = periodos_de_tipos(tipos, ctx.year_from, ctx.year_to, tablas=tablas) valores = valores_del_archivo(ruta) # Hasta el fin del último año del ciclo o del año del corte (por omisión, la última carga: hoy), el que sea mayor. - hasta = date(max(ctx.anio_fin, (ctx.corte or date.today()).year), 12, 31) + hasta = date(max(ctx.year_to, (ctx.cutoff or date.today()).year), 12, 31) desde = date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE]) - grupos = grupos_de_edad_de(ctx.proyecto, valores, tablas=tablas) - oro = ctx.repos.oro - oro.parametros.reemplazar(parametros) - oro.periodos.agregar_faltantes(periodos) - if oro.fechas is not None and not _cubre(oro.fechas, desde, hasta): - oro.fechas.reemplazar_en_bloque(filas_de_dim_fecha(valores, hasta, proyecto=ctx.proyecto)) - if oro.grupos_edad is not None and grupos is not None: - oro.grupos_edad.reemplazar(grupos) + grupos = grupos_de_edad_de(ctx.project, valores, tablas=tablas) + gold = ctx.repos.gold + gold.parameters.replace_all(parametros) + gold.periods.add_missing(periodos) + if gold.dates is not None and not _covers(gold.dates, desde, hasta): + gold.dates.replace_in_bulk(filas_de_dim_fecha(valores, hasta, proyecto=ctx.project)) + if gold.age_groups is not None and grupos is not None: + gold.age_groups.replace_all(grupos) return tipos -def _cubre(fechas, desde: date, hasta: date) -> bool: +def _covers(fechas, desde: date, hasta: date) -> bool: """`dim_fecha` ya es exactamente de `desde` a `hasta`: tiene los dos extremos y un día por fecha.""" return (fechas.get(desde) is not None and fechas.get(hasta) is not None and fechas.count() == (hasta - desde).days + 1) -def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]: +def definitions(migrate: str, ctx: Context) -> dict[str, int]: """The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest. It's synchronized: what a report's unit uses isn't deleted. """ - capas = catalog_layers(ctx.proyecto, _manifest(ctx)) - return {"definiciones": len(capas[0]), **ctx.repos.oro.publicacion.sincronizar(capas)} + capas = catalog_layers(ctx.project, _manifest(ctx)) + return {"definitions": len(capas[0]), **ctx.repos.gold.publication.sync(capas)} -def modelos(cargar: SQLModel, ctx: Contexto) -> int: +def event_models(load: SQLModel, ctx: Context) -> int: """The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base.""" - return len(ctx.repos.plata.vistas.construir(event_views(_manifest(ctx), ctx.proyecto))) + return len(ctx.repos.silver.views.build_all(event_views(_manifest(ctx), ctx.project))) -def _manifest(ctx: Contexto) -> Path: +def _manifest(ctx: Context) -> Path: if ctx.dbt_manifest is None: raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there") return ctx.dbt_manifest -def observar(cargar: SQLModel, registro: list[str], ctx: Contexto) -> int: +def observe(load: SQLModel, registry: list[str], ctx: Context) -> int: """`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente.""" - return ctx.repos.plata.observacion.observar(partial( - periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte, - permitir_sin_definir=ctx.permitir_sin_definir, + return ctx.repos.silver.observation.observar(partial( + periodos_de_observacion, proyecto=ctx.project, corte=ctx.cutoff, + permitir_sin_definir=ctx.allow_undecided, )) -def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], ctx: Contexto) -> dict[str, int]: +def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict[str, int]: """Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro.""" - conteos = ctx.repos.plata.vinculos.verificar(partial(calidad_de_la_plata, tablas=tablas_de(ctx.proyecto))) + conteos = ctx.repos.silver.links.check(partial(calidad_de_la_plata, tablas=tablas_de(ctx.project))) for nombre, n in conteos.items(): if n: - registro_de_eventos.warning("%s, plata de dos tablas: %d %s.", ctx.proyecto, n, nombre.replace("_", " ")) + log.warning("%s, plata de dos tablas: %d %s.", ctx.project, n, nombre.replace("_", " ")) return conteos -@config.when(con_cohortes=True) -def cohortes(modelos: int, ctx: Contexto) -> dict[str, tuple[int, bool]]: +@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 (`modelos` creates it), the same the models and the measures' strata read. + Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read. """ - tablas = tablas_de(ctx.proyecto) - tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES - inicio, fin = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1) + tablas = tablas_de(ctx.project) + tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES + inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1) def armado(definicion, sesion): - corte = ctx.corte or _fecha_de_ultima_carga(sesion, tablas) + corte = ctx.cutoff or _last_load_date(sesion, tablas) return armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, - linea=ctx.repos.plata.timeline.query) + linea=ctx.repos.silver.timeline.query) armados = {} - for ruta in definiciones_de_cohorte(ctx.proyecto): + for ruta in cohort_definitions(ctx.project): definicion = leer_definicion(ruta) - armados[definicion.url] = ctx.repos.oro.cohorte.armar(partial(armado, definicion)) + armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion)) return armados -@config.when(con_cohortes=True) -def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, tuple[int, bool]]: +@config.when(with_cohorts=True) +def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]: """El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008). Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador - (`ctx.estimadores[url]`: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como - un lote `preliminary` (`CohorteRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. + (`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como + un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden - `confirmar-riesgos`, no este paso. + `confirm-risks`, no este paso. """ - tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES + tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES lotes = {} - for ruta in definiciones_de_cohorte(ctx.proyecto): + for ruta in cohort_definitions(ctx.project): definicion = leer_definicion(ruta) - estimador = ctx.estimadores.get(definicion.url) + estimador = ctx.estimators.get(definicion.url) if estimador is None: continue @@ -211,17 +211,17 @@ def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, t return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion, cohortes=tablas_cohorte) - armado_id, ancho = ctx.repos.oro.cohorte.leer(marco) + armado_id, ancho = ctx.repos.gold.cohorts.read(marco) if armado_id is None: continue riesgos = [tuple(r) for r in estimador.estimar(*ancho)] - lotes[definicion.url] = ctx.repos.oro.cohorte.guardar_lote( + lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch( armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos ) return lotes -def _fecha_de_ultima_carga(sesion, tablas) -> date | None: +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): diff --git a/webapi/orquestacion/proyecto.py b/webapi/orchestration/project.py similarity index 86% rename from webapi/orquestacion/proyecto.py rename to webapi/orchestration/project.py index 5cab24e..8daf180 100644 --- a/webapi/orquestacion/proyecto.py +++ b/webapi/orchestration/project.py @@ -6,13 +6,13 @@ from pathlib import Path from indicadores_kit.oro.cohortes.definicion import RAIZ -def tipos_de_periodo(proyecto: str, manifest: Path) -> list[str]: +def period_types(proyecto: str, manifest: Path) -> list[str]: """The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest.""" metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", []) if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")}) -def definiciones_de_cohorte(proyecto: str) -> list[Path]: +def cohort_definitions(proyecto: str) -> list[Path]: """Los TOML de cohortes que el ciclo arma (`/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h).""" return sorted((RAIZ / proyecto / "cohortes").glob("*.toml")) diff --git a/webapi/orchestration/repositories.py b/webapi/orchestration/repositories.py new file mode 100644 index 0000000..8a1b7c7 --- /dev/null +++ b/webapi/orchestration/repositories.py @@ -0,0 +1,95 @@ +"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro. + +Las subclases viven en `persistance/edges//` y se +instancian en `persistance//__init__.py` con la fábrica de sesión del +dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión. +""" + +from dataclasses import dataclass +from importlib import import_module + +from persistance.edges.bronze import StagingRepository +from persistance.edges.gold import ( + CalculationRepository, + CohortRepository, + PublicationRepository, + ReferenceRepository, +) +from persistance.edges.silver import ( + LoadRepository, + CatalogRepository, + ObservationRepository, + TimelineRepository, + LinksRepository, + ViewsRepository, +) +from persistance.materializer import Materializer + + +@dataclass(frozen=True) +class Bronze: + """Lo que deja la ingesta. Solo se lee.""" + + staging: StagingRepository + + +@dataclass(frozen=True) +class Silver: + """Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata.""" + + catalogs: CatalogRepository + loads: LoadRepository + views: ViewsRepository + observation: ObservationRepository + links: LinksRepository + timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it + + +@dataclass(frozen=True) +class Gold: + """El registro (parámetros, periodos, definiciones), los reportes y las cohortes.""" + + parameters: ReferenceRepository + periods: ReferenceRepository + calculation: CalculationRepository + publication: PublicationRepository # el catálogo de publicación de §6f (T-19b) + cohorts: CohortRepository | None # donde hay tablas de cohortes (los tres desde MD-12) + dates: ReferenceRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27) + age_groups: ReferenceRepository | None = None # `dim_grupo_edad`, de `.grupos_edad` (I-MD27) + + +@dataclass(frozen=True) +class Repositories: + """Todo lo que un paso usa para tocar la base de su proyecto, por capa.""" + + bronze: Bronze + silver: Silver + gold: Gold + # Una sesión para leer y escribir en el mismo paso (`load`). + materializer: Materializer | None = None + + +def repositories_of(proyecto: str) -> Repositories: + dominio = import_module(f"persistance.{proyecto}") + return Repositories( + bronze=Bronze(staging=dominio.staging_repository), + silver=Silver( + catalogs=dominio.catalog_repository, + loads=dominio.carga_repository, + views=dominio.views_repository, + observation=dominio.observation_period_repository, + links=dominio.links_repository, + timeline=dominio.timeline_repository, + ), + materializer=dominio.materializer, + gold=Gold( + parameters=dominio.def_parametro_repository, + periods=dominio.dim_periodo_repository, + calculation=dominio.calculation_repository, + publication=dominio.publication_repository, + cohorts=getattr(dominio, "cohort_repository", None), + dates=getattr(dominio, "dim_fecha_repository", None), + age_groups=getattr(dominio, "dim_grupo_edad_repository", None), + ), + ) + diff --git a/webapi/orquestacion/ejecutor.py b/webapi/orchestration/runner.py similarity index 54% rename from webapi/orquestacion/ejecutor.py rename to webapi/orchestration/runner.py index 40a664f..fd3c19c 100644 --- a/webapi/orquestacion/ejecutor.py +++ b/webapi/orchestration/runner.py @@ -1,9 +1,9 @@ -"""Corre los pasos de un proyecto (`ciclo.py`) con Hamilton. +"""Corre los pasos de un proyecto (`cycle.py`) con Hamilton. Si un paso falla, los anteriores quedan hechos (cada operación de un repositorio es su propia transacción) y se puede volver a correr: los pasos no duplican. Si el contexto no trae repositorios, se le ponen los de Persistance -para el proyecto (`repositorios_de`). +para el proyecto (`repositories_of`). """ import logging @@ -16,28 +16,28 @@ from hamilton import driver from hamilton.execution.graph_functions import topologically_sort_nodes from hamilton.lifecycle import NodeExecutionHook -from webapi.orquestacion import ciclo -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.proyecto import definiciones_de_cohorte -from webapi.orquestacion.repositorios import repositorios_de +from webapi.orchestration import cycle +from webapi.orchestration.context import Context +from webapi.orchestration.project import cohort_definitions +from webapi.orchestration.repositories import repositories_of -registro = logging.getLogger(__name__) +log = logging.getLogger(__name__) @dataclass(frozen=True) -class Paso: +class Step: """Lo que dejó un paso: su resumen y cuánto tardó.""" - nombre: str - resumen: Any - segundos: float + name: str + summary: Any + seconds: float -class _Bitacora(NodeExecutionHook): +class _Logbook(NodeExecutionHook): """Anota cada paso que corre, en el orden en que corre.""" def __init__(self): - self.pasos: list[Paso] = [] + self.pasos: list[Step] = [] self._inicio = 0.0 def run_before_node_execution(self, **_): @@ -45,44 +45,44 @@ class _Bitacora(NodeExecutionHook): def run_after_node_execution(self, *, node_name: str, result: Any, success: bool, **_): if success: - self.pasos.append(Paso(node_name, result, time.monotonic() - self._inicio)) - registro.info("%s: %s en %.1f s", node_name, _corto(result), self.pasos[-1].segundos) + self.pasos.append(Step(node_name, result, time.monotonic() - self._inicio)) + log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds) def _driver(proyecto: str, *adaptadores) -> driver.Driver: return (driver.Builder() - .with_modules(ciclo) - .with_config({"con_cohortes": bool(definiciones_de_cohorte(proyecto))}) + .with_modules(cycle) + .with_config({"with_cohorts": bool(cohort_definitions(proyecto))}) .with_adapters(*adaptadores) .build()) -def _en_orden(dr: driver.Driver) -> list[str]: +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 pasos_de(proyecto: str) -> list[str]: - """Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, solo donde hay definiciones).""" - return _en_orden(_driver(proyecto)) +def steps_of(proyecto: str) -> 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)) -def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]: - """Corre el ciclo del proyecto en el orden de sus dependencias. `solo`: los pasos a correr; los demás no corren. +def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]: + """Corre el ciclo del proyecto en el orden de sus dependencias. `only`: los pasos a correr; los demás no corren. Los pasos que no corren se le dan a Hamilton ya resueltos. Así entre dos pedidos puede no quedar dependencia - (`cargar` y `calcular` sin `vistas`), por eso se le piden en el orden del grafo completo. + (`load` y `compute` sin `views`), por eso se le piden en el orden del grafo completo. """ if ctx.repos is None: - ctx = replace(ctx, repos=repositorios_de(ctx.proyecto)) - bitacora = _Bitacora() - dr = _driver(ctx.proyecto, bitacora) - todos = _en_orden(dr) - pedidos = [p for p in todos if solo is None or p in solo] + ctx = replace(ctx, repos=repositories_of(ctx.project)) + bitacora = _Logbook() + dr = _driver(ctx.project, 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}) return bitacora.pasos -def _corto(resumen: Any) -> str: +def _short(resumen: Any) -> str: if isinstance(resumen, dict): return f"{len(resumen)} elementos" return str(resumen) diff --git a/webapi/orquestacion/semantic_layer.py b/webapi/orchestration/semantic_layer.py similarity index 100% rename from webapi/orquestacion/semantic_layer.py rename to webapi/orchestration/semantic_layer.py diff --git a/webapi/orquestacion/__init__.py b/webapi/orquestacion/__init__.py deleted file mode 100644 index c365484..0000000 --- a/webapi/orquestacion/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -"""El ciclo de indicadores de cada proyecto (CaCu, CaMa, TEA): del staging que deja -la ingesta a los reportes que publica el tablero. Lo corre -[Hamilton](https://hamilton.apache.org/). - -Cada paso es una función de `ciclo.py`. Recibe el `Contexto` y, como parámetros, -los pasos que deben correr antes; Hamilton arma el grafo con esos nombres. Los -pasos no se pasan datos: todo va por la base, a través de los repositorios de -Persistance (`ctx.repos`), así que cada uno se puede correr solo. El cálculo es -del kit (`indicadores_kit`); aquí solo se decide qué se lee, a qué repositorio -se le pasa y en qué orden. - - migrar -> catalogos, registro, definiciones - catalogos -> cargar - cargar -> vistas, cohortes - vistas + registro + definiciones -> calcular - calcular -> observar, verificar_plata - cohortes -> estimar (solo donde hay cohortes: hoy, CaCu) - - uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026 - uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular - uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica" - -El servicio `indicadores` (`webapi.indicadores_vivos`) corre este mismo ciclo, -sin `migrar`, cada vez que una importación escribe datos. - -Módulo | Qué hace ----------------|--------- -`ciclo.py` | Los pasos -`ejecutor.py` | `correr(ctx, solo=...)`: arma el driver de Hamilton y corre los pasos pedidos en orden -`contexto.py` | El `Contexto`: proyecto, años, corte, parámetros y repositorios -`repositorios.py` | `repositorios_de(proyecto)`: los repositorios de Persistance, por capa -`proyecto.py` | Tipos de periodo y definiciones de cohorte de un proyecto -`conexion.py` | Apunta Persistance a otra base en el mismo proceso (pruebas) -""" - -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.ejecutor import Paso, correr, pasos_de - -__all__ = ["Contexto", "Paso", "correr", "pasos_de"] diff --git a/webapi/orquestacion/__main__.py b/webapi/orquestacion/__main__.py deleted file mode 100644 index f970967..0000000 --- a/webapi/orquestacion/__main__.py +++ /dev/null @@ -1,63 +0,0 @@ -"""La línea de comandos de la orquestación. - - uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026 [--corte 2026-01-01] [--permitir-sin-definir] - uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular - uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica" [--anular] - -La base es la de `_DATABASE_URL`, como en Persistance. -""" - -import argparse -import logging -from datetime import date -from pathlib import Path - -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.ejecutor import correr - -PROYECTOS = ("cacu", "cama") - - -def main(argv: list[str] | None = None) -> None: - lector = argparse.ArgumentParser(prog="orquestacion", description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ordenes = lector.add_subparsers(dest="orden", required=True) - c = ordenes.add_parser("ciclo", help="corre los pasos del proyecto en orden") - c.add_argument("proyecto", choices=PROYECTOS) - c.add_argument("--desde", type=int, required=True, help="primer año de periodos") - c.add_argument("--hasta", type=int, required=True, help="último año de periodos") - c.add_argument("--corte", type=date.fromisoformat, default=None) - c.add_argument("--permitir-sin-definir", action="store_true") - c.add_argument("--parametros", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)") - c.add_argument("--solo", nargs="+", default=None, help="solo estos pasos") - r = ordenes.add_parser("confirmar-riesgos", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)") - r.add_argument("proyecto", choices=PROYECTOS) - r.add_argument("lote_id", type=int) - r.add_argument("--motivo", required=True, help="por qué se confirma o se anula; queda en cada evaluación") - r.add_argument("--anular", action="store_true", help="anular (entered-in-error) en vez de confirmar") - args = lector.parse_args(argv) - - if args.orden == "confirmar-riesgos": - cambiadas = confirmar_riesgos(args.proyecto, args.lote_id, args.motivo, anular=args.anular) - print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.anular else 'confirmadas'}") - return - logging.basicConfig(level=logging.INFO, format="%(message)s") - ctx = Contexto(args.proyecto, args.desde, args.hasta, args.corte, args.permitir_sin_definir, args.parametros) - for paso in correr(ctx, solo=args.solo): - print(f"{paso.nombre:20} {paso.segundos:6.1f} s") - - -def confirmar_riesgos(proyecto: str, lote_id: int, motivo: str, *, anular: bool = False) -> int: - """Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva. - - No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008). - """ - from persistance.aristas.oro import ERROR, FINAL - - from webapi.orquestacion.repositorios import repositorios_de - - return repositorios_de(proyecto).oro.cohorte.cambiar_estado(lote_id, ERROR if anular else FINAL, motivo) - - -if __name__ == "__main__": - main() diff --git a/webapi/orquestacion/repositorios.py b/webapi/orquestacion/repositorios.py deleted file mode 100644 index 68f87e6..0000000 --- a/webapi/orquestacion/repositorios.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro. - -Las subclases viven en `persistance/aristas//` y se -instancian en `persistance//__init__.py` con la fábrica de sesión del -dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión. -""" - -from dataclasses import dataclass -from importlib import import_module - -from persistance.aristas.bronce import StagingRepository -from persistance.aristas.oro import ( - CalculoRepository, - CohorteRepository, - PublicacionRepository, - RegistroRepository, -) -from persistance.aristas.plata import ( - CargaRepository, - CatalogoRepository, - ObservacionRepository, - TimelineRepository, - VinculosRepository, - VistasRepository, -) -from persistance.materializador import Materializador - - -@dataclass(frozen=True) -class Bronce: - """Lo que deja la ingesta. Solo se lee.""" - - staging: StagingRepository - - -@dataclass(frozen=True) -class Plata: - """Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata.""" - - catalogos: CatalogoRepository - carga: CargaRepository - vistas: VistasRepository - observacion: ObservacionRepository - vinculos: VinculosRepository - timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it - - -@dataclass(frozen=True) -class Oro: - """El registro (parámetros, periodos, definiciones), los reportes y las cohortes.""" - - parametros: RegistroRepository - periodos: RegistroRepository - calculo: CalculoRepository - publicacion: PublicacionRepository # el catálogo de publicación de §6f (T-19b) - cohorte: CohorteRepository | None # donde hay tablas de cohortes (los tres desde MD-12) - fechas: RegistroRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27) - grupos_edad: RegistroRepository | None = None # `dim_grupo_edad`, de `.grupos_edad` (I-MD27) - - -@dataclass(frozen=True) -class Repositorios: - """Todo lo que un paso usa para tocar la base de su proyecto, por capa.""" - - bronce: Bronce - plata: Plata - oro: Oro - # Una sesión para leer y escribir en el mismo paso (`cargar`). - materializador: Materializador | None = None - - -def repositorios_de(proyecto: str) -> Repositorios: - dominio = import_module(f"persistance.{proyecto}") - return Repositorios( - bronce=Bronce(staging=dominio.staging_repository), - plata=Plata( - catalogos=dominio.catalogo_repository, - carga=dominio.carga_repository, - vistas=dominio.vistas_repository, - observacion=dominio.observar_repository, - vinculos=dominio.vinculos_repository, - timeline=dominio.timeline_repository, - ), - materializador=dominio.materializador, - oro=Oro( - parametros=dominio.def_parametro_repository, - periodos=dominio.dim_periodo_repository, - calculo=dominio.calculo_repository, - publicacion=dominio.publicacion_repository, - cohorte=getattr(dominio, "cohorte_repository", None), - fechas=getattr(dominio, "dim_fecha_repository", None), - grupos_edad=getattr(dominio, "dim_grupo_edad_repository", None), - ), - ) - diff --git a/webapi/patient_risk.py b/webapi/patient_risk.py index a0eb2f0..d6d64f9 100644 --- a/webapi/patient_risk.py +++ b/webapi/patient_risk.py @@ -24,8 +24,8 @@ def patient_risk_blueprint(repositories) -> Blueprint: """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.cohorte_repository.membership(pac_id, COHORT_URL) - risk = repositories.cohorte_repository.current_risk(pac_id) + 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 diff --git a/webapi/indicadores_vivos.py b/webapi/recomputation.py similarity index 71% rename from webapi/indicadores_vivos.py rename to webapi/recomputation.py index 0b38ccc..77f4b40 100644 --- a/webapi/indicadores_vivos.py +++ b/webapi/recomputation.py @@ -1,9 +1,9 @@ """Recomputes a domain's indicators after its staging tables change. -A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`), +A successful import asks for a recomputation (`RecomputationQueue.solicitar`), which only drops a marker file. A separate process (`python -m -webapi.indicadores_vivos`, the `indicadores` compose service) picks the -markers up and runs that domain's cycle (`webapi.orquestacion.correr`): catalogs -> +webapi.recomputation`, the `indicadores` compose service) picks the +markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs -> staging to facts -> views -> registry -> definitions -> reports. Requests that arrive while a domain is running are folded into one more run. @@ -26,7 +26,7 @@ from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message -DOMINIOS = ("cacu", "cama") # the domains whose measures the cycle computes +DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) @@ -41,7 +41,7 @@ def _short(value: Any) -> str: return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…" -class ColaDeRecalculo: +class RecomputationQueue: """Marker-file queue and status of the indicator recomputations.""" def __init__(self, base: Path | None = None): @@ -55,18 +55,18 @@ class ColaDeRecalculo: def _status_path(self) -> Path: return self.base / "estado.json" - def solicitar(self, dominio: str) -> None: - if dominio not in DOMINIOS: + def request_run(self, dominio: str) -> None: + if dominio not in DOMAINS: raise ValueError(f"dominio desconocido: {dominio!r}") self._pending.mkdir(parents=True, exist_ok=True) (self._pending / dominio).write_text(_now(), encoding="utf-8") - def pendientes(self) -> list[str]: + def pending(self) -> list[str]: if not self._pending.exists(): return [] - return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS) + return sorted(p.name for p in self._pending.iterdir() if p.name in DOMAINS) - def tomar(self, dominio: str) -> bool: + def take(self, dominio: str) -> bool: """Consumes the marker; a request made from now on queues one more run.""" try: (self._pending / dominio).unlink() @@ -74,15 +74,15 @@ class ColaDeRecalculo: except FileNotFoundError: return False - def estado(self) -> dict[str, Any]: + def status(self) -> dict[str, Any]: try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} - pending = set(self.pendientes()) - return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS} + pending = set(self.pending()) + return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMAINS} - def _guardar_estado(self, dominio: str, entrada: dict[str, Any]) -> None: + def _save_status(self, dominio: str, entrada: dict[str, Any]) -> None: self.base.mkdir(parents=True, exist_ok=True) lock = self.base / ".estado.lock" with open(lock, "w") as handle: @@ -96,58 +96,58 @@ class ColaDeRecalculo: tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8") tmp.replace(self._status_path) - def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: - """Runs the domain's graph (without `migrar`: the API migrates on startup).""" - from webapi.orquestacion import Contexto, correr, pasos_de + def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: + """Runs the domain's graph (without `migrate`: the API migrates on startup).""" + from webapi.orchestration import Context, run, steps_of desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5)) hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year)) inicio = _now() started = time.monotonic() - self._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) + self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: - ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True) - pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"]) + ctx = Context(dominio, desde, hasta, allow_undecided=True) + pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) entrada.update( estado="ok", - pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos], + pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos], ) except Exception as exc: # the worker must survive a failing domain log.exception("recálculo de %s falló", dominio) entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}) entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2)) - self._guardar_estado(dominio, entrada) + self._save_status(dominio, entrada) try: JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada}) except OSError: pass return entrada - def atender(self) -> list[str]: + def serve(self) -> list[str]: """Runs every pending domain once; returns the ones it ran.""" ran = [] - for dominio in self.pendientes(): - if self.tomar(dominio): - self.correr(dominio) + for dominio in self.pending(): + if self.take(dominio): + self.run(dominio) ran.append(dominio) return ran def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") - cola = ColaDeRecalculo() + cola = RecomputationQueue() interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1": - for dominio in DOMINIOS: - cola.solicitar(dominio) + for dominio in DOMAINS: + cola.request_run(dominio) stop = threading.Event() signal.signal(signal.SIGTERM, lambda *_: stop.set()) signal.signal(signal.SIGINT, lambda *_: stop.set()) log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base) while True: - for dominio in cola.atender(): - log.info("%s: %s", dominio, cola.estado()[dominio].get("estado")) + for dominio in cola.serve(): + log.info("%s: %s", dominio, cola.status()[dominio].get("estado")) if stop.wait(interval): break -- 2.53.0 From 270e229a51186c1abdcf56ddcc3dc7fa46ccd5c2 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 03/24] The kit's silver load, reference tables, table maps and follow-up list move into the WebApi; the kit is no longer a dependency --- Dockerfile | 3 +- README.md | 5 +- pyproject.toml | 2 - tests/conftest.py | 4 +- tests/staging/__init__.py | 1 + tests/staging/cacu.py | 187 +++++ tests/staging/cama.py | 171 +++++ tests/test_metrics_on_request.py | 6 +- tests/test_orquestacion_ciclo.py | 2 +- tests/test_orquestacion_oro.py | 10 +- tests/test_orquestacion_plata.py | 10 +- uv.lock | 55 -- webapi/__init__.py | 2 +- webapi/follow_up/__init__.py | 7 + webapi/follow_up/estratos.toml | 53 ++ webapi/follow_up/functions.py | 100 +++ webapi/follow_up/listing.py | 296 ++++++++ webapi/follow_up/pivot.py | 110 +++ webapi/{follow_up.py => follow_up/routes.py} | 4 +- webapi/follow_up/silver.py | 99 +++ webapi/follow_up/status.py | 281 +++++++ webapi/follow_up/view.py | 26 + webapi/orchestration/cycle.py | 42 +- webapi/orchestration/project.py | 9 +- webapi/orchestration/reference/__init__.py | 0 webapi/orchestration/reference/age_groups.py | 61 ++ webapi/orchestration/reference/catalogs.py | 136 ++++ webapi/orchestration/reference/dates.py | 35 + .../orchestration/reference/parametros.toml | 701 ++++++++++++++++++ webapi/orchestration/reference/periods.py | 154 ++++ webapi/orchestration/reference/rules.py | 101 +++ webapi/orchestration/reference/support.py | 38 + webapi/orchestration/silver/__init__.py | 10 + webapi/orchestration/silver/cacu.py | 69 ++ webapi/orchestration/silver/cama.py | 46 ++ webapi/orchestration/silver/loads.py | 47 ++ .../silver/observation_periods.py | 97 +++ .../orchestration/silver/orders_and_notes.py | 73 ++ webapi/orchestration/silver/persons.py | 30 + webapi/orchestration/silver/procedures.py | 257 +++++++ webapi/orchestration/silver/quality.py | 43 ++ webapi/orchestration/silver/values.py | 44 ++ webapi/orchestration/silver/views.py | 72 ++ webapi/orchestration/tables/__init__.py | 87 +++ webapi/orchestration/tables/cacu.py | 77 ++ webapi/orchestration/tables/cama.py | 77 ++ 46 files changed, 3635 insertions(+), 105 deletions(-) create mode 100644 tests/staging/__init__.py create mode 100644 tests/staging/cacu.py create mode 100644 tests/staging/cama.py create mode 100644 webapi/follow_up/__init__.py create mode 100644 webapi/follow_up/estratos.toml create mode 100644 webapi/follow_up/functions.py create mode 100644 webapi/follow_up/listing.py create mode 100644 webapi/follow_up/pivot.py rename webapi/{follow_up.py => follow_up/routes.py} (92%) create mode 100644 webapi/follow_up/silver.py create mode 100644 webapi/follow_up/status.py create mode 100644 webapi/follow_up/view.py create mode 100644 webapi/orchestration/reference/__init__.py create mode 100644 webapi/orchestration/reference/age_groups.py create mode 100644 webapi/orchestration/reference/catalogs.py create mode 100644 webapi/orchestration/reference/dates.py create mode 100644 webapi/orchestration/reference/parametros.toml create mode 100644 webapi/orchestration/reference/periods.py create mode 100644 webapi/orchestration/reference/rules.py create mode 100644 webapi/orchestration/reference/support.py create mode 100644 webapi/orchestration/silver/__init__.py create mode 100644 webapi/orchestration/silver/cacu.py create mode 100644 webapi/orchestration/silver/cama.py create mode 100644 webapi/orchestration/silver/loads.py create mode 100644 webapi/orchestration/silver/observation_periods.py create mode 100644 webapi/orchestration/silver/orders_and_notes.py create mode 100644 webapi/orchestration/silver/persons.py create mode 100644 webapi/orchestration/silver/procedures.py create mode 100644 webapi/orchestration/silver/quality.py create mode 100644 webapi/orchestration/silver/values.py create mode 100644 webapi/orchestration/silver/views.py create mode 100644 webapi/orchestration/tables/__init__.py create mode 100644 webapi/orchestration/tables/cacu.py create mode 100644 webapi/orchestration/tables/cama.py diff --git a/Dockerfile b/Dockerfile index 9df8966..71d909d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build context is the repo root (see docker-compose.yml) so the sibling -# packages Core/, Persistance/, Extraction/, models/ and indicadores_kit/ +# packages Core/, Persistance/, Extraction/ and models/ # can be copied. FROM python:3.12-slim @@ -15,7 +15,6 @@ COPY Core/ Core/ COPY Persistance/ Persistance/ COPY Extraction/ Extraction/ COPY models/ models/ -COPY indicadores_kit/ indicadores_kit/ COPY WebApi/ WebApi/ # One environment for the API, the migrations and the indicator cycle. The SQL diff --git a/README.md b/README.md index 75ca482..819da3e 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ API REST de ISSSTELEON en Flask. Importa datos clínicos de varias fuentes a las bases de CaCu, CaMa y TEA, publica los indicadores ya calculados, guarda una bitácora agregada de cada importación y expone la gobernanza de modelos y de OCR. Usa `Persistance` para las bases, `Extraction` para documentos y -EEG, `indicadores_kit` para leer los indicadores y `orquestacion` para -recalcularlos. +EEG y `models` para las cohortes. Los indicadores se definen en dbt (`Transformation`) y se +responden bajo pedido (`//indicadores`); `orchestration` carga la plata, las tablas de +referencia y las vistas de dbt. ## Estructura diff --git a/pyproject.toml b/pyproject.toml index 20a65bd..7a4b5c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,6 @@ dependencies = [ "persistance", "models[export]", "extraction", - "indicadores-kit", "apache-hamilton>=1.90", "pandas>=2.0", "openpyxl>=3.1", @@ -34,7 +33,6 @@ sql-drivers = [ persistance = { path = "../Persistance", editable = true } models = { path = "../models", editable = true } extraction = { path = "../Extraction", editable = true } -indicadores-kit = { path = "../indicadores_kit", editable = true } [build-system] requires = ["hatchling"] diff --git a/tests/conftest.py b/tests/conftest.py index a0510cd..340f023 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,7 +19,7 @@ import pytest from sqlalchemy import create_engine from sqlmodel import Session -from indicadores_kit.registry.parametros import RUTA_PARAMETROS +from webapi.orchestration.reference.rules import RUTA_PARAMETROS from webapi.orchestration import Context, run from webapi.orchestration.connection import point_to from webapi.orchestration.repositories import repositories_of @@ -62,7 +62,7 @@ def base_de(proyecto: str, carpeta, datos=None) -> Base: run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: - (datos or import_module(f"indicadores_kit.{proyecto}.fixtures").insertar)(sesion) + (datos or import_module(f"staging.{proyecto}").insertar)(sesion) sesion.commit() return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor) diff --git a/tests/staging/__init__.py b/tests/staging/__init__.py new file mode 100644 index 0000000..ccb6a7a --- /dev/null +++ b/tests/staging/__init__.py @@ -0,0 +1 @@ +"""Synthetic staging rows for the tests, one module per domain: written by hand, never real data.""" diff --git a/tests/staging/cacu.py b/tests/staging/cacu.py new file mode 100644 index 0000000..e21430a --- /dev/null +++ b/tests/staging/cacu.py @@ -0,0 +1,187 @@ +"""Filas sintéticas del staging de CaCu, escritas a mano. Nunca datos reales. + +Seis pacientes y nueve citologías en dos semestres de 2025. Los textos de +calidad son provisionales: los valores reales están sin confirmar. + +Pacientes tamizadas: 4 en 2025-S1 y 4 en 2025-S2; de ellas, con muestra +insatisfactoria, 2 y 1. Lo que da cada indicador va abajo (`ESPERADO_*`). + +Casos que ejercita: H-003 tiene dos citologías en S1 y cuenta una vez; +H-004 tiene una el 1 de julio, que ya es S2; H-001 aparece en los dos +semestres. + +Resultados (v0.5.0, T-4): seis citologías tienen reporte y cuatro, VPH; +las dos insatisfactorias de H-002 y H-006 no tienen reporte, y la última +de H-001 todavía no. Tres biopsias, cada una con la citología que la +originó: dos reportadas y una pendiente. Los textos de resultado también +son provisionales. + +Cinco notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico +(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`). + +Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio. +""" + +from datetime import date + +from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente +from sqlmodel import Session, select + +SATISFACTORIO = "SATISFACTORIO" +INSATISFACTORIO = "INSATISFACTORIO" + +PACIENTES = ("H-001", "H-002", "H-003", "H-004", "H-005", "H-006") + +# (pac_id_hospital, fecha de toma, calidad del espécimen) +CITOLOGIAS = ( + ("H-001", date(2025, 2, 10), SATISFACTORIO), + ("H-002", date(2025, 3, 5), INSATISFACTORIO), + ("H-003", date(2025, 1, 20), INSATISFACTORIO), + ("H-003", date(2025, 4, 15), SATISFACTORIO), + ("H-004", date(2025, 5, 30), SATISFACTORIO), + ("H-004", date(2025, 7, 1), SATISFACTORIO), + ("H-005", date(2025, 8, 12), SATISFACTORIO), + ("H-006", date(2025, 9, 1), INSATISFACTORIO), + ("H-001", date(2025, 10, 2), SATISFACTORIO), +) + +# Índice en CITOLOGIAS -> (fecha de reporte, células escamosas, VPH, genotipo 16, genotipo 18). +RESULTADOS = { + 0: (date(2025, 2, 20), "NEGATIVO", None, None, None), + 2: (date(2025, 2, 1), "ASC-US", "POSITIVO", 1, 0), + 3: (date(2025, 4, 25), "LIEBG", "POSITIVO", 0, 0), + 4: (date(2025, 6, 9), "NEGATIVO", None, None, None), + 5: (date(2025, 7, 11), "LIEAG", "POSITIVO", 0, 1), + 6: (date(2025, 8, 22), "NEGATIVO", "NEGATIVO", None, None), +} + +# (índice de la citología que la originó, fecha de solicitud, fecha de reporte, grado CIN) +BIOPSIAS = ( + (3, date(2025, 5, 1), date(2025, 5, 20), "CIN1"), + (5, date(2025, 7, 15), date(2025, 8, 1), "CIN2"), + (6, date(2025, 9, 1), None, None), +) + +# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital). +COLPOSCOPIA, ONCOLOGIA, FAMILIAR = "CLINICA DE MUJER Y COLPOSCOPIA", "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR" +NOTAS = ( + ("H-004", date(2025, 8, 10), "D06.9", COLPOSCOPIA), # 72 días de su toma de mayo y 40 de la de julio + ("H-003", date(2024, 12, 1), "C53.9", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo + ("H-001", date(2025, 3, 1), "N87.1", FAMILIAR), # displasia, pero de medicina familiar: no resuelve + ("H-002", date(2025, 9, 15), "C53", ONCOLOGIA), # a 194 días de su toma: fuera del horizonte + ("H-005", date(2026, 1, 20), "c539", COLPOSCOPIA), # 161 días de su toma, pero después del corte de fin de año +) + +# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital). +# La segunda no es de tamizaje; la especialidad de la tercera no está en el catálogo de Core +# y queda sin reconocer; la cuarta está pedida y todavía no tiene citología. +ORDENES = ( + (50001, "H-001", date(2025, 2, 3), "MEDICINA FAMILIAR"), + (50002, "H-003", date(2025, 4, 10), "CLINICA DE MUJER Y COLPOSCOPIA"), + (50003, "H-004", date(2025, 6, 25), "Dermatología"), + (50004, "H-005", date(2025, 12, 1), "MEDICINA FAMILIAR"), +) + +# Índice en CITOLOGIAS -> número de su orden. Las demás citologías no traen número; la de +# H-005 trae uno que no existe entre las órdenes. +ORDEN_DE_CITOLOGIA = {0: 50001, 3: 50002, 5: 50003, 6: 59999} + +# periodo -> (denominador, numerador) de IND1, con la lista de `cacu.citologia_anomala` +# (ASC-US, ASC-H, LIEBG, LIEAG, CIS). En S1 solo H-003 (su ASC-US y su LIEBG; cuenta una +# vez); en S2 solo H-004 (su LIEAG del 1 de julio). +ESPERADO_IND1 = {"2025-S1": (4, 1), "2025-S2": (4, 1)} + +# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CACU_EU_TIEMPO_REPORTE, +# con horizonte de 60 días. Días de toma a resultado: S1 10, 12, 10, 10 (la toma del 5 de +# marzo no tiene resultado y a fin de año ya pasó el horizonte: cuenta en la inicial y no en +# n); S2 10, 10. A mediados de octubre las tomas de septiembre y octubre sin resultado siguen +# dentro del horizonte: no se miden. A mediados de agosto el resultado del 22 todavía no existe. +ESPERADO_CACU_TIEMPO = { + ("2025-S1", "2025-12-31"): (5, 4, 10.0, 10.0, 10.5), + ("2025-S2", "2025-12-31"): (4, 2, 10.0, 10.0, 10.0), + ("2025-S2", "2025-10-15"): (2, 2, 10.0, 10.0, 10.0), + ("2025-S2", "2025-08-15"): (1, 1, 10.0, 10.0, 10.0), +} + +# periodo -> (denominador, numerador) de CACU_EU13, con la lista de arranque de +# `cacu.deteccion_grados` (LIEAG, CIS, CARCINOMA). Los grados de las biopsias de +# este fixture (CIN1, CIN2) son textos provisionales que no están en esa lista: +# el numerador es cero. El distinto de cero se prueba con filas escritas a mano +# en `cacu/familias/eu13/casos.toml`. +ESPERADO_CACU_EU13 = {"2025-S1": (4, 0), "2025-S2": (4, 0)} + +# periodo -> {categoría: pacientes} de CACU_EU7 (solo las que tienen alguna). En S1, H-003 +# cuenta con el LIEBG de abril (su ASC-US de enero es de una muestra insatisfactoria y, +# además, anterior) y H-002 no tiene resultado; en S2, H-006 no tiene resultado y la de +# octubre de H-001 todavía no. «NEGATIVO» es un texto provisional de este fixture: no está +# en el catálogo (que usa NORMAL, como Core) y sale después de SIN_DATO. +ESPERADO_CACU_EU7 = { + "2025-S1": {"NEGATIVO": 2, "LIEBG": 1, "SIN_DATO": 1}, + "2025-S2": {"NEGATIVO": 1, "LIEAG": 1, "SIN_DATO": 2}, +} + + +def insertar(sesion: Session) -> None: + """Inserta pacientes, órdenes, citologías y biopsias. `pac_id` se resuelve por `pac_id_hospital`.""" + pacientes = { + hospital: Paciente( + pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1) + ) + for hospital in PACIENTES + } + sesion.add_all(pacientes.values()) + sesion.flush() + sesion.add_all( + OrdenesEstudio( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=numero, + ord_tipo_estudio="SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + ord_fecha=fecha, + ord_especialidad=especialidad, + ) + for numero, hospital, fecha, especialidad in ORDENES + ) + citologias = [] + for indice, (hospital, toma, calidad) in enumerate(CITOLOGIAS): + reporte, escamosas, vph, genotipo_16, genotipo_18 = RESULTADOS.get(indice, (None,) * 5) + citologias.append( + CitologiaCervical( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=ORDEN_DE_CITOLOGIA.get(indice), + cit_fecha_toma=toma, + cit_calidad_especimen=calidad, + cit_fecha_reporte=reporte, + cit_celulas_escamosas=escamosas, + cit_vph_resultado=vph, + cit_vph_genotipo_16=genotipo_16, + cit_vph_genotipo_18=genotipo_18, + ) + ) + sesion.add_all(citologias) + sesion.flush() + for indice, solicitud, reporte, grado in BIOPSIAS: + citologia = citologias[indice] + sesion.add( + BiopsiaCervical( + pac_id=citologia.pac_id, + pac_id_hospital=citologia.pac_id_hospital, + cit_id=citologia.cit_id, + bx_fecha_solicitud=solicitud, + bx_fecha_reporte=reporte, + bx_cin_grado=grado, + ) + ) + sesion.add_all( + NotaMedica( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + nm_id_hospital=f"NM-{numero:03d}", + nm_fecha=fecha, + nm_cie_codigo=cie, + nm_especialidad=especialidad, + ) + for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1) + ) + sesion.commit() diff --git a/tests/staging/cama.py b/tests/staging/cama.py new file mode 100644 index 0000000..1b56465 --- /dev/null +++ b/tests/staging/cama.py @@ -0,0 +1,171 @@ +"""Filas sintéticas del staging de CaMa, escritas a mano. Nunca datos reales. + +Seis pacientes y nueve mastografías en dos semestres de 2025. Los textos +de calidad son provisionales: los valores reales están sin confirmar. + +Mastografías: 5 en 2025-S1 y 4 en 2025-S2; de ellas, satisfactorias, 4 y 2. +Lo que da cada indicador va abajo (`ESPERADO_*`). + +Casos que ejercita: H-001 tiene dos mastografías en S1 y cuentan las dos; +una del 1 de julio ya es S2; una de S2 no tiene calidad y cuenta en el +denominador pero no en el numerador. + +Resultados (v0.5.0, T-4): cada mastografía trae su BI-RADS; tiene fecha +de reporte una semana después de la toma, salvo la que no tiene calidad +ni BI-RADS y la última, todavía sin reporte. + +Tres biopsias, cada una con la mastografía que la originó: dos con +reporte y grado, y una solicitada que todavía no lo tiene. + +Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico +(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`). + +H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`: +lo único común entre los dos sistemas es `pac_id_hospital`. + +Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio. +""" + +from datetime import date, timedelta + +from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente +from sqlmodel import Session, select + +SATISFACTORIO = "SATISFACTORIO" +INSATISFACTORIO = "INSATISFACTORIO" + +PACIENTES = ("H-101", "H-102", "H-001", "H-003", "H-103", "H-104") + +# (pac_id_hospital, fecha de toma, calidad de imagen, BI-RADS) +MASTOGRAFIAS = ( + ("H-101", date(2025, 1, 15), SATISFACTORIO, "B1"), + ("H-102", date(2025, 2, 20), SATISFACTORIO, "B2"), + ("H-001", date(2025, 3, 10), INSATISFACTORIO, "B0"), + ("H-001", date(2025, 4, 2), SATISFACTORIO, "B1"), + ("H-003", date(2025, 6, 30), SATISFACTORIO, "B4A"), + ("H-103", date(2025, 7, 1), SATISFACTORIO, "B1"), + ("H-103", date(2025, 9, 9), None, None), + ("H-104", date(2025, 11, 11), INSATISFACTORIO, "B0"), + ("H-102", date(2025, 12, 31), SATISFACTORIO, "B2"), +) + +# (índice de la mastografía que la originó, fecha de solicitud, fecha de reporte, grado histológico) +BIOPSIAS = ( + (2, date(2025, 3, 20), date(2025, 4, 5), "BENIGNO"), + (4, date(2025, 7, 10), date(2025, 7, 28), "CARCINOMA_INVASOR"), + (7, date(2025, 11, 20), None, None), +) + +# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital). +# La de H-003 llega con minúscula y punto; la de H-104 no tiene fecha y la de H-101 es de +# medicina familiar, que no resuelve la toma. +ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR" +NOTAS = ( + ("H-003", date(2025, 8, 4), "c50.4", ONCOLOGIA), # 35 días de su B4A del 30 de junio + ("H-001", date(2025, 3, 1), "D05.1", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo + ("H-102", date(2025, 9, 30), "C50.9", ONCOLOGIA), # a 222 días de su toma de febrero: fuera del horizonte + ("H-103", date(2025, 7, 20), "C50.9", ONCOLOGIA), # 19 días de su toma del 1 de julio + ("H-101", date(2025, 1, 15), "Z12.3", FAMILIAR), # normal, pero de medicina familiar: no resuelve + ("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta +) + +# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital). +# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía. +ORDENES = ( + (60001, "H-101", date(2025, 1, 10), "MEDICINA FAMILIAR"), + (60002, "H-003", date(2025, 6, 20), "CIRUGIA ONCOLOGICA"), + (60003, "H-104", date(2025, 12, 5), "MEDICINA FAMILIAR"), +) + +# Índice en MASTOGRAFIAS -> número de su orden. Las demás no traen número; la de H-102 trae +# uno que no existe entre las órdenes. +ORDEN_DE_MASTOGRAFIA = {0: 60001, 4: 60002, 1: 69999} + +# periodo -> {categoría: pacientes} de CAMA_BIRADS (solo las que tienen alguna). +# H-001 tiene B0 y B1 en S1: cuenta en B0, la más grave. H-103 tiene B1 y una toma sin +# reporte: cuenta en B1. H-102 tiene en S2 solo una toma sin reporte: SIN_DATO. +ESPERADO_CAMA_BIRADS = { + "2025-S1": {"B0": 1, "B1": 1, "B2": 1, "B4A": 1}, + "2025-S2": {"B0": 1, "B1": 1, "SIN_DATO": 1}, +} + +# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CAMA_EU38A, con +# horizonte de 60 días. Todo reporte llega siete días después de la toma. A fin de año la +# toma del 9 de septiembre ya pasó el horizonte sin reporte (cuenta en la inicial y no en n) +# y la del 31 de diciembre sigue en observación. El 15 de septiembre ninguna toma de S2 +# posterior a julio tiene reporte ni ha vencido: solo se mide la del 1 de julio. +ESPERADO_CAMA_EU38A = { + ("2025-S1", "2025-12-31"): (5, 5, 7.0, 7.0, 7.0), + ("2025-S2", "2025-12-31"): (3, 2, 7.0, 7.0, 7.0), + ("2025-S2", "2025-09-15"): (1, 1, 7.0, 7.0, 7.0), +} + +# periodo -> (denominador, numerador) de CAMA_CONFIRMACION_BIRADS45, con la lista de arranque de +# `cama.birads_sospecha` (B4 con o sin subcategoría, B5). La única mastografía de sospecha es la B4A de H-003 del 30 de +# junio, y su biopsia se reportó el 28 de julio: cuenta en S1, el semestre de la mastografía. +# Las otras dos biopsias salen de mastografías B0, que no están en la lista. En S2 no hay +# ninguna de sospecha: sin denominador, el reporte sale suprimido y no se compara. +ESPERADO_CAMA_CONFIRMACION_BIRADS45 = {"2025-S1": (1, 1)} + + +def insertar(sesion: Session) -> None: + """Inserta pacientes, órdenes, mastografías, biopsias y notas. `pac_id` se resuelve por `pac_id_hospital`.""" + pacientes = { + hospital: Paciente( + pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1975, 1, 1) + ) + for hospital in PACIENTES + } + sesion.add_all(pacientes.values()) + sesion.flush() + sesion.add_all( + OrdenesEstudio( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=numero, + ord_tipo_estudio="MASTOGRAFIA", + ord_fecha=fecha, + ord_especialidad=especialidad, + ) + for numero, hospital, fecha, especialidad in ORDENES + ) + mastografias = [] + for indice, (hospital, toma, calidad, birads) in enumerate(MASTOGRAFIAS): + sin_reporte = birads is None or indice == len(MASTOGRAFIAS) - 1 + mastografias.append( + Mastografia( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=ORDEN_DE_MASTOGRAFIA.get(indice), + mast_fecha_toma=toma, + mast_calidad_imagen=calidad, + mast_birads=birads, + mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7), + ) + ) + sesion.add_all(mastografias) + sesion.flush() + for indice, solicitud, reporte, grado in BIOPSIAS: + mastografia = mastografias[indice] + sesion.add( + BiopsiaMama( + pac_id=mastografia.pac_id, + pac_id_hospital=mastografia.pac_id_hospital, + mast_id=mastografia.mast_id, + bx_fecha_solicitud=solicitud, + bx_fecha_reporte=reporte, + bx_grado_histologico=grado, + ) + ) + sesion.add_all( + NotaMedica( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + nm_id_hospital=f"NM-{numero:03d}", + nm_fecha=fecha, + nm_cie_codigo=cie, + nm_especialidad=especialidad, + ) + for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1) + ) + sesion.commit() diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py index ea6f3e0..ee03ccc 100644 --- a/tests/test_metrics_on_request.py +++ b/tests/test_metrics_on_request.py @@ -330,9 +330,9 @@ def kit_status(base, reference: str) -> dict[str, str]: """What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules.""" import tomllib - from indicadores_kit.cacu.seguimiento import estatus_al, reglas_de - from indicadores_kit.registry.parametros import RUTA_PARAMETROS - from indicadores_kit.serving.seguimiento import leer_estrato + from webapi.follow_up.status import estatus_al, reglas_de + from webapi.orchestration.reference.rules import RUTA_PARAMETROS + from webapi.follow_up.listing import leer_estrato from sqlalchemy import bindparam rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8")) diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 8ec5f4a..63cde16 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -39,7 +39,7 @@ def bases(request, tmp_path_factory): run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: - import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) + import_module(f"staging.{proyecto}").insertar(sesion) sesion.commit() pasos = run(ctx) return proyecto, ctx, motor, None, pasos diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 7bfe6ab..9da68bd 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -8,11 +8,11 @@ from datetime import date import pytest -from indicadores_kit.plata.carga import tablas_de_staging -from indicadores_kit.registry.edades import grupos_de_cortes -from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo -from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.tablas import tablas_de +from webapi.orchestration.silver.loads import tablas_de_staging +from webapi.orchestration.reference.age_groups import grupos_de_cortes +from webapi.orchestration.reference.rules import RUTA_PARAMETROS, valores_del_archivo +from webapi.orchestration.reference.periods import periodos_de_tipos +from webapi.orchestration.tables import tablas_de from webapi.orchestration.project import period_types from conftest import ANIO diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 96d743b..57d5940 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -10,15 +10,15 @@ from datetime import date import pytest from conftest import base_de -from indicadores_kit.plata.carga import tablas_de_staging -from indicadores_kit.plata.periodo_observacion import ( +from webapi.orchestration.silver.loads import tablas_de_staging +from webapi.orchestration.silver.observation_periods import ( TIPO_EXTRACCION, ObservacionSinCorte, clave_de_inicio, ) -from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.registry.parametros import RUTA_PARAMETROS, ParametroSinDefinir -from indicadores_kit.tablas import tablas_de +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.reference.rules import RUTA_PARAMETROS, ParametroSinDefinir +from webapi.orchestration.tables import tablas_de from sqlalchemy import inspect, text from sqlmodel import select diff --git a/uv.lock b/uv.lock index cac27f0..1c55eb9 100644 --- a/uv.lock +++ b/uv.lock @@ -1120,34 +1120,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/55/ecca97ae19075f1fac62def77731e7f535e6c1fb8f92ff08160c5e6dade8/importlib_metadata-9.0.1-py3-none-any.whl", hash = "sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0", size = 27920, upload-time = "2026-08-28T15:30:33.433Z" }, ] -[[package]] -name = "indicadores-kit" -version = "0.8.0" -source = { editable = "../indicadores_kit" } -dependencies = [ - { name = "core" }, - { name = "pandas" }, - { name = "pandera" }, - { name = "persistance" }, - { name = "plotly" }, - { name = "sqlalchemy-utils" }, - { name = "sqlmodel" }, -] - -[package.metadata] -requires-dist = [ - { name = "core", editable = "../Core" }, - { name = "pandas", specifier = "==3.0.6" }, - { name = "pandera", specifier = "==0.33.1" }, - { name = "persistance", editable = "../Persistance" }, - { name = "plotly", specifier = "==7.1.0" }, - { name = "sqlalchemy-utils", specifier = "==0.42.1" }, - { name = "sqlmodel", specifier = "==0.0.47" }, -] - -[package.metadata.requires-dev] -dev = [{ name = "pytest", specifier = "==9.1.1" }] - [[package]] name = "iniconfig" version = "2.3.0" @@ -2173,19 +2145,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" }, ] -[[package]] -name = "plotly" -version = "7.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "narwhals" }, - { name = "packaging" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/49/c3/72b369f5ed7701b04ab0ea3dcf83e9bbce71c0b3bc6f07f87568550d09ea/plotly-7.1.0.tar.gz", hash = "sha256:f860166a4a3d78c69cb1f4a15f28a5c8283eade98a282a698f3bb853a449ace5", size = 6689315, upload-time = "2026-09-15T19:21:21.75Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl", hash = "sha256:dbb7fa18afce40d0a8e80d1bf162eceb3faa0ce5a77fe741ad09a74cf78f53f3", size = 9692368, upload-time = "2026-09-15T19:21:18.331Z" }, -] - [[package]] name = "pluggy" version = "1.6.0" @@ -3105,18 +3064,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/a1/bd5e3e99bc9c8863b51ac5b9b03008a7f2da8c6b59695992f5c654e1265b/sqlalchemy-2.0.54-py3-none-any.whl", hash = "sha256:7e33a631ab1474f8fe6b910bd1a07b7b8009c4c78cdd3fb18001b03e3bc2e1d2", size = 1958015, upload-time = "2026-09-15T22:24:22.95Z" }, ] -[[package]] -name = "sqlalchemy-utils" -version = "0.42.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "sqlalchemy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/7d/eb9565b6a49426552a5bf5c57e7c239c506dc0e4e5315aec6d1e8241dc7c/sqlalchemy_utils-0.42.1.tar.gz", hash = "sha256:881f9cd9e5044dc8f827bccb0425ce2e55490ce44fc0bb848c55cc8ee44cc02e", size = 130789, upload-time = "2025-12-13T03:14:13.591Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/25/7400c18c3ee97914cc99c90007795c00a4ec5b60c853b49db7ba24d11179/sqlalchemy_utils-0.42.1-py3-none-any.whl", hash = "sha256:243cfe1b3a1dae3c74118ae633f1d1e0ed8c787387bc33e556e37c990594ac80", size = 91761, upload-time = "2025-12-13T03:14:15.014Z" }, -] - [[package]] name = "sqlglot" version = "30.27.0" @@ -3315,7 +3262,6 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "indicadores-kit" }, { name = "models", extra = ["export"] }, { name = "openpyxl" }, { name = "pandas" }, @@ -3349,7 +3295,6 @@ requires-dist = [ { name = "flask", specifier = ">=3.0" }, { name = "flask-cors", specifier = ">=4.0" }, { name = "gunicorn", specifier = ">=23.0" }, - { name = "indicadores-kit", editable = "../indicadores_kit" }, { name = "models", extras = ["export"], editable = "../models" }, { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2.0" }, diff --git a/webapi/__init__.py b/webapi/__init__.py index eca46bf..b217175 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -10,7 +10,7 @@ from webapi.blueprints.data import data_bp from webapi.blueprints.governance import governance_bp from webapi.blueprints.imports import imports_bp from webapi.blueprints.reports import reports_bp -from webapi.follow_up import follow_up_blueprint, in_dev +from webapi.follow_up.routes import follow_up_blueprint, in_dev class IsoJSONProvider(DefaultJSONProvider): diff --git a/webapi/follow_up/__init__.py b/webapi/follow_up/__init__.py new file mode 100644 index 0000000..3de6541 --- /dev/null +++ b/webapi/follow_up/__init__.py @@ -0,0 +1,7 @@ +"""CaCu's follow-up list (`GET /cacu/seguimiento`): one row per patient, with her ASCCP status and her latest studies. + + routes.py the route: validates the request and answers + listing.py the list: who enters it, what each row shows + status.py the ASCCP status of each patient at a date + silver.py, pivot.py, view.py, functions.py the silver queries they read +""" diff --git a/webapi/follow_up/estratos.toml b/webapi/follow_up/estratos.toml new file mode 100644 index 0000000..f31bcbb --- /dev/null +++ b/webapi/follow_up/estratos.toml @@ -0,0 +1,53 @@ +# Los estratos que un indicador puede declarar en `extension.estratos`. +# Cada uno es una función de SQLAlchemy que devuelve una CTE con +# (unidad_id, estrato); el cálculo la cruza con las poblaciones sin +# tocarlas (mart/estratos.py). +# +# expression "modulo.del.kit:funcion" +# unidad la unidad de los indicadores a los que sirve (`basis`) +# fechas lo que el estrato cruza con dim_fecha, si lo lee +# parametros sus reglas: parámetro de la consulta -> clave de parametros.toml (la +# función las recibe resueltas y entran a la huella del reporte) +# valores sus valores con su etiqueta, en orden, si no salen de otra regla +# etiqueta cómo se llama en pantalla (la leyenda, el selector de filtros); sin ella, su nombre +# +# Sección `comun`: para todos los proyectos; ``: solo ese, y +# gana sobre `comun` si se llaman igual. + +[comun.grupo_edad] +etiqueta = "Grupo de edad" +expression = "comun.estratos.grupo_edad:estrato" +unidad = "paciente" +fechas = { hechos = ["v_persona.fecha_nacimiento"], parametros = ["periodo_inicio"] } + +# Estatus de seguimiento ASCCP de la paciente (T-24c): `cacu/seguimiento.py`. Sus reglas son de +# `parametros.toml` (§2bis) y entran a la huella del reporte. Excluyente y exhaustivo: sin `sin_dato`. +[cacu.estatus_seguimiento] +etiqueta = "Estatus de seguimiento" +expression = "cacu.seguimiento:estrato" +unidad = "paciente" +valores = [ + { valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" }, + { valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" }, + { valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" }, + { valor = "INFO_INSUFICIENTE", etiqueta = "Información insuficiente" }, +] + +[cacu.estatus_seguimiento.parametros] +seguimiento_marco = "cacu.seguimiento.marco" +seguimiento_referencia = "cacu.seguimiento.referencia" +seguimiento_precedencia = "cacu.seguimiento.precedencia" +seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias" +seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito" +seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito" +seguimiento_cie_valoracion = "cacu.diagnostico.cie" +seguimiento_especialidades_valoracion = "cacu.diagnostico.especialidades" +seguimiento_horizonte_valoracion = "cacu.horizontes.toma_diagnostico_dias" +seguimiento_motivos = "cacu.seguimiento.colposcopia.motivos" +seguimiento_especialidades_colposcopia = "cacu.seguimiento.colposcopia.especialidades" +seguimiento_cie_colposcopia = "cacu.seguimiento.colposcopia.cie" +seguimiento_diagnosticos = "cacu.seguimiento.colposcopia.diagnosticos" +seguimiento_fuentes_tratamiento = "cacu.seguimiento.tratamiento.fuentes" +seguimiento_cie_tratamiento = "cacu.seguimiento.tratamiento.cie" +seguimiento_insuficiente = "cacu.seguimiento.insuficiente.regla" +seguimiento_especialidades_vigilancia = "cacu.seguimiento.vigilancia.especialidades" diff --git a/webapi/follow_up/functions.py b/webapi/follow_up/functions.py new file mode 100644 index 0000000..f13fbc4 --- /dev/null +++ b/webapi/follow_up/functions.py @@ -0,0 +1,100 @@ +"""Lo que cada motor escribe distinto, como una función con una regla por motor. + +SQLAlchemy traduce la sintaxis, no las funciones de fecha. Aquí van las +que el kit necesita. Agregar un motor es agregar su regla; ninguna +definición cambia. Sin regla para un motor queda la forma neutra, que es +la que lee el registro de huellas y no se puede ejecutar. Solo la regla +de SQLite se ejecuta en las pruebas (D-S5). +""" + +from sqlalchemy import Integer +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.sql.expression import FunctionElement + + +class dias_entre(FunctionElement): + """Días enteros de `inicio` a `fin`: `dias_entre(inicio, fin)`.""" + + type = Integer() + inherit_cache = True + + +def _partes(elemento, compilador, opciones) -> tuple[str, str]: + inicio, fin = list(elemento.clauses) + return compilador.process(inicio, **opciones), compilador.process(fin, **opciones) + + +@compiles(dias_entre) +def _neutra(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"dias_entre({inicio}, {fin})" + + +@compiles(dias_entre, "sqlite") +def _sqlite(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)" + + +@compiles(dias_entre, "postgresql") +def _postgresql(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))" + + +@compiles(dias_entre, "mysql", "mariadb") +def _mysql(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"DATEDIFF({fin}, {inicio})" + + +@compiles(dias_entre, "mssql") +def _mssql(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"DATEDIFF(day, {inicio}, {fin})" + + +class entero_de_json(FunctionElement): + """Un entero de un objeto JSON guardado como texto: `entero_de_json(columna, "clave")`. + + PostgreSQL no aplica `->>` a `text` y SQL Server no tiene tipo JSON: cada + motor lee la clave con su propia función. + """ + + type = Integer() + inherit_cache = True + + +def _columna_y_clave(elemento, compilador, opciones) -> tuple[str, str]: + columna, clave = list(elemento.clauses) + return compilador.process(columna, **opciones), clave.value + + +@compiles(entero_de_json) +def _entero_neutro(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"entero_de_json({columna}, '{clave}')" + + +@compiles(entero_de_json, "sqlite") +def _entero_sqlite(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(json_extract({columna}, '$.{clave}') AS INTEGER)" + + +@compiles(entero_de_json, "mysql", "mariadb") +def _entero_mysql(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(JSON_UNQUOTE(JSON_EXTRACT({columna}, '$.{clave}')) AS SIGNED)" + + +@compiles(entero_de_json, "postgresql") +def _entero_postgresql(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(CAST({columna} AS JSON) ->> '{clave}' AS INTEGER)" + + +@compiles(entero_de_json, "mssql") +def _entero_mssql(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(JSON_VALUE({columna}, '$.{clave}') AS INT)" diff --git a/webapi/follow_up/listing.py b/webapi/follow_up/listing.py new file mode 100644 index 0000000..fde56f0 --- /dev/null +++ b/webapi/follow_up/listing.py @@ -0,0 +1,296 @@ +"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, una fila por paciente. + +El contrato es T-24a. Es una consulta al +vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada paciente con al menos un +estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su +grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del +estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas +de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula. + +**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta +lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal. + +Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento` +de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna. +""" + +import calendar +import hashlib +import json +import tomllib +from datetime import date, timedelta +from pathlib import Path +from types import SimpleNamespace + +from sqlalchemy import func, select +from sqlmodel import Session + +from webapi.follow_up.silver import citologias, notas +from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de +from webapi.orchestration.tables.cacu import TABLAS +from webapi.follow_up.view import P +from webapi.orchestration.reference.age_groups import grupos_de_cortes +from webapi.orchestration.reference.rules import valor_de +from webapi.orchestration.tables import TablasKit + +RAIZ = Path(__file__).resolve().parent # `estratos.toml` is next to this module +SIN_DATO = "sin_dato" + + +def leer_estrato(proyecto: str, nombre: str) -> SimpleNamespace: + """The stratum's rules and values in `estratos.toml` (the project's, or the common one).""" + with open(RAIZ / "estratos.toml", "rb") as archivo: + secciones = tomllib.load(archivo) + for seccion in (proyecto, "comun"): + if nombre in secciones.get(seccion, {}): + entrada = secciones[seccion][nombre] + return SimpleNamespace(parametros=entrada.get("parametros", {}), valores=entrada.get("valores", [])) + raise KeyError(f"No hay estrato {nombre!r} para {proyecto!r} en estratos.toml.") + + +def ejecutar(sesion: Session, consulta, parametros: dict): + """Runs with the parameters the query names.""" + nombrados = set(consulta.compile().params) + return sesion.execute(consulta, {n: v for n, v in parametros.items() if n in nombrados}) + +VENTANAS = (1, 3, 6, 12) +FECHAS_DE_ESTUDIO = ("toma", "reporte") +ESTUDIOS = ("citologia", "vph") +RESULTADOS_MOSTRADOS = ("ultimo", "mas_grave") +PAGINA_MAXIMA = 200 +# Nombre en esta lista -> clave en `parametros.toml`. +PARAMETROS_DE_LA_LISTA = { + "ventana_meses": "cacu.seguimiento.ventana_meses", + "fecha_estudio": "cacu.seguimiento.fecha_estudio", + "estudios": "cacu.seguimiento.estudios", + "resultado_mostrado": "cacu.seguimiento.resultado_mostrado", + "grupos_edad": "cacu.grupos_edad", + "catalogo": "cacu.catalogos.citologia", + "cie_diagnostico": "cacu.diagnostico.cie", + "especialidades_diagnostico": "cacu.diagnostico.especialidades", + "cie_antecedente": "cacu.diagnostico.cie_antecedente", + "horizonte_dias": "cacu.horizontes.toma_diagnostico_dias", +} +ESTRATO = "estatus_seguimiento" + + +class PedidoInvalido(ValueError): + """Un parámetro del pedido fuera de lo que admite el contrato (400).""" + + +class PaginaFuera(LookupError): + """Una página mayor que la última, habiendo pacientes (404).""" + + +def seguimiento_de( + sesion: Session, + *, + sal: str, + corte: date | None = None, + meses: int | None = None, + estatus: str | None = None, + page: int = 1, + page_size: int = 50, + hoy: date | None = None, + tablas: TablasKit = TABLAS, +) -> dict: + """La lista de seguimiento al `corte`, lista para `json.dumps` (contrato §2). + + `corte` por omisión es `hoy`; en los dos casos se acota a la última fecha con datos de la plata. + `meses` por omisión es `cacu.seguimiento.ventana_meses`. + + Raises: + PedidoInvalido: `meses`, `estatus`, `page` o `page_size` fuera de rango. + PaginaFuera: `page` mayor que la última página, habiendo pacientes. + ReglaDesconocida: una regla de `parametros.toml` con una opción que el código no sabe aplicar. + """ + lista = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in PARAMETROS_DE_LA_LISTA.items()} + del_estatus = leer_estrato("cacu", ESTRATO).parametros + valores_estatus = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in del_estatus.items()} + _validar_reglas(lista) + meses = lista["ventana_meses"] if meses is None else meses + if meses not in VENTANAS: + raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.") + if estatus is not None and estatus not in ESTATUS: + raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.") + if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA: + raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.") + + corte = _acotado(sesion, corte or hoy or date.today(), tablas) + desde = _meses_antes(corte, meses) + timedelta(days=1) + estatus_de = _estatus_al_corte(sesion, corte, valores_estatus) + items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas) + if estatus is not None: + items = [i for i in items if i["estatus"]["codigo"] == estatus] + + total = len(items) + paginas = -(-total // page_size) + if total and page > paginas: + raise PaginaFuera(f"page {page} pasa de la última ({paginas}).") + etiquetas = _etiquetas_de_estatus() + return { + "simulado": True, + "corte": corte.isoformat(), + "ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()}, + "filtros": {"estatus": estatus}, + "estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()], + "reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas), + "paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas}, + "items": items[(page - 1) * page_size : page * page_size], + } + + +def seudonimo(pac_id: int, sal: str) -> str: + """El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`.""" + return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper() + + +def _validar_reglas(lista: dict) -> None: + exigir_opcion("cacu.seguimiento.ventana_meses", lista["ventana_meses"], VENTANAS) + exigir_opcion("cacu.seguimiento.fecha_estudio", lista["fecha_estudio"], FECHAS_DE_ESTUDIO) + exigir_opciones("cacu.seguimiento.estudios", lista["estudios"], ESTUDIOS) + exigir_opcion("cacu.seguimiento.resultado_mostrado", lista["resultado_mostrado"], RESULTADOS_MOSTRADOS) + + +def _acotado(sesion: Session, corte: date, tablas: TablasKit) -> date: + """El corte, sin pasar de la última fecha con datos de la plata (si hay datos).""" + ultima = sesion.execute(select(func.max(tablas.Procedimiento.fecha))).scalar() + return corte if ultima is None else min(corte, _fecha(ultima)) + + +def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int, str]: + cte = estatus_al(P("corte_seguimiento"), reglas_de(valores), incluye_referencia=True) + filas = ejecutar(sesion, select(cte.c.pac_id, cte.c.estatus), {**valores, "corte_seguimiento": corte.isoformat()}) + return {pac_id: estatus for pac_id, estatus in filas} + + +def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]: + """Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua.""" + estudios = _estudios(sesion, corte, lista["fecha_estudio"]) + en_ventana: dict[int, dict[str, list]] = {} + for e in estudios: + if desde <= e["fecha"] <= corte: + de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []}) + if "citologia" in lista["estudios"]: + de_la_paciente["citologia"].append(e) + if "vph" in lista["estudios"] and e["vph"] is not None: + de_la_paciente["vph"].append(e) + gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])} + edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas) + notas_de = _notas_por_paciente(sesion, corte) + items = [] + for pac_id, de_la_paciente in en_ventana.items(): + if not de_la_paciente["citologia"] and not de_la_paciente["vph"]: + continue + cito = _mostrada(de_la_paciente["citologia"], lista["resultado_mostrado"], gravedad) + vph = max(de_la_paciente["vph"], key=lambda e: e["fecha"], default=None) + mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]]) + estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE") + items.append({ + "id_seudonimo": seudonimo(pac_id, sal), + "grupo_edad": edades.get(pac_id, SIN_DATO), + "estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]}, + "ultima_citologia": None if cito is None else { + "fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"], + }, + "ultimo_vph": None if vph is None else { + "fecha": vph["fecha"].isoformat(), "resultado": vph["vph"], + "genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]), + }, + "dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista), + "prioridad": None, + "_orden": mas_reciente, + }) + items.sort(key=lambda i: i["id_seudonimo"]) + items.sort(key=lambda i: i.pop("_orden"), reverse=True) + return items + + +def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]: + """Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe).""" + c = citologias() + filas = sesion.execute(select( + c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18, + )).all() + estudios = [] + for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas: + toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte) + conocido = reporte is not None and reporte <= corte + fecha = toma if fecha_estudio == "toma" else reporte + if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido): + continue + estudios.append({ + "pac_id": pac_id, "fecha": fecha, "toma": toma, "calidad": calidad, + "resultado": resultado if conocido else None, + "vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None, + }) + return estudios + + +def _mostrada(citologias_: list[dict], resultado_mostrado: str, gravedad: dict[str, int]) -> dict | None: + if not citologias_: + return None + if resultado_mostrado == "ultimo": + return max(citologias_, key=lambda e: e["fecha"]) + return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"])) + + +def _grupo_de_edad(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, str]: + """El grupo de edad de cada paciente con fecha de nacimiento, con la edad cumplida al corte.""" + grupos = grupos_de_cortes(cortes, tablas=tablas) + edades = {} + for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)): + if nacimiento is None: + continue + nacimiento = _fecha(nacimiento) + edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day)) + edades[pac_id] = next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO) + return edades + + +def _notas_por_paciente(sesion: Session, corte: date) -> dict[int, list[tuple[date, str, str]]]: + n = notas() + de = {} + filas = sesion.execute(select(n.c.pac_id, n.c.fecha, n.c.cie_codigo, n.c.especialidad)) + for pac_id, fecha, cie, especialidad in filas: + if fecha is not None and _fecha(fecha) <= corte: + de.setdefault(pac_id, []).append((_fecha(fecha), cie, especialidad)) + return de + + +def _dias_a_la_valoracion(cito: dict, notas_de: dict, lista: dict) -> int | None: + """Días de la toma a la primera nota que la resuelve, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO; nulo si aún no. + + También nulo si la paciente ya tenía un diagnóstico de cáncer antes de la toma: esa toma no se mide. + """ + toma, propias = cito["toma"], notas_de.get(cito["pac_id"], []) + if any(f < toma and cie in lista["cie_antecedente"] for f, cie, _ in propias): + return None + dias = [ + (f - toma).days for f, cie, especialidad in propias + if f > toma and (f - toma).days < lista["horizonte_dias"] + and cie in lista["cie_diagnostico"] and especialidad in lista["especialidades_diagnostico"] + ] + return min(dias, default=None) + + +def _reglas_usadas(sesion: Session, claves: list[str], tablas: TablasKit) -> list[dict]: + filas = [sesion.get(tablas.DefParametro, clave) for clave in dict.fromkeys(claves)] + return [{"clave": f.clave, "valor": json.loads(f.valor), "estado": f.estado} for f in filas if f is not None] + + +def _etiquetas_de_estatus() -> dict[str, str]: + """Código -> etiqueta, en orden de presentación: los `valores` del estrato en `estratos.toml`.""" + return {v["valor"]: v["etiqueta"] for v in leer_estrato("cacu", ESTRATO).valores} + + +def _meses_antes(fecha: date, meses: int) -> date: + """La misma fecha `meses` meses antes; si ese mes es más corto, su último día.""" + total = fecha.year * 12 + fecha.month - 1 - meses + anio, mes = divmod(total, 12) + return date(anio, mes + 1, min(fecha.day, calendar.monthrange(anio, mes + 1)[1])) + + +def _fecha(valor) -> date: + """Una fecha de la base, venga como `date` o como texto ISO (SQLite).""" + return valor if isinstance(valor, date) else date.fromisoformat(str(valor)[:10]) diff --git a/webapi/follow_up/pivot.py b/webapi/follow_up/pivot.py new file mode 100644 index 0000000..39aa71e --- /dev/null +++ b/webapi/follow_up/pivot.py @@ -0,0 +1,110 @@ +"""Bloques de consulta sobre la plata de dos tablas (F5, ADR-MD-007). + +Una consulta de indicador no escribe a mano los `JOIN` entre `procedimiento` y +`observacion`: pide un **pivote**, una fila por procedimiento de un estudio y una +clase, con una columna por resultado del catálogo. El valor de cada columna sale de +la columna de `observacion` que le toca según `tipo_valor`: + + codigo valor_id, o el texto tal como llegó si no está en el catálogo (valor_fuente) + booleano valor_numerico, como entero (0 o 1) + numero valor_numerico + fecha valor_fecha + texto valor_texto + externo valor_texto + +Las fechas salen sin tipo (`sin_tipo`), como en las vistas por tipo, para que los parámetros +de periodo se liguen igual que antes. Con eso, el vocabulario de cada proyecto (`

/consultas/plata.py`) se rearma como +CTE, sin vistas en la base: las dos tablas ya son el estado actual (sin versiones de +fila). Solo se arman expresiones de SQLAlchemy; no se lee ni se escribe nada. +""" + +from collections.abc import Mapping +from functools import cache + +from sqlalchemy import Integer, Subquery, and_, case, cast, func, select, type_coerce +from sqlalchemy.types import NullType + +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.tables import PROJECTS, TablasKit, tablas_de + +COLUMNAS_DEL_PROCEDIMIENTO = ("procedimiento_id", "padre_id", "pac_id", "fecha", "fuente_tabla", "fuente_id") + + +class TipoDeResultadoAmbiguo(ValueError): + """Un mismo `resultado_id` con dos `tipo_valor` distintos en dos catálogos.""" + + +@cache +def tipos_de_resultado() -> dict[str, str]: + """`resultado_id` -> `tipo_valor`, de los catálogos de los tres proyectos (deben coincidir donde se repiten).""" + tipos: dict[str, str] = {} + for proyecto in PROJECTS: + for resultado in catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas_de(proyecto)).resultados: + previo = tipos.setdefault(resultado.resultado_id, resultado.tipo_valor) + if previo != resultado.tipo_valor: + raise TipoDeResultadoAmbiguo(f"{resultado.resultado_id}: {previo} y {resultado.tipo_valor}.") + return tipos + + +def sin_tipo(columna): + """Una fecha sin tipo de SQLAlchemy, como las columnas de las vistas por tipo (`consultas.vista.vista`). + + Así un parámetro de la definición (`P("periodo_inicio")`) se liga como lo da el cálculo (texto ISO) + y no como `Date`, y las consultas de los indicadores comparan fechas igual que antes (T-18r). + """ + return type_coerce(columna, NullType()).label(columna.key) if hasattr(columna, "key") else type_coerce(columna, NullType()) + + +def valor(observacion, tipo_valor: str): + """La expresión del valor de una observación según su tipo.""" + if tipo_valor == "codigo": + return func.coalesce(observacion.c.valor_id, observacion.c.valor_fuente) + if tipo_valor == "booleano": + return cast(observacion.c.valor_numerico, Integer) + if tipo_valor == "numero": + return observacion.c.valor_numerico + if tipo_valor == "fecha": + return sin_tipo(observacion.c.valor_fecha) + return observacion.c.valor_texto + + +def pivote( + tablas: TablasKit, estudio_id: str, clase: str, resultados: Mapping[str, str | tuple[str, str]] | None = None, *, + nombre: str | None = None, columnas: tuple[str, ...] = (), +) -> Subquery: + """Una fila por procedimiento del estudio y la clase, con una columna por resultado. + + `resultados`: nombre de la columna -> `resultado_id` (`{"resultado": "citologia.bethesda"}`), o + -> `(resultado_id, columna)` para leer una columna de `observacion` en particular + (`("nota_medica.especialidad", "valor_id")`: el código, nulo si no se reconoció). + Las columnas del procedimiento van siempre: `procedimiento_id`, `padre_id`, `pac_id`, + `fecha`, `fuente_tabla` y `fuente_id`, más las de `columnas` (`("orden_numero",)`). Un resultado + sin observación da nulo. + """ + resultados = dict(resultados or {}) + p = tablas.Procedimiento.__table__ + o = tablas.Observacion.__table__.alias(f"o_{estudio_id}_{clase}") + tipos = tipos_de_resultado() + columnas = [sin_tipo(p.c[c]) if c == "fecha" else p.c[c] for c in (*COLUMNAS_DEL_PROCEDIMIENTO, *columnas)] + if not resultados: + consulta = select(*columnas).where(p.c.estudio_id == estudio_id, p.c.clase == clase) + return consulta.subquery(nombre or f"{estudio_id}_{clase}") + pares = {columna: r if isinstance(r, tuple) else (r, None) for columna, r in resultados.items()} + pivoteadas = [ + func.max(case((o.c.resultado_id == resultado_id, + o.c[especifica] if especifica else valor(o, tipos[resultado_id])))).label(columna) + for columna, (resultado_id, especifica) in pares.items() + ] + consulta = ( + select(*columnas, *pivoteadas) + .select_from(p.outerjoin(o, and_(o.c.procedimiento_id == p.c.procedimiento_id, + o.c.resultado_id.in_([r for r, _ in pares.values()])))) + .where(p.c.estudio_id == estudio_id, p.c.clase == clase) + .group_by(*(p.c[c.key] if c.key == "fecha" else c for c in columnas)) + ) + return consulta.subquery(nombre or f"{estudio_id}_{clase}") + + +def hijos_de(padre: Subquery, hijo: Subquery): + """La condición de unión de un procedimiento con sus hijos (el reporte con su toma).""" + return hijo.c.padre_id == padre.c.procedimiento_id diff --git a/webapi/follow_up.py b/webapi/follow_up/routes.py similarity index 92% rename from webapi/follow_up.py rename to webapi/follow_up/routes.py index ba66fec..7e3b2db 100644 --- a/webapi/follow_up.py +++ b/webapi/follow_up/routes.py @@ -4,7 +4,7 @@ Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de `deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no -existe (404). La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida, +existe (404). La lista la arma el kit (`webapi.follow_up.listing`); aquí solo se valida, se abre la sesión y se traducen los errores. """ @@ -15,7 +15,7 @@ from collections.abc import Callable from datetime import date from flask import Blueprint, Response, jsonify, request -from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seguimiento_de +from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de from sqlmodel import Session FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") diff --git a/webapi/follow_up/silver.py b/webapi/follow_up/silver.py new file mode 100644 index 0000000..2a838fb --- /dev/null +++ b/webapi/follow_up/silver.py @@ -0,0 +1,99 @@ +"""El vocabulario de CaCu sobre la plata de dos tablas (F5, ADR-MD-007): citologías, biopsias, notas y órdenes. + +Lo que leen las familias reescritas, armado con `plata.consultas.pivote` como subconsultas +(sin vistas en la base). Los nombres de columna son los del concepto, no los de una tabla +por tipo: `fecha_toma`, `resultado`, `grado`. Cada uno lleva `procedimiento_id` y +`pac_id`; los que cuelgan de una toma llevan también la de su toma. +""" + +from sqlalchemy import Subquery, select + +from webapi.orchestration.tables.cacu import TABLAS +from webapi.follow_up.pivot import hijos_de, pivote +from webapi.orchestration.tables import TablasKit + + +def citologias(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por citología tomada, con su calidad, su resultado (Bethesda) y su VPH si ya los tiene. + + Lo mismo que la vista por tipo `v_citologia_con_resultado`, desde las dos tablas. + """ + toma = pivote(tablas, "citologia", "toma", {"calidad_muestra": "citologia.calidad_muestra"}, + columnas=("orden_numero",), nombre="toma_citologia") + reporte = pivote(tablas, "citologia", "reporte", {"resultado": "citologia.bethesda"}, nombre="reporte_citologia") + vph = pivote(tablas, "vph", "reporte", { + "vph": "vph.resultado", "genotipo_16_18": "vph.genotipo_16_18", + "genotipo_16": "vph.genotipo_16", "genotipo_18": "vph.genotipo_18", + }, nombre="reporte_vph") + return select( + toma.c.procedimiento_id, toma.c.fuente_tabla, toma.c.fuente_id, toma.c.pac_id, + toma.c.fecha.label("fecha_toma"), toma.c.calidad_muestra, toma.c.orden_numero, + reporte.c.fecha.label("fecha_reporte"), reporte.c.resultado, + vph.c.vph, vph.c.genotipo_16_18, vph.c.genotipo_16, vph.c.genotipo_18, + ).select_from( + toma.outerjoin(reporte, hijos_de(toma, reporte)).outerjoin(vph, hijos_de(toma, vph)) + ).subquery("citologias") + + +def biopsias(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por biopsia reportada, con su grado, su solicitud y la citología que la originó (si se encontró). + + Desde T-22h la biopsia es una orden (`biopsia`, `orden`: la solicitud, con su fecha y su número de orden) + y su reporte, una hija de ella: la toma queda dos niveles arriba (toma, orden, reporte). + """ + reporte = pivote(tablas, "biopsia", "reporte", {"grado": "biopsia.grado"}, nombre="reporte_biopsia") + orden = pivote(tablas, "biopsia", "orden", columnas=("orden_numero",), nombre="orden_biopsia") + toma = pivote(tablas, "citologia", "toma", nombre="toma_de_la_biopsia") + return select( + reporte.c.procedimiento_id, reporte.c.fuente_tabla, reporte.c.fuente_id, reporte.c.pac_id, + reporte.c.fecha.label("fecha_reporte"), reporte.c.grado, orden.c.fecha.label("fecha_solicitud"), orden.c.orden_numero, + toma.c.procedimiento_id.label("toma_id"), toma.c.pac_id.label("toma_pac_id"), toma.c.fecha.label("fecha_toma"), + ).select_from( + reporte.outerjoin(orden, hijos_de(orden, reporte)).outerjoin(toma, hijos_de(toma, orden)) + ).subquery("biopsias") + + +def notas(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por nota médica: su fecha, su CIE-10 y la especialidad que la escribió (código; nulo si no se reconoció).""" + nota = pivote(tablas, "nota_medica", "encuentro", { + "cie_codigo": "nota_medica.diagnostico", + "especialidad": ("nota_medica.especialidad", "valor_id"), + "especialidad_fuente": ("nota_medica.especialidad", "valor_fuente"), + }, nombre="nota_medica") + return select( + nota.c.procedimiento_id, nota.c.fuente_tabla, nota.c.fuente_id, nota.c.pac_id, nota.c.fecha, + nota.c.cie_codigo, nota.c.especialidad, nota.c.especialidad_fuente, + ).subquery("notas") + + +def notas_con_textos(tablas: TablasKit = TABLAS) -> Subquery: + """Las notas con su motivo de consulta y su diagnóstico en texto (tal como llegan) y su identificador del hospital. + + Aparte de `notas` para no mover la huella de las definiciones que ya la leen (T-24b, T-24c). + """ + nota = pivote(tablas, "nota_medica", "encuentro", { + "cie_codigo": "nota_medica.diagnostico", + "especialidad": ("nota_medica.especialidad", "valor_id"), + "motivo": "nota_medica.motivo", + "diagnostico_texto": "nota_medica.diagnostico_texto", + }, columnas=("id_hospital",), nombre="nota_con_textos") + return select( + nota.c.procedimiento_id, nota.c.pac_id, nota.c.fecha, nota.c.cie_codigo, nota.c.especialidad, + nota.c.motivo, nota.c.diagnostico_texto, nota.c.id_hospital, + ).subquery("notas_con_textos") + + +def ordenes_de_biopsia(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por biopsia solicitada (la orden, con o sin reporte; T-22h): de quién y la fecha de la solicitud.""" + orden = pivote(tablas, "biopsia", "orden", nombre="orden_de_biopsia") + return select(orden.c.procedimiento_id, orden.c.pac_id, orden.c.fecha).subquery("ordenes_de_biopsia") + + +def tomas_con_especialidad(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por citología tomada, con la especialidad de la orden de la que cuelga (nula si no tiene o no se reconoce).""" + toma = pivote(tablas, "citologia", "toma", nombre="toma_con_especialidad") + orden = pivote(tablas, "citologia", "orden", {"especialidad": ("orden.especialidad", "valor_id")}, + nombre="orden_de_la_toma") + return select(toma.c.procedimiento_id, toma.c.pac_id, toma.c.fecha, orden.c.especialidad).select_from( + toma.outerjoin(orden, hijos_de(orden, toma)) + ).subquery("tomas_con_especialidad") diff --git a/webapi/follow_up/status.py b/webapi/follow_up/status.py new file mode 100644 index 0000000..142e5a7 --- /dev/null +++ b/webapi/follow_up/status.py @@ -0,0 +1,281 @@ +"""El estatus de seguimiento ASCCP de cada paciente a una fecha (T-24c; plan de seguimiento, §5.2). + +`estatus_al(referencia, reglas)` es la única regla: una CTE `(pac_id, estatus)` con un renglón +por persona. La usan el estrato `estatus_seguimiento` (`estrato`, a la referencia de cada +reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las cohortes (a su +fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo +pasado no cambia cuando la paciente avanza. + + POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia + POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si + es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de + valoración (la nota que resuelve una toma, como en CACU_DIAS_TOMA_DIAGNOSTICO); una + orden o una biopsia, por regla, si es del mismo día que una nota de colposcopia (la + colposcopia es la madre de la biopsia) + INFO_INSUFICIENTE la historia no alcanza (`cacu.seguimiento.insuficiente.regla`); también el resto + PRE_COLPOSCOPIA ninguna de las anteriores y, si se conoce la especialidad de sus citologías, + alguna es de vigilancia + +Ninguna regla está escrita aquí: todas son de `parametros.toml` (`cacu.seguimiento.*`, §2bis); qué +parámetro de la consulta es qué clave lo declara `estratos.toml` (`[cacu.estatus_seguimiento.parametros]`), +y llegan como `reglas`. Las listas (CIE-10, especialidades, evidencias) van ligadas como +parámetros (S-K76); los textos del motivo y del diagnóstico se comparan por contención, en +mayúsculas y sin acentos; la precedencia, la referencia y la regla de insuficiente arman la +consulta. Una opción que el código no sabe aplicar falla con `ReglaDesconocida`. +""" + +import unicodedata +from collections.abc import Mapping +from dataclasses import dataclass + +from sqlalchemy import ( + CTE, ColumnElement, and_, bindparam, case, exists, func, literal, literal_column, or_, select, union_all, +) + +from webapi.follow_up.silver import biopsias, notas_con_textos, ordenes_de_biopsia, tomas_con_especialidad +from webapi.orchestration.tables.cacu import TABLAS +from webapi.follow_up.functions import dias_entre +from webapi.follow_up.view import P, vista +from webapi.orchestration.tables import TablasKit + +ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA") +RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3) +MARCOS = ("estatus", "ronda") +REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte +EVIDENCIAS = ("motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia") +FUENTES_DE_TRATAMIENTO = ("nota_posterior_a_colposcopia",) +REGLAS_DE_INSUFICIENTE = ("inicio_datos_posterior_a_alta", "sin_alta_registrada", "ambos", "nunca") +REQUISITOS_DE_COLPOSCOPIA = ("valoracion_previa", "ninguno") +REQUISITOS_DE_BIOPSIA = ("mismo_dia_que_colposcopia", "ninguno") + +V_PERSONA = vista("v_persona", "pac_id") +SIN_ACENTO = {"Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U", "Ü": "U", "á": "a", "é": "e", "í": "i", "ó": "o", + "ú": "u", "ü": "u"} # fmt: skip + + +class ReglaDesconocida(ValueError): + """Una regla de `cacu.seguimiento.*` con una opción que el código no sabe aplicar.""" + + +@dataclass(frozen=True) +class Reglas: + """Las reglas que dan forma a la consulta, ya validadas. Las listas no van aquí: se ligan al ejecutar.""" + + referencia: str # el parámetro del reporte: `periodo_inicio` o `fecha_corte` + precedencia: tuple[str, ...] + motivos: tuple[str, ...] # normalizados + diagnosticos: tuple[str, ...] # normalizados + insuficiente: str + valoracion_previa: bool # una nota de colposcopia cuenta solo después de una cita de valoración + biopsia_mismo_dia: bool # la orden y la biopsia cuentan solo el día de una nota de colposcopia + + +def reglas_de(valores: Mapping) -> Reglas: + """Valida las reglas (`{parámetro de la consulta: valor}`, los de `estratos.toml`) contra las opciones admitidas.""" + exigir_opciones("cacu.seguimiento.marco", valores["seguimiento_marco"], MARCOS) + if "estatus" not in valores["seguimiento_marco"]: + raise ReglaDesconocida("cacu.seguimiento.marco no incluye «estatus»: el estrato no se publica.") + if "ronda" in valores["seguimiento_marco"]: + raise ReglaDesconocida("cacu.seguimiento.marco: «ronda» (UE) todavía no se sabe aplicar.") + exigir_opcion("cacu.seguimiento.referencia", valores["seguimiento_referencia"], tuple(REFERENCIAS)) + precedencia = tuple(valores["seguimiento_precedencia"]) + if sorted(precedencia) != sorted(ESTATUS): + raise ReglaDesconocida( + f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; " + f"llegó {precedencia}." + ) + exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS) + exigir_opciones( + "cacu.seguimiento.tratamiento.fuentes", valores["seguimiento_fuentes_tratamiento"], FUENTES_DE_TRATAMIENTO + ) + exigir_opcion("cacu.seguimiento.insuficiente.regla", valores["seguimiento_insuficiente"], REGLAS_DE_INSUFICIENTE) + exigir_opcion("cacu.seguimiento.colposcopia.requisito", valores["seguimiento_requisito"], REQUISITOS_DE_COLPOSCOPIA) + exigir_opcion( + "cacu.seguimiento.colposcopia.biopsia_requisito", + valores["seguimiento_biopsia_requisito"], + REQUISITOS_DE_BIOPSIA, + ) + return Reglas( + referencia=REFERENCIAS[valores["seguimiento_referencia"]], + precedencia=precedencia, + motivos=tuple(normalizado(m) for m in valores["seguimiento_motivos"]), + diagnosticos=tuple(normalizado(d) for d in valores["seguimiento_diagnosticos"]), + insuficiente=valores["seguimiento_insuficiente"], + valoracion_previa=valores["seguimiento_requisito"] == "valoracion_previa", + biopsia_mismo_dia=valores["seguimiento_biopsia_requisito"] == "mismo_dia_que_colposcopia", + ) + + +def estrato(valores: Mapping) -> CTE: + """El estrato `estatus_seguimiento` (`estratos.toml`): `(unidad_id, estrato)`, a la referencia del reporte.""" + reglas = reglas_de(valores) + estatus = estatus_al(P(reglas.referencia), reglas, incluye_referencia=reglas.referencia == "fecha_corte") + return select(estatus.c.pac_id.label("unidad_id"), estatus.c.estatus.label("estrato")).cte( + "estrato_estatus_seguimiento" + ) + + +def estatus_al( + referencia: ColumnElement, reglas: Reglas, *, incluye_referencia: bool = False, tablas: TablasKit = TABLAS +) -> CTE: + """La CTE `(pac_id, estatus)`: un renglón por persona, con lo ocurrido antes de `referencia`. + + `referencia` es una fecha de SQL (un parámetro: `P("periodo_inicio")`, `P("corte")`). Con + `incluye_referencia`, cuenta también lo de ese día (un corte); sin él, solo lo anterior (el inicio + de un periodo). Los parámetros `seguimiento_*` de las listas se ligan al ejecutar. + """ + + def antes(fecha) -> ColumnElement: + return fecha <= referencia if incluye_referencia else fecha < referencia + + nota, orden, reporte, toma = ( + notas_con_textos(tablas), ordenes_de_biopsia(tablas), biopsias(tablas), tomas_con_especialidad(tablas) + ) + # La cita de valoración: la nota que resuelve una toma, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO. + valoracion = ( + select(nota.c.pac_id, func.min(nota.c.fecha).label("primera")) + .select_from(nota.join(toma, toma.c.pac_id == nota.c.pac_id)) + .where( + antes(nota.c.fecha), + nota.c.fecha > toma.c.fecha, + dias_entre(toma.c.fecha, nota.c.fecha) < P("seguimiento_horizonte_valoracion"), + nota.c.cie_codigo.in_(P("seguimiento_cie_valoracion", lista=True)), + nota.c.especialidad.in_(P("seguimiento_especialidades_valoracion", lista=True)), + ) + .group_by(nota.c.pac_id) + .cte("seguimiento_valoracion") + ) + # Una nota de colposcopia: de su especialidad y, por regla, posterior a la primera valoración. + de_colposcopia = and_( + antes(nota.c.fecha), + nota.c.especialidad.in_(P("seguimiento_especialidades_colposcopia", lista=True)), + nota.c.fecha > valoracion.c.primera if reglas.valoracion_previa else _siempre(), + ) + con_valoracion = nota.outerjoin(valoracion, valoracion.c.pac_id == nota.c.pac_id) + # Los días con una nota de colposcopia válida: la orden de biopsia se expide ese día (su madre). + visitas = select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(de_colposcopia).cte( + "seguimiento_visitas_de_colposcopia" + ) + + def de_una_visita(pac_id, fecha) -> ColumnElement: + if not reglas.biopsia_mismo_dia: + return _siempre() + return exists().where(visitas.c.pac_id == pac_id, visitas.c.fecha == fecha) + + evidencias = union_all( + select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where( + _habilitada("motivo"), de_colposcopia, _contiene(nota.c.motivo, reglas.motivos, "motivo") + ), + select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where( + _habilitada("cie"), de_colposcopia, nota.c.cie_codigo.in_(P("seguimiento_cie_colposcopia", lista=True)), + ), + select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where( + _habilitada("diagnostico_texto"), de_colposcopia, + _contiene(nota.c.diagnostico_texto, reglas.diagnosticos, "diagnostico"), + ), + select(orden.c.pac_id, orden.c.fecha).where( + _habilitada("orden_biopsia"), antes(orden.c.fecha), de_una_visita(orden.c.pac_id, orden.c.fecha) + ), + select(reporte.c.pac_id, reporte.c.fecha_reporte.label("fecha")).where( + _habilitada("biopsia"), antes(reporte.c.fecha_reporte), + de_una_visita(reporte.c.pac_id, reporte.c.fecha_solicitud), + ), + ).subquery("evidencias_de_colposcopia") + colposcopia = ( + select(evidencias.c.pac_id, func.min(evidencias.c.fecha).label("primera")) + .group_by(evidencias.c.pac_id) + .cte("seguimiento_colposcopia") + ) + tratamiento = ( + select(nota.c.pac_id) + .distinct() + .select_from(nota.join(colposcopia, colposcopia.c.pac_id == nota.c.pac_id)) + .where( + antes(nota.c.fecha), + nota.c.fecha > colposcopia.c.primera, + nota.c.cie_codigo.in_(P("seguimiento_cie_tratamiento", lista=True)), + ) + .cte("seguimiento_tratamiento") + ) + # Fuera de vigilancia: todas sus citologías tienen especialidad conocida y ninguna es de vigilancia. + de_vigilancia = or_( + toma.c.especialidad.is_(None), toma.c.especialidad.in_(P("seguimiento_especialidades_vigilancia", lista=True)) + ) + fuera_de_vigilancia = ( + select(toma.c.pac_id) + .where(antes(toma.c.fecha)) + .group_by(toma.c.pac_id) + .having(func.sum(case((de_vigilancia, 1), else_=0)) == 0) + .cte("seguimiento_fuera_de_vigilancia") + ) + persona = V_PERSONA + cumple = { + "POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None), + "POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None), + "INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente), + "PRE_COLPOSCOPIA": fuera_de_vigilancia.c.pac_id.is_(None), + } + estatus = case(*((cumple[e], literal(e)) for e in reglas.precedencia), else_=literal(RESTO)) + return ( + select(persona.c.pac_id, estatus.label("estatus")) + .select_from( + persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id) + .outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id) + .outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id) + ) + .cte("seguimiento_estatus") + ) + + +def normalizado(texto: str) -> str: + """Un texto para comparar: sin espacios al borde, sin acentos y en mayúsculas (la Ñ se queda).""" + return "".join(SIN_ACENTO.get(c, c) for c in unicodedata.normalize("NFC", texto.strip())).upper() + + +def _normalizado_sql(columna: ColumnElement) -> ColumnElement: + """`normalizado` en SQL: sin acentos (antes de `upper`, que en SQLite solo sabe ASCII) y en mayúsculas.""" + for con, sin in SIN_ACENTO.items(): + columna = func.replace(columna, con, sin) + return func.upper(columna) + + +def _contiene(columna: ColumnElement, textos: tuple[str, ...], nombre: str) -> ColumnElement: + """La columna, normalizada, contiene alguno de los textos (ya normalizados). Sin textos, nunca.""" + if not textos: + return _nunca() + normal = _normalizado_sql(columna) + return or_(*(normal.contains(bindparam(f"seguimiento_{nombre}_{i}", t)) for i, t in enumerate(textos))) + + +def _habilitada(evidencia: str) -> ColumnElement: + """La evidencia está en `cacu.seguimiento.colposcopia.evidencias` (ligada al ejecutar).""" + return literal(evidencia).in_(P("seguimiento_evidencias", lista=True)) + + +def _insuficiente(regla: str) -> ColumnElement: + """La regla de historia insuficiente. Hoy no hay fecha de alta (usuario, 2026-10-22): se asume posterior al + inicio de los datos, así que `inicio_datos_posterior_a_alta` no marca a nadie y `sin_alta_registrada`, a todas.""" + return _siempre() if regla in ("sin_alta_registrada", "ambos") else _nunca() + + +def _siempre() -> ColumnElement: + """Una condición verdadera. No `true()`: SQL Server la escribe como `1`, que no es condición.""" + return literal_column("1") == literal_column("1") + + +def _nunca() -> ColumnElement: + """Una condición falsa (ver `_siempre`).""" + return literal_column("1") == literal_column("0") + + +def exigir_opcion(clave: str, valor, admitidas: tuple) -> None: + """La regla `clave` vale una de las opciones que el código sabe aplicar; si no, `ReglaDesconocida`.""" + if valor not in admitidas: + raise ReglaDesconocida(f"{clave} = {valor!r}: el código sabe aplicar {list(admitidas)}.") + + +def exigir_opciones(clave: str, valores, admitidas: tuple) -> None: + """Cada valor de la regla `clave` es una opción que el código sabe aplicar; si no, `ReglaDesconocida`.""" + desconocidas = [v for v in valores if v not in admitidas] + if desconocidas: + raise ReglaDesconocida(f"{clave}: {desconocidas} no se saben aplicar; el código sabe {list(admitidas)}.") diff --git a/webapi/follow_up/view.py b/webapi/follow_up/view.py new file mode 100644 index 0000000..2a764d2 --- /dev/null +++ b/webapi/follow_up/view.py @@ -0,0 +1,26 @@ +"""De dónde lee una definición: una vista o una tabla por su nombre, y sus parámetros. + +Una definición de indicador lee la plata genérica por su vocabulario +(`/consultas/plata.py`) y las tablas de apoyo (`dim_fecha`, +`dim_grupo_edad`, `v_persona`) por `vista`. Desde F6 (ADR-MD-009) no hay +tablas de hechos por tipo ni sus vistas `v__actual`. + +Las consultas son objetos de SQLAlchemy: el SQL lo escribe SQLAlchemy +para el motor de la sesión. +""" + +from sqlalchemy import BindParameter, FromClause, bindparam, column, table + + +def vista(nombre: str, *columnas: str) -> FromClause: + """Una vista o una tabla por su nombre y sus columnas, para las que no salen de un modelo.""" + return table(nombre, *(column(nombre_columna) for nombre_columna in columnas)) + + +def P(nombre: str, *, lista: bool = False) -> BindParameter: + """Un parámetro de una definición. `lista`: su valor es una lista y va en un `IN`. + + El valor no entra al SQL: se liga al ejecutar, así que la definición + no cambia cuando cambia una regla del TOML (S-K76). + """ + return bindparam(nombre, expanding=lista) diff --git a/webapi/orchestration/cycle.py b/webapi/orchestration/cycle.py index 2fe7003..a54c9f1 100644 --- a/webapi/orchestration/cycle.py +++ b/webapi/orchestration/cycle.py @@ -17,30 +17,30 @@ from importlib import import_module from pathlib import Path from hamilton.function_modifiers import config -from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata -from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado -from indicadores_kit.oro.cohortes.definicion import leer_definicion -from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging -from indicadores_kit.plata.periodo_observacion import periodos_de_observacion -from indicadores_kit.plata.vistas import ddl_de_vistas as ddl_de_v_persona -from indicadores_kit.registry.apoyo import ( +from webapi.orchestration.silver.quality import verificar_plata as calidad_de_la_plata +from webapi.orchestration.silver.loads import carga_desde_staging, tablas_de_staging +from webapi.orchestration.silver.observation_periods import periodos_de_observacion +from webapi.orchestration.silver.views import ddl_de_vistas as ddl_de_v_persona +from webapi.orchestration.reference.support import ( CLAVE_DIM_FECHA_DESDE, filas_de_dim_fecha, grupos_de_edad_de, ) -from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.registry.parametros import ( +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.reference.rules import ( RUTA_PARAMETROS, leer_parametros, valores_del_archivo, ) -from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.tablas import tablas_de +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 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 log = logging.getLogger(__name__) @@ -173,17 +173,17 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]: Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read. """ tablas = tablas_de(ctx.project) - tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES + 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 armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, + return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, linea=ctx.repos.silver.timeline.query) armados = {} for ruta in cohort_definitions(ctx.project): - definicion = leer_definicion(ruta) + definicion = read_definition(ruta) armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion)) return armados @@ -192,26 +192,26 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]: def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]: """El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008). - Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador + Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador (`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden `confirm-risks`, no este paso. """ - tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES + tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES lotes = {} for ruta in cohort_definitions(ctx.project): - definicion = leer_definicion(ruta) + definicion = read_definition(ruta) estimador = ctx.estimators.get(definicion.url) if estimador is None: continue - def marco(sesion, definicion=definicion): - armado_id = ultimo_armado(sesion, definicion.url, cohortes=tablas_cohorte) - return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion, + 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) - armado_id, ancho = ctx.repos.gold.cohorts.read(marco) + armado_id, ancho = ctx.repos.gold.cohorts.read(frame) if armado_id is None: continue riesgos = [tuple(r) for r in estimador.estimar(*ancho)] diff --git a/webapi/orchestration/project.py b/webapi/orchestration/project.py index 8daf180..07c9e67 100644 --- a/webapi/orchestration/project.py +++ b/webapi/orchestration/project.py @@ -1,9 +1,9 @@ -"""Lo que el ciclo necesita saber de las definiciones de un proyecto: sus periodos (dbt) y sus cohortes (el kit).""" +"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`).""" import json from pathlib import Path -from indicadores_kit.oro.cohortes.definicion import RAIZ +from models.cohorts.definition import ROOT def period_types(proyecto: str, manifest: Path) -> list[str]: @@ -14,5 +14,6 @@ def period_types(proyecto: str, manifest: Path) -> list[str]: def cohort_definitions(proyecto: str) -> list[Path]: - """Los TOML de cohortes que el ciclo arma (`/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h).""" - return sorted((RAIZ / proyecto / "cohortes").glob("*.toml")) + """The cohort TOMLs the cycle builds (`models/cohorts//*.toml`): today only CaCu's surveillance cohort. + Those in `/proposals/` aren't built.""" + return sorted((ROOT / proyecto).glob("*.toml")) diff --git a/webapi/orchestration/reference/__init__.py b/webapi/orchestration/reference/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/webapi/orchestration/reference/age_groups.py b/webapi/orchestration/reference/age_groups.py new file mode 100644 index 0000000..d5ba5b4 --- /dev/null +++ b/webapi/orchestration/reference/age_groups.py @@ -0,0 +1,61 @@ +"""`dim_grupo_edad`: los grupos de edad como datos, para etiquetar sin funciones del motor. + +Una fila por grupo, con sus dos límites incluidos. El SQL calcula la edad +cumplida con las partes de la fecha de `dim_fecha` y cruza con esta +tabla. Los cortes de cada proyecto son la regla `.grupos_edad` +del TOML de parámetros (una lista de pares mínimo y máximo): cambiar los +grupos es editar el TOML, no un SQL. +""" + +from core.indicadores.registro import DimGrupoEdadBase +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + + +EDAD_MAXIMA = 150 # tope del grupo abierto de arriba; una edad mayor es un error de captura + + +def grupos_de_cortes(cortes: list[list[int]], *, tablas: TablasKit) -> list[DimGrupoEdadBase]: + """De los pares `[edad_min, edad_max]` del TOML a los grupos, más dos abiertos. + + [[25, 34], [35, 44]] -> "<25", "25-34", "35-44", "45+". Los grupos + abiertos (S-M3, usuario, 2026-10-08) hacen que toda edad conocida + caiga en un grupo: `sin_dato` queda solo para quien no tiene fecha de + nacimiento (o una edad imposible). Por lo mismo, los cortes no pueden + encimarse ni dejar huecos. + """ + grupos = [] + for corte in cortes: + if len(corte) != 2 or not all(type(edad) is int for edad in corte): + raise ValueError(f"Un corte de edad son dos enteros, mínimo y máximo; llegó {corte!r}.") + minimo, maximo = corte + grupos.append( + tablas.DimGrupoEdad(etiqueta=f"{minimo}-{maximo}", edad_min=minimo, edad_max=maximo) + ) + _exigir_contiguos(grupos) + menor = min(grupo.edad_min for grupo in grupos) + mayor = max(grupo.edad_max for grupo in grupos) + if menor > 0: + grupos.insert(0, tablas.DimGrupoEdad(etiqueta=f"<{menor}", edad_min=0, edad_max=menor - 1)) + if mayor < EDAD_MAXIMA: + grupos.append( + tablas.DimGrupoEdad(etiqueta=f"{mayor + 1}+", edad_min=mayor + 1, edad_max=EDAD_MAXIMA) + ) + return grupos + + +def _exigir_contiguos(grupos: list[DimGrupoEdadBase]) -> None: + if not grupos: + raise ValueError("Hace falta al menos un corte de edad.") + anterior = None + for grupo in sorted(grupos, key=lambda g: g.edad_min): + if grupo.edad_min > grupo.edad_max: + raise ValueError(f"El grupo {grupo.etiqueta!r} tiene los límites al revés.") + if anterior is not None and grupo.edad_min <= anterior.edad_max: + raise ValueError(f"Los grupos {anterior.etiqueta!r} y {grupo.etiqueta!r} se enciman.") + if anterior is not None and grupo.edad_min > anterior.edad_max + 1: + raise ValueError( + f"Entre {anterior.etiqueta!r} y {grupo.etiqueta!r} hay edades sin grupo." + ) + anterior = grupo diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py new file mode 100644 index 0000000..afb0798 --- /dev/null +++ b/webapi/orchestration/reference/catalogs.py @@ -0,0 +1,136 @@ +"""Catálogos de la plata (F1): `core/catalogos/.toml` leído y validado. + +Un catálogo es estudio -> resultado -> valor (`core/catalogos/LEEME.md`). +Aquí solo se lee el archivo y se devuelven las filas de `cat_estudio`, +`cat_resultado` y `cat_valor` del proyecto; las escribe Persistance por la +arista `catalogos` de webapi.orchestration (T-17c). + +`codigos_hospital` de cada estudio no va a ninguna tabla: es cómo nombra el +hospital al estudio (tipo de estudio de la orden, instrumento), y lo usa la +carga de F5. +""" + +import tomllib +from pathlib import Path +from typing import NamedTuple + +import core +from core.indicadores.catalogos import TIPOS_DE_VALOR +from sqlmodel import SQLModel + +from webapi.orchestration.tables import TablasKit + +# Los catálogos viven en Core, junto a los modelos de sus tablas. +RAIZ_CATALOGOS = Path(core.__file__).parent / "catalogos" + + +class CatalogoInvalido(ValueError): + """El archivo de catálogo no cumple sus reglas.""" + + +class Catalogo(NamedTuple): + """Las filas de las tres tablas de catálogo de un proyecto, en el orden del archivo.""" + + estudios: list[SQLModel] + resultados: list[SQLModel] + valores: list[SQLModel] + + +def ruta_de_catalogo(proyecto: str) -> Path: + """El archivo de catálogo del proyecto: `core/catalogos/.toml`.""" + return RAIZ_CATALOGOS / f"{proyecto}.toml" + + +def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo: + """Lee el archivo, lo valida y devuelve las filas con las clases de `tablas`. + + `resultado_id` es `"."`; el `orden` de un valor es su + posición en la lista, desde 1, y todos llegan `vigente` (retirar uno es + cosa de quien sincroniza la tabla). + """ + estudios, resultados, valores = [], [], [] + for estudio_id, estudio in _leer(ruta).items(): + estudios.append(tablas.CatEstudio(estudio_id=estudio_id, etiqueta=_etiqueta(estudio, estudio_id))) + for nombre, resultado in estudio.get("resultados", {}).items(): + resultado_id = f"{estudio_id}.{nombre}" + tipo_valor = _tipo_de_valor(resultado, resultado_id) + resultados.append( + tablas.CatResultado( + resultado_id=resultado_id, + estudio_id=estudio_id, + etiqueta=_etiqueta(resultado, resultado_id), + tipo_valor=tipo_valor, + unidad=resultado.get("unidad"), + sistema=resultado.get("sistema"), + ) + ) + valores += [ + tablas.CatValor( + resultado_id=resultado_id, + valor_id=valor_id, + etiqueta=etiqueta, + orden=orden, + estado="vigente", + ) + for orden, (valor_id, etiqueta) in enumerate(_valores(resultado, resultado_id, tipo_valor), start=1) + ] + return Catalogo(estudios, resultados, valores) + + +def codigos_hospital(proyecto: str) -> dict[str, str]: + """Código del hospital -> `estudio_id`, del catálogo del proyecto. + + Un código que aparece en dos estudios es un error: no se sabría a cuál va. + """ + codigos: dict[str, str] = {} + for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items(): + for codigo in estudio.get("codigos_hospital", []): + if codigo in codigos: + raise CatalogoInvalido( + f"El código del hospital {codigo!r} está en dos estudios: {codigos[codigo]!r} y {estudio_id!r}." + ) + codigos[codigo] = estudio_id + return codigos + + +def _leer(ruta: Path) -> dict: + return tomllib.loads(Path(ruta).read_text(encoding="utf-8")) + + +def _etiqueta(seccion: dict, nombre: str) -> str: + if "etiqueta" not in seccion: + raise CatalogoInvalido(f"{nombre}: falta la etiqueta.") + return seccion["etiqueta"] + + +def _tipo_de_valor(resultado: dict, resultado_id: str) -> str: + """El `tipo_valor` del resultado, y las llaves que ese tipo admite.""" + tipo_valor = resultado.get("tipo_valor") + if tipo_valor not in TIPOS_DE_VALOR: + raise CatalogoInvalido( + f"{resultado_id}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}." + ) + if tipo_valor == "codigo" and not resultado.get("valores"): + raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.") + if tipo_valor != "codigo" and "valores" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.") + if tipo_valor != "externo" and "sistema" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.") + if tipo_valor != "numero" and "unidad" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.") + return tipo_valor + + +def _valores(resultado: dict, resultado_id: str, tipo_valor: str) -> list[tuple[str, str]]: + """(valor, etiqueta) de cada valor del resultado, en el orden del archivo; sin repetidos.""" + if tipo_valor != "codigo": + return [] + vistos: set[str] = set() + valores = [] + for entrada in resultado["valores"]: + valor = entrada["valor"] + if valor in vistos: + raise CatalogoInvalido(f"{resultado_id}: el valor {valor!r} está repetido.") + vistos.add(valor) + valores.append((valor, _etiqueta(entrada, f"{resultado_id}: {valor!r}"))) + return valores diff --git a/webapi/orchestration/reference/dates.py b/webapi/orchestration/reference/dates.py new file mode 100644 index 0000000..e4c3408 --- /dev/null +++ b/webapi/orchestration/reference/dates.py @@ -0,0 +1,35 @@ +"""`dim_fecha`: una fila por día, para hacer aritmética de fechas sin funciones del motor. + +Sumar días o medir un intervalo es una resta de `dia_num` con un cruce. +`dia_habil_num` cuenta solo de lunes a viernes; los días festivos no +están (haría falta un calendario, S-K27). `anio`, `mes` y `dia` son las +partes de la fecha: sirven para la edad cumplida, que no es una resta de +días. Se reemplaza entera por `RegistroRepository.reemplazar`. +""" + +from datetime import date, timedelta + +from core.indicadores.registro import DimFechaBase + +from webapi.orchestration.tables import TablasKit + + +def dias(desde: date, hasta: date, *, tablas: TablasKit) -> list[DimFechaBase]: + """Los días de `desde` a `hasta`, los dos incluidos.""" + if hasta < desde: + raise ValueError(f"El rango de dim_fecha va al revés: {desde} a {hasta}.") + filas, habiles = [], 0 + for numero in range((hasta - desde).days + 1): + dia = desde + timedelta(days=numero) + habiles += dia.weekday() < 5 + filas.append( + tablas.DimFecha( + fecha=dia, + dia_num=numero, + dia_habil_num=habiles, + anio=dia.year, + mes=dia.month, + dia=dia.day, + ) + ) + return filas diff --git a/webapi/orchestration/reference/parametros.toml b/webapi/orchestration/reference/parametros.toml new file mode 100644 index 0000000..776275d --- /dev/null +++ b/webapi/orchestration/reference/parametros.toml @@ -0,0 +1,701 @@ +# Parámetros de indicadores_kit, para todos los proyectos. +# +# Cada parámetro lleva: +# valor lo que usa el cálculo +# estado "sin_definir" nadie lo ha decidido; el valor solo permite correr +# "provisional" hay una propuesta documentada, falta confirmarla +# "confirmado" decisión cerrada +# fuente dónde está documentada la decisión o la pendiente +# +# Se carga en la tabla def_parametro de cada base con +# registry.parametros.cargar_parametros. La clave es "seccion.nombre". + +[comun.dim_fecha.desde] +# El primer día de `dim_fecha`, la tabla de fechas que cruzan las consultas portables (la edad del estrato +# `grupo_edad`). Fijo, porque `dia_num` y `dia_habil_num` se cuentan desde él; el último día es el fin del +# último año del ciclo. Tiene que ser anterior al nacimiento más antiguo: si no, la guarda de cobertura +# (`calidad/cobertura.exigir_cobertura`) detiene el cálculo y lo dice (T-24f, I-MD27). +valor = "1920-01-01" +estado = "provisional" +fuente = "Usuario, 2026-10-22: dim_fecha y dim_grupo_edad se llenan de los TOML (T-24f, I-MD27); 1920 cubre edades hasta los 106 años" + +[comun.umbral_supresion] +# Se suprime un resultado cuyo denominador es menor que este valor. +valor = 5 +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta confirmarla (usuario, 2026-10-12). Los catálogos dicen < 5 y dejan la pregunta abierta (conventions.suppression.min_cell)" + +# Bandas del resumen de riesgos (`mart/riesgos.py`, T-21d). Provisionales: la compuerta +# pide que todo indicador calcule sin `sin_definir`; son candidatos documentados, falta que clínica decida (MD-Q5). +[comun.riesgos.corte_intermedio] +# Probabilidad desde la que la banda es INTERMEDIO (de 0 a 1). +valor = 0.04 +estado = "provisional" +fuente = "Candidato del prototipo: umbral de acción de ASCCP 2019 para colposcopia (4 %, riesgo inmediato de CIN3+). Decide clínica (MD-Q5)" + +[comun.riesgos.corte_alto] +# Probabilidad desde la que la banda es ALTO (de 0 a 1). +valor = 0.25 +estado = "provisional" +fuente = "Candidato del prototipo: umbral de ASCCP 2019 para tratamiento (25 %). En TEA no hay candidato propio. Decide clínica (MD-Q5)" + +[cacu.riesgos.horizonte_banda] +# Años desde la fecha índice de la evaluación que se clasifica; 0 = riesgo prevalente (inmediato). +valor = 0 +estado = "provisional" +fuente = "Prototipo: horizonte 0, el que miden los umbrales de ASCCP. Decide clínica con modelos (MD-Q5)" + +[cama.riesgos.horizonte_banda] +# Años desde el BI-RADS índice: el horizonte del desenlace de la cohorte de tamizaje (365 días, T-21g). +valor = 1 +estado = "provisional" +fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)" + +[tea.riesgos.horizonte_banda] +# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses). +valor = 4 +estado = "provisional" +fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)" + +[comun.catalogos.banda_riesgo] +# Las bandas del resumen de riesgos, de menor a mayor. +valor = [ + { clave = "BAJO", etiqueta = "Riesgo bajo", color = "#9DBFE3" }, + { clave = "INTERMEDIO", etiqueta = "Riesgo intermedio", color = "#E8C28E" }, + { clave = "ALTO", etiqueta = "Riesgo alto", color = "#D98E4A" }, +] +estado = "provisional" +fuente = "Propuesta T-21d: tres bandas fijas con dos cortes (comun.riesgos.*); los nombres siguen a MD-Q5" + +[cacu.calidad_insatisfactoria] +valor = "INSATISFACTORIO" +estado = "provisional" +fuente = "kpi_catalog_cacu_eu.yaml CACU_EU8; Core admite también \"0\" (CITO_CALIDAD_ESPECIMEN_ALIAS); valores reales sin confirmar" + +[cama.calidad_satisfactoria] +valor = "SATISFACTORIO" +estado = "provisional" +fuente = "kpi_catalog_cama_eu.yaml CAMA_EU8; mast_calidad_imagen es texto libre, valores reales sin confirmar" + +[cacu.grupos_edad] +# Grupos de edad del estrato `grupo_edad`: pares [mínimo, máximo] en años cumplidos, incluidos, +# contiguos. Se agrega un grupo abierto en cada extremo ("<25", "65+"). +valor = [[25, 34], [35, 44], [45, 54], [55, 64]] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar" + +[cama.grupos_edad] +valor = [[40, 49], [50, 59], [60, 69]] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar" + +# =========================================================================== +# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8) +# +# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la +# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses". +# Las listas y tablas se guardan en def_parametro como JSON. +# El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga. +# Documentos citados (repositorio analisis-tea, carpeta docs/): +# lista = lista_indicadores_TEA_v2.md · contexto = contexto_reporte_pipeline_TEA.md +# estandares = estandares_indicadores_TEA.md · modif = modificaciones.md +# =========================================================================== + +[tea.cohorte.edad_min_meses] +valor = 16 +estado = "confirmado" +fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)" + +[tea.cohorte.edad_max_meses] +valor = 36 +estado = "confirmado" +fuente = "contexto §1 (director)" + +[tea.cohorte.dias_por_mes] +# Mes medio para pasar días a meses (edad con un decimal). +valor = 30.4375 +estado = "confirmado" +fuente = "analisis-tea/tea/comun.py, edad_meses" + +[tea.cohorte.plazo_ados2_eeg_dias] +# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo. +valor = 30 +estado = "confirmado" +fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)" + +[tea.cohorte.ventanas] +# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos. +valor = [ + { clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" }, + { clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" }, + { clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" }, +] +estado = "confirmado" +fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)" + +[tea.instrumentos.informantes_ramos] +# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre. +valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"] +estado = "confirmado" +fuente = "contexto §1 (equipo); psicología no registra al cuidador principal" + +[tea.instrumentos.informantes_otros] +valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"] +estado = "confirmado" +fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21" + +[tea.ramos.areas] +# «TOTAL» no cuenta como área. +valor = [ + { clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" }, + { clave = "LINGUISTICO", etiqueta = "Lingüístico" }, + { clave = "FISICO", etiqueta = "Físico" }, + { clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" }, + { clave = "ADAPTATIVO", etiqueta = "Adaptativo" }, +] +estado = "confirmado" +fuente = "spec v2, catálogo de ins_area; contexto §1" + +[tea.poblacion.css_min_tea] +# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor. +valor = 3 +estado = "confirmado" +fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo" + +[tea.diagnostico.cie_tea] +# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840). +valor = ["F840"] +estado = "confirmado" +fuente = "usuario (2026-10-15): solo F84.0 (autismo)" + +[tea.diagnostico.instrumentos_mchat] +# M25: valores de psi_instrumento_tamizaje que son un M-CHAT. +valor = ["M_CHAT_R", "M_CHAT_RF"] +estado = "confirmado" +fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)" + +[tea.atencion.plazo_referencia_evaluacion_dias] +# K1: inicio de la evaluación a más tardar este número de días después de la referencia. +valor = 90 +estado = "confirmado" +fuente = "estandares: NICE QS51, enunciado 1 (3 meses)" + +[tea.parto.apgar_corte] +# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10). +valor = 7 +estado = "confirmado" +fuente = "lista, M17: menor de 7, 7, y 8 a 10" + +# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar: +# un cambio pide volver a cargar. +[tea.antecedentes_maternos.no_registrado] +valor = "NO_REGISTRADO" +estado = "confirmado" +fuente = "spec v2: NO_REGISTRADO = sin dato" + +[tea.antecedentes_maternos.hipertension_ninguno] +valor = "NINGUNO" +estado = "confirmado" +fuente = "spec v2, catálogo de amg_hipertension_preeclampsia" + +[tea.antecedentes_maternos.embarazo_no_unico] +valor = ["GEMELAR", "TRIPLE_O_MAS"] +estado = "confirmado" +fuente = "spec v2, catálogo de amg_embarazo_multiple" + +[tea.antecedentes_maternos.liquido_anormal] +valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"] +estado = "confirmado" +fuente = "spec v2, catálogo de amg_liquido_amniotico" + +[tea.supresion.activa] +# Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se +# suprime nada, aunque comun.umbral_supresion tenga valor. +valor = false +estado = "provisional" +fuente = "modif: supresión opcional, apagada por omisión (tablero interno); CaCu tiene la suya sin decidir (bloqueos.md D1)" + +[tea.presentacion.fuente] +valor = "Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL" +estado = "confirmado" +fuente = "lista: toda figura lleva la fuente" + +[tea.presentacion.leyenda] +valor = "Uso exclusivo de investigación. No usar para decisiones clínicas." +estado = "confirmado" +fuente = "marco_regulatorio_TEA.md §3" + +# Catálogos de las composiciones (C2): clave (como en la base), etiqueta y color. +# Colores: paleta de ejemplo del estándar común, hasta que se fije la hoja de estilo. +[tea.catalogos.sin_dato] +valor = { etiqueta = "Sin dato", color = "#C9CDD2" } +estado = "confirmado" +fuente = "lista: «sin dato» siempre se muestra como categoría propia" + +[tea.catalogos.sexo] +valor = [ + { clave = "F", etiqueta = "Femenino", color = "#E0A030" }, + { clave = "M", etiqueta = "Masculino", color = "#2F6DB3" }, + { clave = "I", etiqueta = "Indeterminado", color = "#8A9199" }, +] +estado = "provisional" +fuente = "spec v2, pac_sexo; colores provisionales" + +[tea.catalogos.resultado_mchat] +valor = [ + { clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" }, + { clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" }, + { clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" }, +] +estado = "provisional" +fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales" + +[tea.catalogos.interpretacion_ramos] +valor = [ + { clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" }, + { clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" }, + { clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" }, +] +estado = "provisional" +fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales" + +[tea.catalogos.grado_hipoacusia] +valor = [ + { clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" }, + { clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" }, + { clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" }, + { clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" }, + { clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" }, + { clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" }, +] +estado = "provisional" +fuente = "spec v2, pea_grado_hipoacusia; colores provisionales" + +[tea.catalogos.apgar_5min] +valor = [ + { clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" }, + { clave = "SIETE", etiqueta = "7", color = "#E8C28E" }, + { clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" }, +] +estado = "provisional" +fuente = "lista, M17; colores provisionales" + +# =========================================================================== +# CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml) +# =========================================================================== + +[cacu.citologia_anomala] +# Resultados de citología (células escamosas) que cuentan como anómalos en IND1. +valor = ["ASC-US", "ASC-H", "LIEBG", "LIEAG", "CIS"] +estado = "provisional" +fuente = "Usuario, 2026-10-24: ASC-US cuenta como anómalo. Antes (2026-10-12) quedaba fuera, como en kpi_catalog.yaml IND1 ('abnormal set is LSIL+, ASC-H, HSIL'); falta que clínica lo confirme y decidir glandulares y carcinoma (I-K61)" + +[cacu.biopsia_cis] +valor = ["CIS"] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). IND2b (I-K16): arranque con el grado CIS de Core (GradoCIN); falta que clínica lo confirme y ver que llega poblado en bx_cin_grado" + +[cacu.deteccion_grados] +# Grados de biopsia que cuentan como lesión detectada en CACU_EU13: el umbral CIN2+. +valor = ["LIEAG", "CIS", "CARCINOMA"] +estado = "provisional" +fuente = "Propuesta del catálogo (kpi_catalog_cacu_eu.yaml CACU_EU13: CIN2+), falta que clínica la confirme. CIN3+ no se puede: `bx_cin_grado` guarda CIN2 y CIN3 juntos como LIEAG (I-K15)" + +[cacu.citologia_alto_grado] +# Resultados de citología de alto grado: la población de CACU_CONFIRMACION_CITOLOGIA (la paciente entra si su +# última citología válida del periodo es una de estos) y los valores del estrato `citologia_alto_grado`. +valor = ["ASC-H", "LIEAG", "CIS"] +estado = "provisional" +fuente = "Usuario, 2026-10-24: confirmación por biopsia según resultado citológico, las tres peores categorías Bethesda; falta que clínica la confirme" + +# =========================================================================== +# CaCu · estatus de seguimiento ASCCP (T-24c): las reglas de `cacu/seguimiento.py` +# +# El código solo aplica estas reglas; cada una dice en su comentario las opciones que +# sabe aplicar. Una opción desconocida falla con un mensaje que lista las admitidas. +# Los textos se comparan en mayúsculas y sin acentos, por contención. +# =========================================================================== + +[cacu.seguimiento.marco] +# Qué estratificación de seguimiento se publica. Opciones: "estatus" (ASCCP), "ronda" (UE, todavía no). +valor = ["estatus"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22 (§5.1): ASCCP provisional; las rondas UE, después" + +[cacu.seguimiento.referencia] +# A qué fecha se evalúa el estatus en el estrato: "inicio_periodo" (lo que traía al entrar al +# periodo, como `grupo_edad`) o "fecha_corte" (al corte del reporte). +valor = "inicio_periodo" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo" + +[cacu.seguimiento.precedencia] +# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de +# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir). +# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo). +valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.colposcopia.evidencias] +# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto): +# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos` +# "cie" una nota de colposcopia con un CIE-10 de `colposcopia.cie` +# "diagnostico_texto" una nota de colposcopia cuyo diagnóstico en texto contiene uno de +# `colposcopia.diagnosticos` (la nota que llega «S/C») +# "orden_biopsia" una orden de biopsia (la solicitud) +# "biopsia" una biopsia reportada +# «Nota de colposcopia»: de una de `colposcopia.especialidades` y, con `colposcopia.requisito`, posterior +# a la cita de valoración. +valor = ["motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: el motivo, el CIE y el diagnóstico en texto, solo en notas de colposcopia" + +[cacu.seguimiento.colposcopia.requisito] +# Qué tiene que haber antes de una nota de colposcopia para que cuente. Opciones: +# "valoracion_previa" una cita de valoración anterior: la nota que resuelve una toma, con las reglas de +# CACU_DIAS_TOMA_DIAGNOSTICO (`cacu.diagnostico.cie`, `cacu.diagnostico.especialidades` +# y `cacu.horizontes.toma_diagnostico_dias`); es de donde sale la fecha de diagnóstico +# "ninguno" cuenta sola +valor = "valoracion_previa" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «si no hay cita de valoración, que es de la que se toma la fecha de diagnóstico, no puede haber cita de colposcopia»" + +[cacu.seguimiento.colposcopia.biopsia_requisito] +# Cuándo cuentan la orden de biopsia y la biopsia reportada. Opciones: +# "mismo_dia_que_colposcopia" la orden (o la solicitud de la reportada) es del mismo día que una nota de +# colposcopia válida de la paciente: la colposcopia es la madre de la biopsia +# "ninguno" cuentan solas +valor = "mismo_dia_que_colposcopia" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «la orden de biopsia debe ser expedida el mismo día que la de colposcopia»; «la colposcopia es padre de la biopsia»" + +[cacu.seguimiento.colposcopia.motivos] +# Textos del motivo de consulta de una nota de colposcopia que la indican (lista libre, en mayúsculas y sin acentos). +valor = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.colposcopia.especialidades] +# Especialidades de una nota de colposcopia (para el motivo, el CIE y el diagnóstico en texto). Opciones: +# el enum `Especialidad` de Core (MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA). +valor = ["CLINICA_MUJER_COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: la nota de colposcopia es de «Clínica de la Mujer y Colposcopia», no hay otra" + +[cacu.seguimiento.colposcopia.cie] +# CIE-10 de una nota de colposcopia que indican colposcopia, como los deja la carga (sin punto). +# Opciones: el enum CIE-10 compartido con dev-data. +valor = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme; B97.7 (VPH) agregado por el ejemplo del usuario (2026-10-22)" + +[cacu.seguimiento.colposcopia.diagnosticos] +# Textos del diagnóstico de una nota de colposcopia que indican colposcopia aunque el CIE llegue +# «S/C» (lista libre, en mayúsculas y sin acentos). +valor = ["VIRUS DEL PAPILOMA HUMANO"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «S/C y con Diagnóstico: VIRUS DEL PAPILOMA HUMANO»" + +[cacu.seguimiento.tratamiento.fuentes] +# Qué cuenta como tratamiento. Opciones: "nota_posterior_a_colposcopia" (una nota con un CIE-10 de +# `tratamiento.cie`, posterior en fecha a la primera evidencia de colposcopia). +valor = ["nota_posterior_a_colposcopia"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: el tratamiento está en la nota médica, después de una de colposcopia" + +[cacu.seguimiento.tratamiento.cie] +# CIE-10 de la nota de tratamiento, como los deja la carga. Opciones: el enum CIE-10 compartido. +valor = ["D06", "D060", "D061", "D067", "D069"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «un código CIE-10 anómalo, por ejemplo D06»" + +[cacu.seguimiento.insuficiente.regla] +# Cuándo la historia no alcanza. Opciones: "inicio_datos_posterior_a_alta", "sin_alta_registrada", +# "ambos", "nunca". Hoy no hay fecha de alta (derechohabiencia): con "inicio_datos_posterior_a_alta" +# se asume alta posterior al inicio de los datos y nadie cae; con "sin_alta_registrada", todas caerían. +valor = "inicio_datos_posterior_a_alta" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: sin columna de alta, se asume posterior" + +[cacu.seguimiento.vigilancia.especialidades] +# Especialidades de las citologías de vigilancia. Opciones: el enum `Especialidad` de Core. Se aplica +# solo cuando la especialidad de la citología se conoce (la de su orden): una paciente sale de +# vigilancia si todas sus citologías tienen especialidad conocida y ninguna está aquí. +valor = ["MEDICINA_FAMILIAR", "CLINICA_MUJER_COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: solo cuando se conoce" + +# =========================================================================== +# CaCu · la lista de seguimiento (T-24d): `GET /cacu/seguimiento`, `serving/seguimiento.py` +# =========================================================================== + +[cacu.seguimiento.ventana_meses] +# Meses hacia atrás desde el corte en los que un estudio mete a la paciente en la lista. Opciones: 1, 3, 6, 12. +valor = 3 +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.fecha_estudio] +# Desde qué fecha cuenta la ventana. Opciones: "toma" (la de la toma) o "reporte" (la de su resultado). +valor = "toma" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.estudios] +# Qué estudios meten a la paciente en la lista. Opciones: cualquier subconjunto de "citologia" y "vph". +valor = ["citologia", "vph"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.resultado_mostrado] +# Qué citología mostrar si hay varias en la ventana. Opciones: "ultimo" o "mas_grave" (por el orden de +# `cacu.catalogos.citologia`, de menos a más grave; empate, la más reciente). El VPH muestra siempre el último. +valor = "ultimo" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +# Catálogo de resultados citológicos de CaCu (C2), de menos a más grave. Las claves son las +# de `CelulasEscamosas` en Core (`cit_celulas_escamosas`). +[cacu.catalogos.sin_dato] +valor = { etiqueta = "Sin dato", color = "#C9CDD2" } +estado = "confirmado" +fuente = "lista: «sin dato» siempre se muestra como categoría propia" + +[cacu.catalogos.citologia] +valor = [ + { clave = "NORMAL", etiqueta = "Normal", color = "#9DBFE3" }, + { clave = "ASC-US", etiqueta = "ASC-US", color = "#2F6DB3" }, + { clave = "LIEBG", etiqueta = "LIEBG", color = "#E8C28E" }, + { clave = "ASC-H", etiqueta = "ASC-H", color = "#D98E4A" }, + { clave = "LIEAG", etiqueta = "LIEAG", color = "#B55A1F" }, + { clave = "CIS", etiqueta = "Carcinoma in situ", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Las seis categorías de CelulasEscamosas (Core); falta decidir si se agrupan (indicadores.md pide cinco como máximo en la figura) y si entran glandulares y carcinoma invasor (I-K61); colores provisionales" + +[cacu.catalogos.resultado_anormal] +valor = [ + { clave = "NO_ANORMAL", etiqueta = "Sin anomalía", color = "#9DBFE3" }, + { clave = "ANORMAL", etiqueta = "Anormal", color = "#B55A1F" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Anormal es la lista `cacu.citologia_anomala` (la de IND1); colores provisionales" + +# Catálogo de BI-RADS de CaMa (C2). Las claves son las del staging (`mast_birads`). +[cama.catalogos.sin_dato] +valor = { etiqueta = "Sin dato", color = "#C9CDD2" } +estado = "confirmado" +fuente = "lista: «sin dato» siempre se muestra como categoría propia" + +[cama.catalogos.birads] +valor = [ + { clave = "B0", etiqueta = "BI-RADS 0", color = "#8A9199" }, + { clave = "B1", etiqueta = "BI-RADS 1", color = "#9DBFE3" }, + { clave = "B2", etiqueta = "BI-RADS 2", color = "#2F6DB3" }, + { clave = "B3", etiqueta = "BI-RADS 3", color = "#E8C28E" }, + { clave = "B4A", etiqueta = "BI-RADS 4A", color = "#E0A060" }, + { clave = "B4B", etiqueta = "BI-RADS 4B", color = "#CF7D3C" }, + { clave = "B4C", etiqueta = "BI-RADS 4C", color = "#C26A2B" }, + { clave = "B5", etiqueta = "BI-RADS 5", color = "#B55A1F" }, + { clave = "B6", etiqueta = "BI-RADS 6", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). fixture de CaMa (B0, B1, B2, B4). Subcategorías 4A, 4B y 4C: el hospital las reporta y llegan normalizadas (usuario, 2026-10-16). Un 4 sin subcategoría ya no tiene barra fija en 0: si llega alguno, se reporta tal cual después de «Sin dato», como todo valor fuera del catálogo, y sigue contando como sospecha y en BI-RADS 4 a 6 (cama.birads_sospecha, cama.birads_4_a_6). Colores provisionales" + +[cacu.catalogos.biopsia] +# Grados histológicos de la biopsia cervical (C2), de menos a más grave. Las claves son las +# de `GradoCIN` en Core (`bx_cin_grado`). +valor = [ + { clave = "NORMAL", etiqueta = "Normal", color = "#9DBFE3" }, + { clave = "LIEBG", etiqueta = "LIEBG (CIN 1)", color = "#E8C28E" }, + { clave = "LIEAG", etiqueta = "LIEAG (CIN 2 y 3)", color = "#D98E4A" }, + { clave = "CIS", etiqueta = "Carcinoma in situ", color = "#B55A1F" }, + { clave = "CARCINOMA", etiqueta = "Carcinoma invasor", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Los grados de GradoCIN (Core) menos DESCONOCIDO, que se reporta tal cual; colores provisionales" + +[cama.catalogos.biopsia] +# Grados histológicos de la biopsia de mama (C2), de menos a más grave. Las claves son las de +# `GradoHistologicoMama` en Core (`bx_grado_histologico`). +valor = [ + { clave = "BENIGNO", etiqueta = "Benigno", color = "#9DBFE3" }, + { clave = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ", color = "#D98E4A" }, + { clave = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Los grados de GradoHistologicoMama (Core) menos DESCONOCIDO, que se reporta tal cual; colores provisionales" + +[cama.biopsia_cancer] +# Grados de la biopsia de mama que cuentan como cáncer: el grupo «anómalo» de CAMA_BIOPSIAS. +valor = ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"] +estado = "provisional" +fuente = "Propuesta para poder agrupar, falta que clínica la confirme (usuario, 2026-10-13: par de gráficas de biopsias)" + +[cama.birads_gravedad] +# Las categorías de BI-RADS de menos a más grave, para ordenar su presentación. Es el mismo +# orden con que CAMA_BIRADS elige la categoría de cada paciente (`GRAVEDAD`, S-M54). +valor = ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"] +estado = "provisional" +fuente = "S-M54: un BI-RADS 0 (incompleto) pide más estudios y pesa más que uno benigno; falta que clínica lo confirme. Un 4 sin subcategoría pesa menos que 4A (usuario, 2026-10-16)" + +[cama.birads_sospecha] +# BI-RADS que piden biopsia: el denominador de CAMA_CONFIRMACION_BIRADS45. +valor = ["B4", "B4A", "B4B", "B4C", "B5"] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme (usuario, 2026-10-13: «confirmación histopatológica BI-RADS 4/5»). Con las subcategorías 4A, 4B y 4C (usuario, 2026-10-16)" + +[cama.birads_4_a_6] +# BI-RADS que cuentan CAMA_BIRADS456_PACIENTE y CAMA_BIRADS456_MASTOGRAFIA: los de sospecha +# (4, 5) y la malignidad confirmada (6). No es `birads_sospecha`: ese es el denominador de la +# confirmación histopatológica, y un B6 ya está confirmado. +valor = ["B4", "B4A", "B4B", "B4C", "B5", "B6"] +estado = "provisional" +fuente = "Usuario, 2026-10-16: conteos de BI-RADS 4, 5 y 6 por paciente y por mastografía; falta que clínica lo confirme" + +[cama.catalogos.birads_4_a_6] +valor = [ + { clave = "B4A", etiqueta = "BI-RADS 4A", color = "#E0A060" }, + { clave = "B4B", etiqueta = "BI-RADS 4B", color = "#CF7D3C" }, + { clave = "B4C", etiqueta = "BI-RADS 4C", color = "#C26A2B" }, + { clave = "B5", etiqueta = "BI-RADS 5", color = "#B55A1F" }, + { clave = "B6", etiqueta = "BI-RADS 6", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Subconjunto de cama.catalogos.birads, con los mismos colores. Sin B4: un 4 sin subcategoría se reporta tal cual después de «Sin dato» (usuario, 2026-10-16)" + +# =========================================================================== +# Periodo de observación: desde cuándo hay datos de cada proyecto +# =========================================================================== + +[cacu.observacion.inicio_datos] +# Primer día del que hay datos cargados. Antes de esa fecha no se sabe qué le pasó a la +# paciente: quien se tamizó antes parece nueva. Lo usa el paso `observar`. +valor = "2023-01-01" +estado = "sin_definir" +fuente = "indicadores_kit_0, issues del catálogo de CaCu (I-12): «con historia desde 2023»; falta que quien administra la fuente confirme la fecha de la primera extracción" + +[cama.observacion.inicio_datos] +valor = "2023-01-01" +estado = "sin_definir" +fuente = "Sin fuente propia: se copia el de CaCu para poder correr; falta la fecha de la primera extracción de CaMa" + +[tea.observacion.inicio_datos] +valor = "2025-01-01" +estado = "confirmado" +fuente = "responsable de TEA, 2026-10-21" + +# =========================================================================== +# Vínculos entre un resultado y su toma (paso `verificar_vinculos`) +# =========================================================================== + +[comun.vinculos.minimo_validos] +# Proporción mínima de filas con vínculo válido, de 0 a 1. Solo se exige si la arista se +# llama con `exigir=True` (`vinculos_del_proyecto` de webapi.orchestration): por debajo, falla en vez de dejar calcular con vínculos rotos. +valor = 0.95 +estado = "sin_definir" +fuente = "Sin decisión: 0.95 es un punto de partida para poder correr; falta medirlo con datos reales" + +# =========================================================================== +# Horizontes: una clave por par de eventos (MV-4). Días desde el primer evento en los que +# todavía se espera el segundo; el día en que se cumplen ya no se espera. +# =========================================================================== + +[cacu.horizontes.toma_reporte_dias] +# Días desde la toma en los que todavía se espera el resultado: pasado ese plazo sin +# resultado, el estudio ya no está «en observación» y cuenta como excluido de C3r. +valor = 60 +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme: no hay ventana de monitoreo fijada (usuario, 2026-10-13). S-K85 (indicadores_mvp.md): 60 es el de las pruebas de campo" + +[cama.horizontes.toma_reporte_dias] +valor = 60 +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme: no hay ventana de monitoreo fijada (usuario, 2026-10-13). S-K85 (indicadores_mvp.md): 60 es el de las pruebas de campo" + +[cacu.horizontes.toma_diagnostico_dias] +# Días desde la toma en los que una nota de diagnóstico todavía se le atribuye: la primera +# nota con un CIE-10 de `cacu.diagnostico.cie` antes de que se cumpla el plazo es su +# diagnóstico. Pasado el plazo sin nota, la toma cuenta como excluida de C3r (S-TD4). +valor = 180 +estado = "provisional" +fuente = "Arbitrario para poder calcular (usuario, 2026-10-16: «las ventanas de tiempo, dejarlas parametrizadas»); falta que clínica lo fije" + +[cama.horizontes.toma_diagnostico_dias] +valor = 180 +estado = "provisional" +fuente = "Arbitrario para poder calcular (usuario, 2026-10-16: «las ventanas de tiempo, dejarlas parametrizadas»); falta que clínica lo fije" + +# =========================================================================== +# Diagnóstico: las notas médicas que resuelven una toma y las que son antecedente (S-TD3) +# =========================================================================== +# Los CIE-10 van sin punto (C53.9 -> C539) y se comparan exactos: cada lista trae el código +# de tres caracteres y sus subcategorías. Se cambian aquí sin tocar el código. + +[cacu.diagnostico.cie] +# CACU_DIAS_TOMA_DIAGNOSTICO: CIE-10 de la nota que resuelven la toma, sea cual sea el +# resultado (usuario, 2026-10-16: «el diagnóstico no necesariamente tiene que ser maligno»): +# normal: Z01.4 (examen ginecológico) y Z12.4 (pesquisa de tumor del cuello uterino); +# VPH: B97.7 (papilomavirus); citología anormal: R87.6; +# lesión escamosa: N87.0, N87.1, N87.2 y N87.9 (displasia cervical leve, moderada, grave +# y sin especificar); +# cáncer: D06 (carcinoma in situ) y C53 (tumor maligno del cuello del útero). +valor = [ + "Z014", "Z124", + "B977", "R876", + "N87", "N870", "N871", "N872", "N879", + "D06", "D060", "D061", "D067", "D069", + "C53", "C530", "C531", "C538", "C539", +] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cacu.diagnostico.cie_antecedente] +# Una nota con uno de estos CIE-10 anterior a la toma deja fuera la toma: la paciente ya es +# un caso (S-TD2). Solo la incidencia, D06 y C53: con la lista amplia, cualquier consulta +# previa sacaría a la paciente del tamizaje. +valor = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cacu.diagnostico.especialidades] +# Las especialidades (código de `Core`, `nota_medica.enums.Especialidad`) cuyas notas +# resuelven la toma: las que dan el diagnóstico, no medicina familiar. +valor = ["CLINICA_MUJER_COLPOSCOPIA", "CIRUGIA_ONCOLOGICA"] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cama.diagnostico.cie] +# CAMA_DIAS_TOMA_DIAGNOSTICO: CIE-10 de la nota que resuelven la toma, sea cual sea el resultado: +# normal: Z12.3 (pesquisa de tumor de la mama); +# benignos: N60 (displasia mamaria benigna), N61 a N64 (otros trastornos de la mama) y +# D24 (tumor benigno de la mama); +# imagen anormal: R92; +# cáncer: D05 (carcinoma in situ) y C50 (tumor maligno de la mama). +valor = [ + "Z123", + "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", + "N61", "N62", "N63", + "N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", + "D24", "R92", + "D05", "D050", "D051", "D057", "D059", + "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509", +] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cama.diagnostico.cie_antecedente] +# Como en CaCu: solo la incidencia, D05 y C50. +valor = [ + "D05", "D050", "D051", "D057", "D059", + "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509", +] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cama.diagnostico.especialidades] +# El catálogo de `Core` no tiene una clínica de mama: queda cirugía oncológica. +valor = ["CIRUGIA_ONCOLOGICA"] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" diff --git a/webapi/orchestration/reference/periods.py b/webapi/orchestration/reference/periods.py new file mode 100644 index 0000000..4d8f6a7 --- /dev/null +++ b/webapi/orchestration/reference/periods.py @@ -0,0 +1,154 @@ +"""`dim_periodo`: una sola definición de a qué periodo pertenece una fecha. + +Se genera, no se escribe a mano ni se calcula con `strftime` en cada SQL +(ADR-003 §9, regla 4). Cada periodo es el intervalo `[inicio, fin)`. + +Hay un tipo por granularidad (S-M4, T-1 de v0.4.0); el `periodo_id` dice +el tipo y ordena bien como texto: + + dia 2025-03-05 un día + semana_epidemiologica 2025-SE10 domingo a domingo + semana_habil 2025-SH10 lunes a sábado: los cinco días hábiles + semana_iso 2025-W10 lunes a lunes, ISO 8601 + mes 2025-03 + bimestre 2025-B2 enero-febrero = B1 + trimestre 2025-T1 enero-marzo = T1 + semestre 2025-S1 enero-junio = S1 + +`anio` es el año del periodo; en las semanas, el año de la semana, que +puede empezar en diciembre del anterior. `semestre` es el semestre que +contiene el inicio del periodo. +""" + +from collections.abc import Callable, Iterable +from datetime import date, timedelta + +from core.indicadores.registro import DimPeriodoBase +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + +Generador = Callable[[type[DimPeriodoBase], int], list[DimPeriodoBase]] + + +class TipoDePeriodoDesconocido(ValueError): + """Se pidió un tipo de periodo que el kit no sabe generar.""" + + +def semestres(anio_inicio: int, anio_fin: int, *, tablas: TablasKit) -> list[DimPeriodoBase]: + """Los semestres de `anio_inicio` a `anio_fin`, los dos incluidos.""" + return periodos("semestre", anio_inicio, anio_fin, tablas=tablas) + + +def periodos( + tipo: str, anio_inicio: int, anio_fin: int, *, tablas: TablasKit +) -> list[DimPeriodoBase]: + """Los periodos de un tipo cuyo año va de `anio_inicio` a `anio_fin`, los dos incluidos.""" + if tipo not in _GENERADORES: + raise TipoDePeriodoDesconocido( + f"No hay periodos de tipo {tipo!r}; los tipos son {', '.join(TIPOS_PERIODO)}." + ) + generar = _GENERADORES[tipo] + return [ + fila for anio in range(anio_inicio, anio_fin + 1) for fila in generar(tablas.DimPeriodo, anio) + ] + + +def periodos_de_tipos( + tipos: Iterable[str], anio_inicio: int, anio_fin: int, *, tablas: TablasKit +) -> list[DimPeriodoBase]: + """Los periodos de varios tipos, uno tras otro. Los `periodo_id` no chocan entre tipos.""" + return [fila for tipo in tipos for fila in periodos(tipo, anio_inicio, anio_fin, tablas=tablas)] + + +def inicio_semana_epidemiologica(anio: int) -> date: + """El domingo en que empieza la semana epidemiológica 1 de `anio`. + + La semana 1 es la primera que tiene al menos cuatro días en el año + (regla de la Secretaría de Salud y del CDC): la que contiene el 4 de + enero. Puede empezar entre el 29 de diciembre y el 4 de enero. + """ + cuatro_de_enero = date(anio, 1, 4) + return cuatro_de_enero - timedelta(days=(cuatro_de_enero.weekday() + 1) % 7) + + +def _fila( + modelo: type[DimPeriodoBase], periodo_id: str, tipo: str, inicio: date, fin: date, anio: int +) -> DimPeriodoBase: + return modelo( + periodo_id=periodo_id, + tipo=tipo, + inicio=inicio, + fin=fin, + anio=anio, + semestre=1 if inicio.month <= 6 else 2, + ) + + +def _dias(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]: + primero, siguiente = date(anio, 1, 1), date(anio + 1, 1, 1) + return [ + _fila(modelo, dia.isoformat(), "dia", dia, dia + timedelta(days=1), anio) + for dia in (primero + timedelta(days=n) for n in range((siguiente - primero).days)) + ] + + +def _por_meses(meses: int, tipo: str, prefijo: str) -> Generador: + """Los periodos de `meses` meses que parten el año desde enero.""" + + def generar(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]: + filas = [] + for numero in range(1, 12 // meses + 1): + mes = (numero - 1) * meses + 1 + inicio = date(anio, mes, 1) + fin = date(anio + 1, 1, 1) if mes + meses > 12 else date(anio, mes + meses, 1) + periodo_id = f"{anio}-{numero:02d}" if not prefijo else f"{anio}-{prefijo}{numero}" + filas.append(_fila(modelo, periodo_id, tipo, inicio, fin, anio)) + return filas + + return generar + + +def _semanas( + tipo: str, prefijo: str, inicio_del_anio: Callable[[int], date], dias_desde_el_inicio: tuple[int, int] +) -> Generador: + """Las semanas de un año: de `inicio_del_anio(anio)` al de `anio + 1`, de siete en siete. + + `dias_desde_el_inicio` recorta cada semana: (0, 7) es la semana entera; + (1, 6), de lunes a sábado en una semana que empieza en domingo. + """ + desde, hasta = dias_desde_el_inicio + + def generar(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]: + primera, siguiente = inicio_del_anio(anio), inicio_del_anio(anio + 1) + return [ + _fila( + modelo, + f"{anio}-{prefijo}{numero:02d}", + tipo, + semana + timedelta(days=desde), + semana + timedelta(days=hasta), + anio, + ) + for numero, semana in enumerate( + (primera + timedelta(weeks=n) for n in range((siguiente - primera).days // 7)), + start=1, + ) + ] + + return generar + + +_GENERADORES: dict[str, Generador] = { + "dia": _dias, + "semana_epidemiologica": _semanas("semana_epidemiologica", "SE", inicio_semana_epidemiologica, (0, 7)), + # La semana hábil lleva el número y el año de la epidemiológica que la contiene (S-M7). + "semana_habil": _semanas("semana_habil", "SH", inicio_semana_epidemiologica, (1, 6)), + "semana_iso": _semanas("semana_iso", "W", lambda anio: date.fromisocalendar(anio, 1, 1), (0, 7)), + "mes": _por_meses(1, "mes", ""), + "bimestre": _por_meses(2, "bimestre", "B"), + "trimestre": _por_meses(3, "trimestre", "T"), + "semestre": _por_meses(6, "semestre", "S"), +} + +TIPOS_PERIODO = tuple(_GENERADORES) diff --git a/webapi/orchestration/reference/rules.py b/webapi/orchestration/reference/rules.py new file mode 100644 index 0000000..fe11c8f --- /dev/null +++ b/webapi/orchestration/reference/rules.py @@ -0,0 +1,101 @@ +"""Registro L2 de parámetros: `parametros.toml` cargado en `def_parametro`. + +El archivo en git es la única fuente de verdad. La tabla se reconstruye +entera en cada carga; nadie la edita a mano (ADR-003 §9). +""" + +import hashlib +import json +import tomllib +from pathlib import Path + +from core.indicadores.registro import DefParametroBase +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + +# Un solo archivo para todos los proyectos, dentro del paquete. +RUTA_PARAMETROS = Path(__file__).resolve().parent / "parametros.toml" +ESTADOS_PARAMETRO = ("sin_definir", "provisional", "confirmado") + + +class ParametroSinDefinir(LookupError): + """Se pidió un parámetro que nadie ha decidido todavía.""" + + +def leer_parametros(ruta: Path, *, tablas: TablasKit) -> list[DefParametroBase]: + """Lee el archivo y devuelve una fila por parámetro, ya validada. + + Un parámetro es una tabla con algún valor que no es tabla; su clave es + la ruta de secciones con puntos: `[tea.cohorte.edad_min_meses]` da + `"tea.cohorte.edad_min_meses"`. Una tabla sin esas llaves es una + sección más. + """ + contenido = Path(ruta).read_bytes() + toml_sha = hashlib.sha256(contenido).hexdigest() + secciones = tomllib.loads(contenido.decode("utf-8")) + return [ + _a_fila(tablas.DefParametro, clave, parametro, toml_sha) + for clave, parametro in _parametros_de(secciones) + ] + + +def valores_del_archivo(ruta: Path = RUTA_PARAMETROS) -> dict: + """Clave -> valor de cada parámetro del archivo, sin estado ni base. + + Para quien necesita una regla antes de que exista `def_parametro` + (los antecedentes de TEA, al cargar). No comprueba el estado. + """ + secciones = tomllib.loads(Path(ruta).read_text(encoding="utf-8")) + return {clave: parametro.get("valor") for clave, parametro in _parametros_de(secciones)} + + +def valor_de( + sesion: Session, clave: str, *, tablas: TablasKit, permitir_sin_definir: bool = False +): + """El valor de un parámetro. + + Un parámetro `sin_definir` trae un valor que solo permite correr: hay que pedirlo a propósito con `permitir_sin_definir=True`. + """ + fila = sesion.get(tablas.DefParametro, clave) + if fila is None: + raise KeyError(f"No existe el parámetro {clave!r}.") + if fila.estado == "sin_definir" and not permitir_sin_definir: + raise ParametroSinDefinir( + f"El parámetro {clave!r} está sin definir ({fila.fuente})." + ) + return json.loads(fila.valor) + + +def _parametros_de(seccion: dict, ruta: tuple[str, ...] = ()): + """(clave, tabla) de cada parámetro, en el orden del archivo.""" + for nombre, contenido in seccion.items(): + if not isinstance(contenido, dict): + raise ValueError(f"{'.'.join(ruta) or 'El archivo'}: {nombre!r} no es una sección.") + # Una sección solo tiene tablas; un parámetro tiene al menos un valor suelto + # (`estado`, `fuente`). Así una sección se puede llamar `fuente`. + if not all(isinstance(valor, dict) for valor in contenido.values()): + yield ".".join((*ruta, nombre)), contenido + else: + yield from _parametros_de(contenido, (*ruta, nombre)) + + +def _a_fila( + modelo: type[DefParametroBase], clave: str, parametro: dict, toml_sha: str +) -> DefParametroBase: + # Solo un parámetro sin definir puede no tener valor todavía. + obligatorias = {"estado", "fuente"} | ( + set() if parametro.get("estado") == "sin_definir" else {"valor"} + ) + faltan = obligatorias - set(parametro) + if faltan: + raise ValueError(f"Al parámetro {clave!r} le falta {sorted(faltan)}.") + if parametro["estado"] not in ESTADOS_PARAMETRO: + raise ValueError(f"Parámetro {clave!r}: estado desconocido {parametro['estado']!r}.") + return modelo( + clave=clave, + valor=json.dumps(parametro.get("valor"), ensure_ascii=False), + estado=parametro["estado"], + fuente=parametro["fuente"], + toml_sha=toml_sha, + ) diff --git a/webapi/orchestration/reference/support.py b/webapi/orchestration/reference/support.py new file mode 100644 index 0000000..8992cf5 --- /dev/null +++ b/webapi/orchestration/reference/support.py @@ -0,0 +1,38 @@ +"""Las tablas de apoyo que salen de los TOML (I-MD27, T-24f): `dim_fecha` y `dim_grupo_edad`. + +Las usan los estratos que cruzan fechas (`grupo_edad`: la edad cumplida, portable entre +SQLite y Postgres). Las escribe la arista `registro` de webapi.orchestration; aquí solo se arman: + + filas_de_dim_fecha de `comun.dim_fecha.desde` a `hasta`, como diccionarios para un + INSERT en bloque (se arman una vez por proceso: son decenas de miles) + grupos_de_edad_de los grupos de `.grupos_edad`, o `None` si el proyecto no + tiene cortes (TEA) + +`comun.dim_fecha.desde` es fijo porque `dia_num` y `dia_habil_num` se cuentan desde él. +""" + +from collections.abc import Mapping +from datetime import date +from functools import lru_cache + +from webapi.orchestration.reference.age_groups import grupos_de_cortes +from webapi.orchestration.reference.dates import dias +from webapi.orchestration.tables import TablasKit, tablas_de + +CLAVE_DIM_FECHA_DESDE = "comun.dim_fecha.desde" + + +def filas_de_dim_fecha(valores: Mapping, hasta: date, *, proyecto: str) -> list[dict]: + """Los días de `comun.dim_fecha.desde` a `hasta`, como diccionarios de `dim_fecha`.""" + return list(_dias(date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE]), hasta, proyecto)) + + +def grupos_de_edad_de(proyecto: str, valores: Mapping, *, tablas: TablasKit) -> list | None: + """Los grupos de edad de `.grupos_edad` (más los dos abiertos), o `None` si no tiene cortes.""" + cortes = valores.get(f"{proyecto}.grupos_edad") + return None if cortes is None else grupos_de_cortes(cortes, tablas=tablas) + + +@lru_cache(maxsize=8) +def _dias(desde: date, hasta: date, proyecto: str) -> tuple[dict, ...]: + return tuple(fila.model_dump() for fila in dias(desde, hasta, tablas=tablas_de(proyecto))) diff --git a/webapi/orchestration/silver/__init__.py b/webapi/orchestration/silver/__init__.py new file mode 100644 index 0000000..32e37cd --- /dev/null +++ b/webapi/orchestration/silver/__init__.py @@ -0,0 +1,10 @@ +"""La plata de dos tablas (F5, ADR-MD-007): de staging a `persona`, `procedimiento` y `observacion_clinica`. + + procedimiento.py `DeStaging`, `plata_desde_staging` y el orden de escritura por padres + carga.py `carga_desde_staging`: de las filas de staging a las personas y la plata + valores.py las normalizaciones de un valor de staging + personas.py de una fila de pacientes a `persona` + ordenes_y_notas.py la orden de estudio y la nota médica de CaCu y CaMa + periodo_observacion.py desde y hasta cuándo hay datos de cada paciente + vistas.py la DDL de `v_persona` +""" diff --git a/webapi/orchestration/silver/cacu.py b/webapi/orchestration/silver/cacu.py new file mode 100644 index 0000000..2a264ea --- /dev/null +++ b/webapi/orchestration/silver/cacu.py @@ -0,0 +1,69 @@ +"""CaCu en la plata de dos tablas (ADR-MD-007), por staging directo (T-20c, ADR-MD-009). + +`DESDE_STAGING`: qué procedimientos salen de cada fila de staging, con la normalización como columnas +derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`). +""" + +from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente +from core.cacu.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad + +from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio +from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre + +PACIENTES = Paciente # de donde salen las personas +ESPECIALIDADES = {e.value for e in Especialidad} +LA_TOMA_DE_SU_FILA = Padre(estudio_id="citologia", clase="toma", fuente_id="cit_id", tabla=CitologiaCervical.__tablename__) +LA_ORDEN_DEL_ESTUDIO = Padre(por_numero_de_orden="ord_numero_hospital") + + +def _genotipo_16_18(fila): + genotipos = (fila.cit_vph_genotipo_16, fila.cit_vph_genotipo_18) + return None if genotipos == (None, None) else int(any(genotipos)) + + +# La biopsia (T-22h, I-MD23): solicitada, es una `orden` del estudio `biopsia` que cuelga de la toma que la +# originó; su reporte llega después como hija `reporte`, sin reescribir la orden. Pasa de staging solo lo +# realizado: la que trae fecha de solicitud o de reporte. Con reporte y sin solicitud, la orden queda sin fecha. +def _biopsia_que_pasa(fila) -> bool: + return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None + + +DESDE_STAGING = ( + DeStaging( + CitologiaCervical, "cit_id", "toma", estudio_id="citologia", fecha="cit_fecha_toma", + padres=(LA_ORDEN_DEL_ESTUDIO,), columnas={"orden_numero": "ord_numero_hospital"}, + resultados={"cit_calidad_especimen": "citologia.calidad_muestra"}, + ), + # Un resultado sin fecha de reporte todavía no es un resultado: la fila no da reporte. + DeStaging( + CitologiaCervical, "cit_id", "reporte", estudio_id="citologia", fecha="cit_fecha_reporte", + solo_si=lambda f: f.cit_fecha_reporte is not None, padres=(LA_TOMA_DE_SU_FILA,), + resultados={ + "cit_celulas_escamosas": "citologia.bethesda", + "cit_celulas_glandulares": "citologia.celulas_glandulares", + "cit_carcinoma_invasor": "citologia.carcinoma_invasor", + "cit_dx_lesion": "citologia.dx_lesion", + }, + ), + # El VPH de la misma muestra, si se hizo; con la fecha del reporte de la citología (S-K38). + DeStaging( + CitologiaCervical, "cit_id", "reporte", estudio_id="vph", fecha="cit_fecha_reporte", + solo_si=lambda f: f.cit_fecha_reporte is not None and f.cit_vph_resultado is not None, + padres=(LA_TOMA_DE_SU_FILA,), derivadas={"genotipo_16_18": _genotipo_16_18}, + resultados={ + "cit_vph_resultado": "vph.resultado", + "genotipo_16_18": "vph.genotipo_16_18", + "cit_vph_genotipo_16": "vph.genotipo_16", + "cit_vph_genotipo_18": "vph.genotipo_18", + }, + ), + DeStaging( + BiopsiaCervical, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud", + solo_si=_biopsia_que_pasa, padres=(LA_TOMA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"}, + hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte", + resultados={"bx_cin_grado": "biopsia.grado"}),), + ), + orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES), + # El motivo de consulta y el diagnóstico en texto: de ahí sale la colposcopia del estatus de seguimiento (T-24b, T-24c). + nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, con_textos=True), +) diff --git a/webapi/orchestration/silver/cama.py b/webapi/orchestration/silver/cama.py new file mode 100644 index 0000000..e81acba --- /dev/null +++ b/webapi/orchestration/silver/cama.py @@ -0,0 +1,46 @@ +"""CaMa en la plata de dos tablas (ADR-MD-007), por staging directo (T-20c, ADR-MD-009). + +`DESDE_STAGING`: qué procedimientos salen de cada fila de staging, con la normalización como columnas +derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`). +""" + +from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente +from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad + +from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio +from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre + +PACIENTES = Paciente # de donde salen las personas +ESPECIALIDADES = {e.value for e in Especialidad} +# La toma de un resultado: la mastografía de su fila (BI-RADS) o la que la originó (`mast_id` de la biopsia). +LA_MASTOGRAFIA_DE_SU_FILA = Padre(estudio_id="mastografia", clase="toma", fuente_id="mast_id", tabla=Mastografia.__tablename__) +LA_ORDEN_DEL_ESTUDIO = Padre(por_numero_de_orden="ord_numero_hospital") + +# La biopsia (T-22h, I-MD23): solicitada, es una `orden` del estudio `biopsia` que cuelga de la toma que la +# originó; su reporte llega después como hija `reporte`, sin reescribir la orden. Pasa de staging solo lo +# realizado: la que trae fecha de solicitud o de reporte. Con reporte y sin solicitud, la orden queda sin fecha. +def _biopsia_que_pasa(fila) -> bool: + return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None + + +DESDE_STAGING = ( + DeStaging( + Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma", + padres=(LA_ORDEN_DEL_ESTUDIO,), columnas={"orden_numero": "ord_numero_hospital"}, + resultados={"mast_calidad_imagen": "mastografia.calidad_imagen"}, + ), + # Un resultado sin fecha de reporte todavía no es un resultado. + 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,), + resultados={"mast_birads": "mastografia.birads"}, + ), + 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"}, + hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte", + resultados={"bx_grado_histologico": "biopsia.grado"}),), + ), + orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES), + nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES), +) diff --git a/webapi/orchestration/silver/loads.py b/webapi/orchestration/silver/loads.py new file mode 100644 index 0000000..d545d62 --- /dev/null +++ b/webapi/orchestration/silver/loads.py @@ -0,0 +1,47 @@ +"""La carga del staging directo (T-20c): de las filas de staging a las personas y la plata. Pura. + +En un paso: las personas salen de la tabla de pacientes del proyecto (`

/plata.PACIENTES`) +y los procedimientos y observaciones, de `

/plata.DESDE_STAGING`. Lo escribe Persistance +(`guardar_carga_en`) por el modelo `carga` de webapi.orchestration. +""" + +from collections.abc import Iterable, Mapping +from importlib import import_module +from typing import NamedTuple + +from webapi.orchestration.silver.persons import a_persona +from webapi.orchestration.silver.procedures import LotePlata, plata_desde_staging +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, codigos_hospital, ruta_de_catalogo +from webapi.orchestration.tables import tablas_de + + +class CargaDesdeStaging(NamedTuple): + fuente: str # las tablas de staging que dan procedimientos, en el orden de `DESDE_STAGING` + personas: list + plata: LotePlata + + +def _plata(proyecto: str): + return import_module(f"webapi.orchestration.silver.{proyecto}") + + + +def tablas_de_staging(proyecto: str) -> tuple[type, ...]: + """Las tablas de staging que lee la carga: la de pacientes y las de `DESDE_STAGING`, sin repetir.""" + plata = _plata(proyecto) + return (plata.PACIENTES, *dict.fromkeys(c.staging for c in plata.DESDE_STAGING)) + + +def carga_desde_staging(filas: Mapping[str, Iterable], *, proyecto: str) -> CargaDesdeStaging: + """Las personas y la plata de un proyecto, desde sus filas de staging (tabla -> filas).""" + plata = _plata(proyecto) + tablas = tablas_de(proyecto) + lote = plata_desde_staging( + filas, correspondencias=plata.DESDE_STAGING, + catalogo=catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas), + codigos_hospital=codigos_hospital(proyecto), + pacientes=(p.pac_id for p in filas.get(plata.PACIENTES.__tablename__, ())), + ) + personas = [a_persona(paciente, tablas=tablas) for paciente in filas.get(plata.PACIENTES.__tablename__, ())] + fuente = ", ".join(dict.fromkeys(c.staging.__tablename__ for c in plata.DESDE_STAGING)) + return CargaDesdeStaging(fuente, personas, lote) diff --git a/webapi/orchestration/silver/observation_periods.py b/webapi/orchestration/silver/observation_periods.py new file mode 100644 index 0000000..13f1edb --- /dev/null +++ b/webapi/orchestration/silver/observation_periods.py @@ -0,0 +1,97 @@ +"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente. + +Un indicador que mira hacia atrás (¿es su primera citología?) o hacia +adelante (¿llegó la biopsia?) necesita saber cuánto se pudo observar a la +paciente. Sin eso, quien se tamizó antes de que empezaran los datos +parece nueva, y a quien se tamizó ayer parece que no le llegó nada. + +El periodo es el de la extracción: empieza el día que dice la regla +`.observacion.inicio_datos` y termina en la fecha de corte (la +de la última carga, si no se da otra). Es el mismo para todas las +pacientes; la tabla es por paciente para cuando haya una fuente mejor +(alta y baja de la derechohabiencia). Aquí se calculan las filas; las escribe +`ObservacionRepository` de Persistance (plata), en la arista `observar`. +""" + +import json +from datetime import date, datetime + +from sqlmodel import Session, func, select + +from webapi.orchestration.reference.rules import ParametroSinDefinir +from webapi.orchestration.tables import tablas_de + +TIPO_EXTRACCION = "extraccion" + + +class ObservacionSinCorte(ValueError): + """No se dio fecha de corte y no hay ninguna carga de donde tomarla.""" + + +def clave_de_inicio(proyecto: str) -> str: + """La regla que dice desde cuándo hay datos del proyecto.""" + return f"{proyecto}.observacion.inicio_datos" + + +def periodos_de_observacion( + sesion: Session, proyecto: str, *, corte: date | None = None, permitir_sin_definir: bool = False +) -> list: + """Las filas de `periodo_observacion`: un periodo de extracción por persona. Solo lee. + + Necesita las personas (la carga) y la regla en `def_parametro` (el registro). + `corte` es el último día observado; sin él, el de la última carga. Una regla + sin definir hay que pedirla a propósito, como en el cálculo. + + Raises: + KeyError: la regla no está en `def_parametro`. + ParametroSinDefinir: la regla está sin definir y no se pidió permitirla. + ObservacionSinCorte: no hay corte ni cargas. + ValueError: el corte es anterior al inicio de los datos. + """ + tablas = tablas_de(proyecto) + clave = clave_de_inicio(proyecto) + inicio = _inicio(clave, sesion.get(tablas.DefParametro, clave), permitir_sin_definir) + corte = _corte(fecha_de_ultima_carga(sesion, tablas) if corte is None else corte, inicio) + personas = sesion.exec(select(tablas.Persona).order_by(tablas.Persona.pac_id)).all() + return _periodos(tablas, inicio, corte, personas) + + +def _inicio(clave: str, regla, permitir_sin_definir: bool) -> date: + if regla is None: + raise KeyError(f"No existe el parámetro {clave!r}: corra la arista `registro`.") + if regla.estado == "sin_definir" and not permitir_sin_definir: + raise ParametroSinDefinir(f"El parámetro {clave!r} está sin definir ({regla.fuente}).") + return date.fromisoformat(json.loads(regla.valor)) + + +def _corte(corte, inicio: date) -> date: + if corte is None: + raise ObservacionSinCorte("No se dio corte y no hay ninguna carga de donde tomarlo.") + corte = a_fecha(corte) + if corte < inicio: + raise ValueError(f"El corte ({corte}) es anterior al inicio de los datos ({inicio}).") + return corte + + +def _periodos(tablas, inicio: date, corte: date, personas) -> list: + return [ + tablas.PeriodoObservacion( + pac_id=persona.pac_id, fecha_inicio=inicio, fecha_fin=corte, tipo_periodo=TIPO_EXTRACCION + ) + for persona in personas + ] + + +def fecha_de_ultima_carga(sesion: Session, 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() + return None if ultima is None else a_fecha(ultima) + + +def a_fecha(valor) -> date: + """A date however the engine returns it: text, date or date-time.""" + if isinstance(valor, datetime): + return valor.date() + if isinstance(valor, date): + return valor + return date.fromisoformat(str(valor)[:10]) diff --git a/webapi/orchestration/silver/orders_and_notes.py b/webapi/orchestration/silver/orders_and_notes.py new file mode 100644 index 0000000..f7ecde6 --- /dev/null +++ b/webapi/orchestration/silver/orders_and_notes.py @@ -0,0 +1,73 @@ +"""La orden de estudio y la nota médica de CaCu y CaMa en el staging directo (T-20c). + +El staging de los dos proyectos trae las mismas columnas (`ordenesestudio`, `notamedica`); cada uno +da sus tablas y su catálogo de especialidades. Es la normalización que hacían `cdm/ordenes.py` y +`cdm/notas.py`, como columnas derivadas: +- una orden es lo que se pidió, se haya hecho o no; sin ninguna fecha no es una orden, y su fecha es + la de emisión o, si falta, la de solicitud; +- la especialidad se guarda en el código de Core (nula si no se reconoce) y, como `valor_fuente`, tal + como llegó; +- el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`; +- el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b), + sin normalizarlos (I-K61). +""" + +from collections.abc import Collection, Mapping + +from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio +from webapi.orchestration.silver.procedures import DeStaging + + +def especialidad(columna: str, alias: Mapping[str, str], codigos: Collection[str]) -> dict: + """Las derivadas de una especialidad: su código en Core y el texto tal como llegó.""" + return { + "especialidad": lambda f: codigo_de_especialidad(getattr(f, columna), alias, codigos), + "especialidad_fuente": lambda f: texto_limpio(getattr(f, columna)), + } + + +def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collection[str]) -> DeStaging: + return DeStaging( + staging, "ord_id", "orden", estudio_de="tipo_estudio", fecha="fecha_orden", + solo_si=lambda f: (f.ord_fecha or f.ord_fecha_solicitud) is not None, + derivadas={ + "tipo_estudio": lambda f: texto_limpio(f.ord_tipo_estudio), + "fecha_orden": lambda f: f.ord_fecha or f.ord_fecha_solicitud, + "intencion": lambda f: INTENCION, + "estatus": lambda f: texto_limpio(f.ord_estatus), + "diagnostico": lambda f: texto_limpio(f.ord_diagnostico), + **especialidad("ord_especialidad", alias, codigos), + }, + columnas={"numero_hospital": "ord_numero_hospital", "codigo_fuente": "ord_tipo_estudio"}, + resultados={ + "intencion": "orden.intencion", + "ord_fecha_solicitud": "orden.fecha_solicitud", + "ord_fecha_resultado": "orden.fecha_resultado", + "estatus": "orden.estatus", + "especialidad": "orden.especialidad", + "diagnostico": "orden.diagnostico", + }, + fuentes={"especialidad": "especialidad_fuente"}, + ) + + +def nota_medica( + staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False +) -> DeStaging: + textos = { + "motivo": lambda f: texto_limpio(f.nm_motivo_consulta), + "diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto), + } if con_textos else {} + return DeStaging( + staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha", + columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional) + derivadas={ + "cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos, + }, + resultados={ + "cie_codigo": "nota_medica.diagnostico", + "especialidad": "nota_medica.especialidad", + **({f: f"nota_medica.{f}" for f in textos}), + }, + fuentes={"especialidad": "especialidad_fuente"}, + ) diff --git a/webapi/orchestration/silver/persons.py b/webapi/orchestration/silver/persons.py new file mode 100644 index 0000000..613c760 --- /dev/null +++ b/webapi/orchestration/silver/persons.py @@ -0,0 +1,30 @@ +"""De una fila de pacientes de staging a `persona` (T-20c).""" + +from core.indicadores.comunes import PersonaBase + +from webapi.orchestration.silver.values import codigo, texto_limpio +from webapi.orchestration.tables import TablasKit + + +def a_persona(paciente, *, tablas: TablasKit, **propias) -> PersonaBase: + """La persona de una fila de pacientes; las columnas propias del proyecto salen de `tablas.persona_propias`.""" + return tablas.Persona( + pac_id=paciente.pac_id, + pac_id_hospital=paciente.pac_id_hospital, + fecha_nacimiento=paciente.pac_fecha_nacimiento, + **{**tablas.persona_propias(paciente), **propias}, + ) + + +def de_derechohabiente(paciente) -> dict: + """Lo que la persona de CaCu y CaMa agrega a las comunes: lo que el hospital sabe de la derechohabiente.""" + return { + "dependencia": texto_limpio(paciente.pac_dependencia), + "parentesco": texto_limpio(paciente.pac_parentesco), + "codigo_postal": texto_limpio(paciente.pac_codigo_postal), + } + + +def con_sexo(paciente) -> dict: + """Lo que la persona de TEA agrega: el sexo, como código.""" + return {"sexo": codigo(paciente.pac_sexo)} diff --git a/webapi/orchestration/silver/procedures.py b/webapi/orchestration/silver/procedures.py new file mode 100644 index 0000000..9946a2d --- /dev/null +++ b/webapi/orchestration/silver/procedures.py @@ -0,0 +1,257 @@ +"""De staging a `procedimiento` y `observacion` (F5, ADR-MD-007; staging directo, T-20c y ADR-MD-009). + +Cada proyecto declara en `/plata.py`, `DESDE_STAGING`, qué procedimientos salen de cada +fila de cada tabla de staging (`DeStaging`): su clase, su estudio, su fecha, su padre, sus columnas +y sus resultados, nombrando columnas de staging o **derivadas** (funciones de la fila: la +normalización). `plata_desde_staging` reparte cada fila en un procedimiento (el acto) y sus +observaciones (un valor por resultado del catálogo). La carga doble y su `Correspondencia` por +tabla por tipo se retiraron en T-20c2. + +Solo se calcula: lo escribe Persistance (`guardar_carga_en`), en una transacción. Las filas salen como diccionarios, con la +llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`, +`clase`) y la de su padre, porque los `procedimiento_id` solo los conoce la base. +""" + +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import NamedTuple + +from webapi.orchestration.reference.catalogs import Catalogo + +# A igual profundidad, el orden en que se escriben las clases (`en_orden_de_padres`). +ORDEN_DE_CLASES = ("orden", "encuentro", "toma", "reporte", "parte") +# Las columnas de `procedimiento` que puede llenar una correspondencia, además de pac_id y fecha. +COLUMNAS_DE_PROCEDIMIENTO = ("numero_hospital", "orden_numero", "codigo_fuente", "id_hospital") + +Llave = tuple[str, str, str, str] # (fuente_tabla, fuente_id, estudio_id, clase) + + +@dataclass(frozen=True) +class Padre: + """Cómo encuentra un procedimiento a su padre. + + Por la llave de otra fila de staging: `fuente_id` (y, si la trae, `fuente_tabla`) son + columnas de la fila; `tabla` es la tabla de staging del padre cuando la fila no la + trae. O por el número de orden del hospital (`por_numero_de_orden`): el padre es la + orden con ese `numero_hospital`. + """ + + estudio_id: str | None = None + clase: str | None = None + fuente_id: str | None = None + fuente_tabla: str | None = None + tabla: str | None = None + por_numero_de_orden: str | None = None + + +@dataclass(frozen=True) +class Hija: + """Un procedimiento que sale de la misma fila que otro y cuelga de él (el ADOS-2 de una evaluación). + + Solo se crea si alguna de las columnas `solo_si` de la fila trae valor. Su llave tiene la + misma fila de staging, con su propio estudio y clase. + """ + + estudio_id: str + clase: str + solo_si: tuple[str, ...] + fecha: str | None = None + resultados: Mapping[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class DeStaging: + """Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c). + + El contenido de la fila son sus columnas de staging más las `derivadas` (nombre -> función de + la fila). `paciente` es la columna con el `pac_id`; nula si el procedimiento lo toma de su padre + (un instrumento, un segmento). `columnas`: columna de `procedimiento` -> columna del contenido. + `estudio_id`, `estudio_de`, `fecha`, `padres`, `resultados`, `fuentes` e `hijas` nombran + columnas del contenido. + - `solo_si`: si da falso, la fila no produce este procedimiento (un reporte sin fecha todavía + no es un reporte); no es un descarte. + - `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en + `descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging. + + Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada. + Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17). + """ + + staging: type + llave: str + clase: str + estudio_id: str | None = None + estudio_de: str | None = None + fecha: str | None = None + padres: tuple[Padre, ...] = () + columnas: Mapping[str, str] = field(default_factory=dict) + resultados: Mapping[str, str] = field(default_factory=dict) + fuentes: Mapping[str, str] = field(default_factory=dict) + hijas: tuple[Hija, ...] = () + derivadas: Mapping[str, Callable] = field(default_factory=dict) + paciente: str | None = "pac_id" + solo_si: Callable | None = None + descartar: Callable | None = None + + +class LotePlata(NamedTuple): + """Lo que recibe `guardar_plata_en`: procedimientos en orden de clase, sus observaciones y los descartes.""" + + procedimientos: list[dict] + observaciones: list[dict] + descartes: dict[str, int] + + +def plata_desde_staging( + filas: Mapping[str, Iterable], + *, + correspondencias: Iterable[DeStaging], + catalogo: Catalogo, + codigos_hospital: Mapping[str, str], + pacientes: Iterable[int] = (), +) -> LotePlata: + """De las filas de staging (tabla -> filas) a procedimientos y observaciones. Pura (staging directo, T-20c). + + Cada `DeStaging` arma el contenido de cada fila de su tabla (columnas más derivadas) y lo + reparte en un procedimiento (y sus hijas) con sus observaciones. Cada procedimiento sale como + `{"llave": Llave, "padres": [Llave | ("orden", numero)], "pac_id", "fecha", ...}` y cada + observación como `{"procedimiento": Llave, "pac_id", "resultado_id", "valor_id", + "valor_numerico", "valor_fecha", "valor_texto", "valor_fuente"}`. Una fila cuyo estudio no se + encuentra en `codigos_hospital` no entra y se cuenta en `descartes`, como una fila a la + que `descartar` le da motivo se cuenta en `descartes` y no entra. `pacientes`: los `pac_id` + conocidos, para `descartar`. + """ + pacientes = set(pacientes) + tipos, vigentes = _tipos_y_vigentes(catalogo) + procedimientos, observaciones, descartes = [], [], {} + for c in correspondencias: + tabla = c.staging.__tablename__ + for fila in filas.get(tabla, ()): + fuente_id = getattr(fila, c.llave) + if c.descartar is not None and (motivo := c.descartar(fila, pacientes)) is not None: + descartes[motivo] = descartes.get(motivo, 0) + 1 + continue + if c.solo_si is not None and not c.solo_si(fila): + continue + contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}} + contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente) + contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()}) + _repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital, + tipos, vigentes, procedimientos, observaciones, descartes) + return LotePlata(en_orden_de_padres(procedimientos), observaciones, descartes) + + +class CicloDePadres(ValueError): + """Un procedimiento del lote que es, por sus padres, ancestro de sí mismo.""" + + +def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]: + """Los procedimientos en el orden en que se escriben: cada uno después de sus padres del mismo lote (T-22h). + + `guardar_plata_en` resuelve el padre con lo que ya escribió, así que un padre del lote va antes que + sus hijos aunque su clase vaya después (la orden de una biopsia cuelga de su toma). A igual + profundidad, por `ORDEN_DE_CLASES` y, dentro de la clase, como llegaron. Un padre fuera del lote (ya + escrito, o la orden del hospital por su número) no cuenta. Un ciclo de padres falla con `CicloDePadres`. + """ + por_llave = {p["llave"]: p for p in procedimientos} + profundidad: dict = {} + + def de(llave, camino=()): + if llave in profundidad: + return profundidad[llave] + if llave in camino: + raise CicloDePadres(f"Ciclo de padres en el lote: {' -> '.join(map(str, (*camino, llave)))}.") + padres = [padre for padre in por_llave[llave]["padres"] if padre in por_llave] + profundidad[llave] = 1 + max((de(padre, (*camino, llave)) for padre in padres), default=-1) + return profundidad[llave] + + return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3]))) + + +def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]: + tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados} + vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"} + return tipos, vigentes + + +def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, columnas: tuple[str, ...], + codigos_hospital: Mapping[str, str], tipos: dict, vigentes: set, + procedimientos: list, observaciones: list, descartes: dict) -> None: + """Un procedimiento (y sus hijas) con sus observaciones, desde el contenido de una fila: el motor común.""" + estudio_id = c.estudio_id or codigos_hospital.get(contenido.get(c.estudio_de)) + if estudio_id is None: + motivo = f"{nombre}: {c.estudio_de} fuera de catálogo" + descartes[motivo] = descartes.get(motivo, 0) + 1 + return + llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase) + procedimientos.append({ + "llave": llave, + "padres": [p for p in (_parent(padre, contenido) for padre in c.padres) if p is not None], + "pac_id": contenido.get("pac_id"), + "fecha": contenido.get(c.fecha) if c.fecha else None, + # Sin columna de fecha (instrumentos, segmentos), la fecha es la del padre; con ella, puede quedar nula. + "fecha_del_padre": c.fecha is None, + **{columna: contenido.get(columna) for columna in columnas}, + }) + observaciones += _observaciones(llave, contenido, c.resultados, c.fuentes, tipos, vigentes) + for hija in c.hijas: + if all(contenido.get(columna) is None for columna in hija.solo_si): + continue + llave_hija = (fuente_tabla, str(fuente_id), hija.estudio_id, hija.clase) + procedimientos.append({ + "llave": llave_hija, "padres": [llave], "pac_id": contenido.get("pac_id"), + "fecha": contenido.get(hija.fecha) if hija.fecha else None, "fecha_del_padre": hija.fecha is None, + }) + observaciones += _observaciones(llave_hija, contenido, hija.resultados, c.fuentes, tipos, vigentes) + + +def valor_de_observacion(valor, fuente, *, tipo_valor: str, en_catalogo: Callable[[str], bool]) -> dict: + """El valor en su columna según `tipo_valor` (ADR-MD-007). Un valor nulo da la observación con valor nulo.""" + fila = {"valor_id": None, "valor_numerico": None, "valor_fecha": None, "valor_texto": None, "valor_fuente": None} + if tipo_valor == "codigo": + texto = None if valor is None else str(valor) + fila["valor_id"] = texto if texto is not None and en_catalogo(texto) else None + fila["valor_fuente"] = None if fuente is None else str(fuente) + elif tipo_valor in ("booleano", "numero"): + fila["valor_numerico"] = None if valor is None else float(valor) + elif tipo_valor == "fecha": + fila["valor_fecha"] = valor + else: # texto, externo + fila["valor_texto"] = None if valor is None else str(valor) + return fila + + +def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str], fuentes: Mapping[str, str], + tipos: dict, vigentes: set) -> list[dict]: + filas = [] + for columna, plantilla in resultados.items(): + resultado_id = plantilla.format(estudio=llave[2]) + filas.append({ + "procedimiento": llave, + "pac_id": contenido.get("pac_id"), + "resultado_id": resultado_id, + **valor_de_observacion( + contenido.get(columna), _fuente(contenido, columna, fuentes), + tipo_valor=tipos[resultado_id], en_catalogo=lambda v, r=resultado_id: (r, v) in vigentes, + ), + }) + return filas + + +def _fuente(contenido: dict, columna: str, fuentes: Mapping[str, str]): + """El valor tal como llegó: el de su columna fuente, o el mismo valor si esa columna viene vacía.""" + fuente = contenido.get(fuentes.get(columna, columna)) + return contenido.get(columna) if fuente is None else fuente + + +def _parent(padre: Padre, contenido: dict): + if padre.por_numero_de_orden: + numero = contenido.get(padre.por_numero_de_orden) + return None if numero is None else ("orden", numero) + fuente_id = contenido.get(padre.fuente_id) + if fuente_id is None: + return None + tabla = contenido.get(padre.fuente_tabla) if padre.fuente_tabla else padre.tabla + if tabla is None: + return None + return (tabla, str(fuente_id), padre.estudio_id, padre.clase) diff --git a/webapi/orchestration/silver/quality.py b/webapi/orchestration/silver/quality.py new file mode 100644 index 0000000..249f8fe --- /dev/null +++ b/webapi/orchestration/silver/quality.py @@ -0,0 +1,43 @@ +"""Calidad de la plata de dos tablas: lo que está mal en `procedimiento` y `observacion`, contado. + +Cuatro conteos, una consulta cada uno (ADR-MD-007): + + reporte_sin_padre un reporte o una parte sin procedimiento padre + fuera_de_catalogo una observación codificada cuyo valor no está en `cat_valor` (llegó texto, no código) + de_otro_estudio una observación de un resultado de otro estudio que el de su procedimiento + (salvo los `orden.*` de una orden, cuyo estudio es el pedido) + nulas una observación sin ningún valor + +Solo lee y solo cuenta. Qué hacer con los conteos (avisar) lo decide la arista +`verificar_plata` de webapi.orchestration. +""" + +from sqlalchemy import and_, func, not_, select +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + +CONTEOS = ("reporte_sin_padre", "fuera_de_catalogo", "de_otro_estudio", "nulas") +VALORES = ("valor_id", "valor_numerico", "valor_fecha", "valor_texto", "valor_fuente") + + +def verificar_plata(sesion: Session, *, tablas: TablasKit) -> dict[str, int]: + """Los cuatro conteos de `CONTEOS` sobre el estado actual de las dos tablas.""" + p, o, r = tablas.Procedimiento, tablas.Observacion, tablas.CatResultado + observaciones_con_resultado = select(func.count()).select_from(o).join(r, r.resultado_id == o.resultado_id) + consultas = { + "reporte_sin_padre": select(func.count()).select_from(p).where( + p.clase.in_(("reporte", "parte")), p.padre_id.is_(None) + ), + "fuera_de_catalogo": observaciones_con_resultado.where( + r.tipo_valor == "codigo", o.valor_id.is_(None), o.valor_fuente.is_not(None) + ), + "de_otro_estudio": observaciones_con_resultado.join(p, p.procedimiento_id == o.procedimiento_id).where( + r.estudio_id != p.estudio_id, + not_(and_(r.estudio_id == "orden", p.clase == "orden")), + ), + "nulas": select(func.count()).select_from(o).where( + *(getattr(o, columna).is_(None) for columna in VALORES) + ), + } + return {nombre: sesion.execute(consulta).scalar_one() for nombre, consulta in consultas.items()} diff --git a/webapi/orchestration/silver/values.py b/webapi/orchestration/silver/values.py new file mode 100644 index 0000000..4292b54 --- /dev/null +++ b/webapi/orchestration/silver/values.py @@ -0,0 +1,44 @@ +"""Las normalizaciones de un valor de staging que usan las columnas derivadas de `DESDE_STAGING` (T-20c). + +Una sola definición por regla (T-20c3; antes repartidas en `cdm/` y en la normalización de cada proyecto, +retirados en T-20c2). +""" + +from collections.abc import Collection, Mapping + +INTENCION = "order" # FHIR `ServiceRequest.intent` de una orden; sus valores están sin definir + + +def texto_limpio(valor) -> str | None: + """Un texto de staging sin espacios alrededor; nulo si viene vacío. No lo normaliza más (I-K61).""" + if valor is None: + return None + return str(valor).strip() or None + + +def codigo(texto: str | None) -> str | None: + """Un código como lo compara ulises: sin espacios al borde y en mayúsculas; vacío es nulo.""" + if texto is None: + return None + return texto.strip().upper() or None + + +def cie(texto: str | None) -> str | None: + """Un código CIE-10 para compararlo: sin espacios, sin punto y en mayúsculas (C53.9 -> C539); vacío es nulo.""" + if texto is None: + return None + return texto.strip().upper().replace(".", "").replace(" ", "") or None + + +def codigo_de_especialidad(texto, alias: Mapping[str, str], codigos: Collection[str]) -> str | None: + """La especialidad en el código de Core: el propio código o su alias, sin distinguir mayúsculas. + + Nulo si no viene o no se reconoce: quien la use la cuenta como sin dato. + """ + limpio = texto_limpio(texto) + if limpio is None: + return None + en_mayusculas = limpio.upper() + if en_mayusculas in codigos: + return en_mayusculas + return alias.get(en_mayusculas) diff --git a/webapi/orchestration/silver/views.py b/webapi/orchestration/silver/views.py new file mode 100644 index 0000000..36f81be --- /dev/null +++ b/webapi/orchestration/silver/views.py @@ -0,0 +1,72 @@ +"""La vista `v_persona`, la única que queda en la base de un proyecto (F6, ADR-MD-009). + +Es un `select` de SQLAlchemy; `CreateView` y `DropView`, de aquí, la escriben para +el motor (T-2 de v0.5.0). La crea la arista `vistas`, no la migración (B21). Aquí +solo se arma la DDL; no se ejecuta. + +Antes eran las de `sqlalchemy-utils`, pero importar ese paquete registra para toda +sesión de SQLAlchemy un `after_flush` (`sqlalchemy_utils.aggregates`) que recorre +todos los objetos de la sesión en cada flush. La carga a plata hace un flush por +procedimiento nuevo, así que la carga crecía con el cuadrado de los pacientes +(TEA, 1000 pacientes: 25 s con él, 9 s sin él). + +Las vistas por tipo (`v__actual`, las de rol y las de cada proyecto) +se borraron con sus tablas en las migraciones de F6. +""" + +from sqlalchemy import Select, column, select, table +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.schema import DDLElement +from sqlalchemy.sql.expression import Executable + +from core.indicadores.comunes import PersonaBase + + +def ddl_de_vistas(persona: type = PersonaBase) -> list[Executable]: + """La DDL que crea o reemplaza `v_persona`, con las columnas de la persona del proyecto. No la ejecuta. + + La ejecuta Persistance (`VistasRepository.construir`) o, en una base de + prueba, `pruebas.construir_vistas`. + """ + # `persona` no tiene versiones: su vista es la tabla, para que un + # indicador lea solo vistas (B18, I-K23). + return reemplazar_vista("v_persona", select(*_columnas("persona", persona))) + + +def _columnas(nombre: str, modelo: type) -> list: + """Las columnas de `modelo`, leídas de la tabla o vista `nombre`.""" + return list(table(nombre, *(column(campo) for campo in modelo.model_fields)).c) + + +class CreateView(DDLElement): + """`CREATE VIEW nombre AS `, con los valores escritos en la consulta.""" + + def __init__(self, nombre: str, consulta: Select) -> None: + self.nombre, self.consulta = nombre, consulta + + +class DropView(DDLElement): + """`DROP VIEW IF EXISTS nombre`, sin CASCADE: SQLite no lo acepta (I-K100).""" + + def __init__(self, nombre: str) -> None: + self.nombre = nombre + + +@compiles(CreateView) +def _crear(elemento: CreateView, compilador, **_) -> str: + nombre = compilador.dialect.identifier_preparer.quote(elemento.nombre) + return f"CREATE VIEW {nombre} AS {compilador.sql_compiler.process(elemento.consulta, literal_binds=True)}" + + +@compiles(DropView) +def _borrar(elemento: DropView, compilador, **_) -> str: + return f"DROP VIEW IF EXISTS {compilador.dialect.identifier_preparer.quote(elemento.nombre)}" + + +def borrar_vista(nombre: str) -> DropView: + return DropView(nombre) + + +def reemplazar_vista(nombre: str, consulta: Select) -> list[Executable]: + """La DDL que crea la vista `nombre` con esa consulta; si ya existe, la reemplaza.""" + return [borrar_vista(nombre), CreateView(nombre, consulta)] diff --git a/webapi/orchestration/tables/__init__.py b/webapi/orchestration/tables/__init__.py new file mode 100644 index 0000000..fd15b32 --- /dev/null +++ b/webapi/orchestration/tables/__init__.py @@ -0,0 +1,87 @@ +"""Las tablas de un proyecto, juntas, para pasarlas al código común. + +El código común (carga, registro, cálculo, contratos) no importa clases +de tabla: recibe las del proyecto en un `TablasKit`. Así cada proyecto +puede tener sus propias clases, aunque las columnas sean las mismas, y +CaCu y CaMa corren en el mismo proceso sin un "proyecto activo". + +Cada proyecto declara la suya en `/tablas.py` como `TABLAS`. +""" + +from collections.abc import Callable +from dataclasses import dataclass +from importlib import import_module + +from sqlmodel import SQLModel + +PROJECTS = ("cacu", "cama") + + +@dataclass(frozen=True) +class TablasKit: + """Las tablas de un proyecto: el registro, el oro y la plata genérica (una sola plata, ADR-MD-009).""" + + Persona: type[SQLModel] + PeriodoObservacion: type[SQLModel] + Carga: type[SQLModel] + DefParametro: type[SQLModel] + DimPeriodo: type[SQLModel] + DimFecha: type[SQLModel] + DimGrupoEdad: type[SQLModel] + MeasureReport: type[SQLModel] + # Los catálogos de la plata (F1): estudio -> resultado -> valor, de `core/catalogos/.toml`. + CatEstudio: type[SQLModel] + CatResultado: type[SQLModel] + CatValor: type[SQLModel] + # La plata de dos tablas (F5, ADR-MD-007). + Procedimiento: type[SQLModel] + Observacion: type[SQLModel] + # El oro por unidad y su catálogo (§6f, MD-19): opcionales para que un registro de prueba no los necesite. + CatMeasure: type[SQLModel] | None = None + CatMeasureResultado: type[SQLModel] | None = None + CatMeasureValor: type[SQLModel] | None = None + CatMeasureGrupo: type[SQLModel] | None = None + CatEstrato: type[SQLModel] | None = None + CatEstratoValor: type[SQLModel] | None = None + CatMeasureEstrato: type[SQLModel] | None = None + MeasureReportUnidad: type[SQLModel] | None = None + MeasureReportUnidadEstrato: type[SQLModel] | None = None + # De una fila de `paciente` de staging, las columnas que este proyecto agrega a su `persona`. + persona_propias: Callable[[object], dict] = lambda paciente: {} + + def comunes(self) -> list[type[SQLModel]]: + return [ + self.Persona, + self.PeriodoObservacion, + self.Carga, + self.DefParametro, + self.DimPeriodo, + self.DimFecha, + self.DimGrupoEdad, + self.MeasureReport, + self.CatEstudio, + self.CatResultado, + self.CatValor, + self.Procedimiento, + self.Observacion, + ] + + def publicacion(self) -> list[type[SQLModel]]: + """Las tablas de §6f (MD-19) que el proyecto declara, en orden de llaves foráneas.""" + return [m for m in (self.CatMeasure, self.CatMeasureResultado, self.CatMeasureValor, self.CatMeasureGrupo, self.CatEstrato, self.CatEstratoValor, self.CatMeasureEstrato, self.MeasureReportUnidad, self.MeasureReportUnidadEstrato) if m is not None] + + def catalogo_de_publicacion(self) -> list[type[SQLModel]]: + """Las siete tablas `cat_*` de §6f, padres antes que hijos (lo que sincroniza la arista `definiciones`).""" + return [m for m in (self.CatEstrato, self.CatEstratoValor, self.CatMeasure, self.CatMeasureResultado, + self.CatMeasureValor, self.CatMeasureGrupo, self.CatMeasureEstrato) if m is not None] + + def todas(self) -> list[type[SQLModel]]: + """Todo lo que la base del proyecto lleva del kit (sin staging ni cohortes).""" + return [*self.comunes(), *self.publicacion()] + + +def tablas_de(proyecto: str) -> TablasKit: + """El `TablasKit` del proyecto, de `/tablas.py`.""" + if proyecto not in PROJECTS: + raise KeyError(f"Proyecto desconocido: {proyecto!r}.") + return import_module(f"webapi.orchestration.tables.{proyecto}").TABLAS diff --git a/webapi/orchestration/tables/cacu.py b/webapi/orchestration/tables/cacu.py new file mode 100644 index 0000000..8b9801a --- /dev/null +++ b/webapi/orchestration/tables/cacu.py @@ -0,0 +1,77 @@ +"""Las tablas de CaCu: viven en `Core`, en el registro del dominio (ADR-004). + +`TABLAS` es lo que el código común recibe para trabajar con este proyecto. +""" + +from core.cacu.indicadores.models import ( + CatMeasure, + CatMeasureResultado, + CatMeasureValor, + CatMeasureGrupo, + CatEstrato, + CatEstratoValor, + CatMeasureEstrato, + MeasureReportUnidad, + MeasureReportUnidadEstrato, + CatEstudio, + CatResultado, + CatValor, + Observacion, + Procedimiento, + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, + Carga, + DefParametro, + DimFecha, + DimGrupoEdad, + DimPeriodo, + MeasureReport, + PeriodoObservacion, + Persona, +) + +from webapi.orchestration.silver.persons import de_derechohabiente +from core.indicadores.cohortes import TablasCohorte +from webapi.orchestration.tables import TablasKit + +__all__ = ["TABLAS", "COHORTES"] + +TABLAS = TablasKit( + Persona=Persona, + PeriodoObservacion=PeriodoObservacion, + Carga=Carga, + DefParametro=DefParametro, + DimPeriodo=DimPeriodo, + DimFecha=DimFecha, + DimGrupoEdad=DimGrupoEdad, + MeasureReport=MeasureReport, + CatEstudio=CatEstudio, + CatResultado=CatResultado, + CatValor=CatValor, + Procedimiento=Procedimiento, + Observacion=Observacion, + CatMeasure=CatMeasure, + CatMeasureResultado=CatMeasureResultado, + CatMeasureValor=CatMeasureValor, + CatMeasureGrupo=CatMeasureGrupo, + CatEstrato=CatEstrato, + CatEstratoValor=CatEstratoValor, + CatMeasureEstrato=CatMeasureEstrato, + MeasureReportUnidad=MeasureReportUnidad, + MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, + persona_propias=de_derechohabiente, +) + +# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003). +COHORTES = TablasCohorte( + CohorteArmado=CohorteArmado, + CohorteMiembro=CohorteMiembro, + CohorteExclusion=CohorteExclusion, + CohorteVariable=CohorteVariable, + EvaluacionRiesgoLote=EvaluacionRiesgoLote, + EvaluacionRiesgo=EvaluacionRiesgo, +) diff --git a/webapi/orchestration/tables/cama.py b/webapi/orchestration/tables/cama.py new file mode 100644 index 0000000..c1a7b5f --- /dev/null +++ b/webapi/orchestration/tables/cama.py @@ -0,0 +1,77 @@ +"""Las tablas de CaMa: viven en `Core`, en el registro del dominio (ADR-004). + +`TABLAS` es lo que el código común recibe para trabajar con este proyecto. +""" + +from core.cama.indicadores.models import ( + CatMeasure, + CatMeasureResultado, + CatMeasureValor, + CatMeasureGrupo, + CatEstrato, + CatEstratoValor, + CatMeasureEstrato, + MeasureReportUnidad, + MeasureReportUnidadEstrato, + CatEstudio, + CatResultado, + CatValor, + Observacion, + Procedimiento, + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, + Carga, + DefParametro, + DimFecha, + DimGrupoEdad, + DimPeriodo, + MeasureReport, + PeriodoObservacion, + Persona, +) + +from webapi.orchestration.silver.persons import de_derechohabiente +from core.indicadores.cohortes import TablasCohorte +from webapi.orchestration.tables import TablasKit + +__all__ = ["TABLAS", "COHORTES"] + +TABLAS = TablasKit( + Persona=Persona, + PeriodoObservacion=PeriodoObservacion, + Carga=Carga, + DefParametro=DefParametro, + DimPeriodo=DimPeriodo, + DimFecha=DimFecha, + DimGrupoEdad=DimGrupoEdad, + MeasureReport=MeasureReport, + CatEstudio=CatEstudio, + CatResultado=CatResultado, + CatValor=CatValor, + Procedimiento=Procedimiento, + Observacion=Observacion, + CatMeasure=CatMeasure, + CatMeasureResultado=CatMeasureResultado, + CatMeasureValor=CatMeasureValor, + CatMeasureGrupo=CatMeasureGrupo, + CatEstrato=CatEstrato, + CatEstratoValor=CatEstratoValor, + CatMeasureEstrato=CatMeasureEstrato, + MeasureReportUnidad=MeasureReportUnidad, + MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, + persona_propias=de_derechohabiente, +) + +# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003; MD-12). +COHORTES = TablasCohorte( + CohorteArmado=CohorteArmado, + CohorteMiembro=CohorteMiembro, + CohorteExclusion=CohorteExclusion, + CohorteVariable=CohorteVariable, + EvaluacionRiesgoLote=EvaluacionRiesgoLote, + EvaluacionRiesgo=EvaluacionRiesgo, +) -- 2.53.0 From c430a5bd1110f0fb40db358c6b5878dfce8cdbc8 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 04/24] Every stratum value an answer writes is in the stratum-value catalog --- tests/test_metrics_on_request.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py index ee03ccc..2b7ba59 100644 --- a/tests/test_metrics_on_request.py +++ b/tests/test_metrics_on_request.py @@ -158,6 +158,19 @@ def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7 assert without(composition_cells(result), STATUS) == expected["published"], period_id +def test_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7): + """Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't + enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the + stratum values the catalog lacks.""" + for d in (eu13, eu7): + ask(base, d, "2025-S1") + with base.motor.connect() as connection: + written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar() + broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all() + assert written > 0 + assert broken == [] + + def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7): """Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing.""" -- 2.53.0 From a0407e41d6e5ad71818a5471fe2a6b745eb67e7e Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 12 Nov 2026 15:21:25 -0600 Subject: [PATCH 05/24] TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary --- pyproject.toml | 1 + tests/conftest.py | 2 +- tests/staging/tea.py | 139 +++++++ tests/test_fhir_measures.py | 60 +++ tests/test_fhir_tea.py | 223 +++++++++++ tests/test_imports_endpoints.py | 26 +- tests/test_imports_pdf_endpoints.py | 8 +- tests/test_new_sources.py | 95 ++--- tests/test_orquestacion_ciclo.py | 2 +- tests/test_orquestacion_oro.py | 7 +- tests/test_orquestacion_pasos.py | 2 +- tests/test_orquestacion_plata.py | 1 + tests/test_orquestacion_regla_repositorios.py | 2 +- tests/test_schemas.py | 19 +- tests/test_schemas_registry.py | 23 +- tests/test_source_ids.py | 28 +- tests/test_tea_measures.py | 245 ++++++++++++ uv.lock | 32 +- webapi/__init__.py | 10 +- webapi/compositions.py | 4 + webapi/durations.py | 12 +- webapi/fhir/__init__.py | 360 ++++++++++++++++++ webapi/fhir/common.py | 93 +++++ webapi/fhir/measures.py | 194 ++++++++++ webapi/fhir/tea.py | 352 +++++++++++++++++ webapi/fhir/tea_eeg.toml | 53 +++ webapi/fhir/terminology.py | 74 ++++ webapi/imports/connectors/edf.py | 55 +-- webapi/imports/schemas/coercion.py | 10 +- webapi/imports/schemas/registry.py | 100 ++--- webapi/imports/schemas/tea/ados2.py | 55 +++ .../tea/antecedentes_maternos_gestacion.py | 55 --- webapi/imports/schemas/tea/eeg.py | 26 ++ webapi/imports/schemas/tea/eeg_estudio.py | 69 ---- webapi/imports/schemas/tea/eeg_metrica.py | 16 + .../schemas/tea/eeg_metrica_electrodo.py | 12 + webapi/imports/schemas/tea/eeg_segmento.py | 21 - .../schemas/tea/evaluacion_neuropediatrica.py | 27 ++ .../schemas/tea/evaluacion_psicologica.py | 86 ----- .../schemas/tea/instrumento_aplicado.py | 13 - webapi/imports/schemas/tea/mchat.py | 13 + webapi/imports/schemas/tea/nota_medica.py | 46 --- webapi/imports/schemas/tea/ordenes_estudio.py | 26 +- webapi/imports/schemas/tea/pacientes.py | 18 +- webapi/imports/schemas/tea/parto_neonatal.py | 50 --- .../tea/potenciales_evocados_auditivos.py | 26 -- webapi/metrics.py | 199 +++++++++- webapi/orchestration/__main__.py | 2 +- .../orchestration/reference/parametros.toml | 151 +------- webapi/orchestration/semantic_layer.py | 14 +- webapi/orchestration/silver/procedures.py | 43 ++- webapi/orchestration/silver/tea.py | 120 ++++++ webapi/orchestration/tables/__init__.py | 2 +- webapi/orchestration/tables/tea.py | 75 ++++ webapi/recomputation.py | 2 +- 55 files changed, 2609 insertions(+), 790 deletions(-) create mode 100644 tests/staging/tea.py create mode 100644 tests/test_fhir_measures.py create mode 100644 tests/test_fhir_tea.py create mode 100644 tests/test_tea_measures.py create mode 100644 webapi/fhir/__init__.py create mode 100644 webapi/fhir/common.py create mode 100644 webapi/fhir/measures.py create mode 100644 webapi/fhir/tea.py create mode 100644 webapi/fhir/tea_eeg.toml create mode 100644 webapi/fhir/terminology.py create mode 100644 webapi/imports/schemas/tea/ados2.py delete mode 100644 webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py create mode 100644 webapi/imports/schemas/tea/eeg.py delete mode 100644 webapi/imports/schemas/tea/eeg_estudio.py create mode 100644 webapi/imports/schemas/tea/eeg_metrica.py create mode 100644 webapi/imports/schemas/tea/eeg_metrica_electrodo.py delete mode 100644 webapi/imports/schemas/tea/eeg_segmento.py create mode 100644 webapi/imports/schemas/tea/evaluacion_neuropediatrica.py delete mode 100644 webapi/imports/schemas/tea/evaluacion_psicologica.py delete mode 100644 webapi/imports/schemas/tea/instrumento_aplicado.py create mode 100644 webapi/imports/schemas/tea/mchat.py delete mode 100644 webapi/imports/schemas/tea/nota_medica.py delete mode 100644 webapi/imports/schemas/tea/parto_neonatal.py delete mode 100644 webapi/imports/schemas/tea/potenciales_evocados_auditivos.py create mode 100644 webapi/orchestration/silver/tea.py create mode 100644 webapi/orchestration/tables/tea.py diff --git a/pyproject.toml b/pyproject.toml index 7a4b5c3..3738009 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,7 @@ packages = ["webapi"] [dependency-groups] dev = [ + "fhir-resources>=8", "pytest>=8.0.0", "reportlab>=4.0", ] diff --git a/tests/conftest.py b/tests/conftest.py index 340f023..114fb37 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -67,7 +67,7 @@ def base_de(proyecto: str, carpeta, datos=None) -> Base: return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor) -@pytest.fixture(params=["cacu", "cama"]) +@pytest.fixture(params=["cacu", "cama", "tea"]) def proyecto(request): return request.param diff --git a/tests/staging/tea.py b/tests/staging/tea.py new file mode 100644 index 0000000..8bb82ce --- /dev/null +++ b/tests/staging/tea.py @@ -0,0 +1,139 @@ +"""TEA's synthetic staging, written by hand. Never real data. + +Seven children screened in 2025, each one exercising a rule of the screening's chain (M-CHAT, psychology note +with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first M-CHAT, in completed months: + +- 1, H-T01, 19 months (16 to 23): the whole chain. M-CHAT 10 Jan, ADOS-2 5 Feb, F84.0 note 12 Mar, a bad EEG + 2 Apr, a good EEG 20 May with a slow posterior rhythm, then a second good EEG 1 Sep that changes nothing. Leaves + after May. Its EEG has an order. +- 2, H-T02, 26 months (24 to 29): M-CHAT 20 Jan, ADOS-2 1 Mar, a note with F84 without subcode 10 Apr (not a + confirmation), no EEG: stays at neuropediatrics. +- 3, H-T03, 35 months (30 to 36): M-CHAT 14 Feb (a second one 10 Jun doesn't count), ADOS-2 28 Feb, nothing else: + stays at psychology. +- 4, H-T04, 39 months: out of the cohort, never counted. +- 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in + order, so it stays at M-CHAT. +- 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG + step is dated by the note, so it reaches EEG on 2 Jun and leaves after June. +- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else. + +Every EEG's quality criteria are written as its analysis would; a bad EEG has one criterion out of its threshold. + +Test support: writes in the session it's given, never in the domain's database. +""" + +from datetime import date + +from core.tea.models import ( + Ados2, + Eeg, + EegMetrica, + EegMetricaElectrodo, + EvaluacionNeuropediatrica, + Mchat, + OrdenesEstudio, + Pacientes, +) +from sqlmodel import Session + +# (pac_id, pac_id_hospital, birth date) +PACIENTES = ( + (1, "H-T01", date(2023, 6, 1)), + (2, "H-T02", date(2022, 11, 15)), + (3, "H-T03", date(2022, 3, 1)), + (4, "H-T04", date(2021, 12, 1)), + (5, "H-T05", date(2023, 9, 1)), + (6, "H-T06", date(2023, 1, 10)), + (7, "H-T07", None), +) + +# (pac_id, date, score) +MCHATS = ( + (1, date(2025, 1, 10), 12), + (2, date(2025, 1, 20), 9), + (3, date(2025, 2, 14), 15), + (3, date(2025, 6, 10), 4), + (4, date(2025, 3, 3), 11), + (5, date(2025, 6, 15), 8), + (6, date(2025, 4, 5), 14), + (7, date(2025, 5, 1), 7), +) + +# (pac_id, date, module, CSS, classification) +ADOS2 = ( + (1, date(2025, 2, 5), "MODULO_1", 7, "AUTISMO"), + (2, date(2025, 3, 1), "Toddler", 4, "espectro autista"), + (3, date(2025, 2, 28), "MODULO_2", 2, "NO_TEA"), + (6, date(2025, 4, 20), "MODULO_1", 8, "AUTISMO"), +) + +# (pac_id, date, ICD-10 as the hospital writes it) +NOTAS = ( + (1, date(2025, 3, 12), "F84.0"), + (2, date(2025, 4, 10), "F84"), + (5, date(2025, 7, 1), "f84.0"), + (6, date(2025, 6, 2), "F84.0"), +) + +GOOD = {"amplitud": 0, "alta_frecuencia": 1, "correlacion": 0, "sin_senal": 0, "linea": 3.5} +BAD = {**GOOD, "sin_senal": 5} + +# (eeg id, pac_id, date, laboratory id, criteria, with sleep) +EEGS = ( + ("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0), + ("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1), + ("eeg-1c", 1, date(2025, 9, 1), "LAB-1C", GOOD, 1), + ("eeg-5", 5, date(2025, 7, 20), "LAB-5", GOOD, 0), + ("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1), +) + +# (metric id, eeg id, code, value): a null value can't be evaluated. +METRICAS = ( + ("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2), + ("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0), + ("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4), + ("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0), + ("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5), + ("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None), + ("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6), +) + +# (electrode value id, metric id, electrode, z-score) +ELECTRODOS = ( + ("mel-1", "met-1b-rp", "O1", -2.8), + ("mel-2", "met-1b-rp", "O2", -2.4), + ("mel-3", "met-1b-rp", "Pz", -1.1), +) + +# The EEG of child 1 that completes the chain hangs from an order. +ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),) +ORDEN_DE = {"eeg-1b": "ord-1b"} + +# What the load gives (`test_orquestacion_plata`). +PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS) + + +def insertar(sesion: Session) -> None: + """Writes the children, their orders and their studies.""" + sesion.add_all(Pacientes(pac_id=p, pac_id_hospital=h, pac_fecha_nacimiento=n) for p, h, n in PACIENTES) + sesion.add_all(OrdenesEstudio(ord_id=i, ord_pac_id=p, ord_id_hospital=h, ord_tipo_estudio=t, ord_fecha=f) + for i, p, h, t, f in ORDENES) + sesion.add_all(Mchat(mch_id=f"mch-{k}", mch_pac_id=p, mch_fecha=f, mch_puntaje=s) + for k, (p, f, s) in enumerate(MCHATS, 1)) + for k, (p, f, modulo, css, clasificacion) in enumerate(ADOS2, 1): + items = {f"ado_sa_b{n}": n % 3 for n in range(1, 6)} | {"ado_rrb_d1": 2, "ado_rrb_d2": 1} + sesion.add(Ados2(ado_id=f"ado-{k}", ado_pac_id=p, ado_fecha=f, ado_modulo=modulo, ado_css=css, + ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items)) + sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c) + for k, (p, f, c) in enumerate(NOTAS, 1)) + for i, p, f, lab, criterios, sueno in EEGS: + sesion.add(Eeg( + eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i), + eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0, + eeg_canales_amplitud=criterios["amplitud"], eeg_canales_alta_frecuencia=criterios["alta_frecuencia"], + eeg_canales_correlacion=criterios["correlacion"], eeg_canales_sin_senal=criterios["sin_senal"], + eeg_ruido_linea_db=criterios["linea"], + )) + sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v) for i, e, c, v in METRICAS) + sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v) + for i, m, e, v in ELECTRODOS) diff --git a/tests/test_fhir_measures.py b/tests/test_fhir_measures.py new file mode 100644 index 0000000..f842703 --- /dev/null +++ b/tests/test_fhir_measures.py @@ -0,0 +1,60 @@ +"""What this module covers: the FHIR R4 measure routes of `webapi.fhir` for CaCu and CaMa: every `Measure` of the +domain and one `MeasureReport` of each, checked against FHIR's models (`fhir.resources`, R4B), and the patient routes +absent outside TEA. + +Fixtures: `domain_client`, a Flask app with only the domain's FHIR blueprint over its fixture database loaded through +the cycle up to `event_models` (`conftest.base_de`); needs `DBT_MANIFEST`. +""" + +import os +from pathlib import Path + +import pytest +from fhir.resources.R4B import get_fhir_model_class +from flask import Flask + +from conftest import base_de +from webapi.fhir import fhir_blueprint + +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@pytest.fixture(scope="module", params=["cacu", "cama"]) +def domain_client(request, tmp_path_factory): + manifest = os.environ.get("DBT_MANIFEST") + if not manifest: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + base = base_de(request.param, tmp_path_factory.mktemp(request.param)) + base.run(*UNTIL_MODELS, allow_undecided=True) + app = Flask(__name__) + app.register_blueprint(fhir_blueprint(request.param, base.dominio, Path(manifest), with_patients=True), + url_prefix=f"/{request.param}/fhir") + yield request.param, app.test_client() + base.motor.dispose() + + +def valid(resource: dict) -> dict: + get_fhir_model_class(resource["resourceType"]).model_validate(resource) + for item in resource.get("entry", ()): + get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"]) + return resource + + +def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client): + """Pins down: each Measure of the domain, and its report for 2025-S1, validate as FHIR R4 resources, compositions + with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape.""" + domain, client = domain_client + measures = valid(client.get(f"/{domain}/fhir/Measure").get_json()) + assert measures["total"] == 7 + for item in measures["entry"]: + response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1") + assert response.status_code in (200, 409), response.get_json() + valid(response.get_json()) + + +def test_the_patient_routes_are_tea_s_only(domain_client): + """Pins down: `EpisodeOfCare` exists only on TEA's endpoint; elsewhere it's an OperationOutcome 404. Fails if + the patient routes register for another domain.""" + domain, client = domain_client + response = client.get(f"/{domain}/fhir/EpisodeOfCare") + assert response.status_code == 404 and valid(response.get_json())["resourceType"] == "OperationOutcome" diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py new file mode 100644 index 0000000..03b8789 --- /dev/null +++ b/tests/test_fhir_tea.py @@ -0,0 +1,223 @@ +"""What this module covers: TEA's FHIR R4 endpoint (`/tea/fhir/`): the capability statement, the measures as +`Measure` and their answers as `MeasureReport` (one period and several), the follow-up list as `EpisodeOfCare` with +its filters, paging and includes, the EEG summary and the patient summary; and that the alterations stay hidden until +validated. Every resource is checked against FHIR's models (`fhir.resources`, R4B, which keeps R4's shape for these +resources). + +Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes exist) over TEA's fixture database +(`staging.tea`) loaded through the cycle up to `event_models`; needs `DBT_MANIFEST`. `validated`, the switch that +shows the alterations (`TEA_ALTERACIONES_VALIDADAS`). +""" + +import os + +import pytest +from fhir.resources.R4B import get_fhir_model_class + +from conftest import base_de + +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@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") + mp = pytest.MonkeyPatch() + mp.setenv("DEV_REVISION", "pruebas") + mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) + base = base_de("tea", tmp_path_factory.mktemp("tea_fhir")) + base.run(*UNTIL_MODELS, allow_undecided=True) + from webapi import create_app + + app = create_app() + app.config.update(TESTING=True) + with app.test_client() as test_client: + yield test_client + base.motor.dispose() + mp.undo() + + +@pytest.fixture +def validated(monkeypatch): + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + + +def valid(resource: dict) -> dict: + """The resource, after checking it and every resource in it against FHIR's model of its type.""" + get_fhir_model_class(resource["resourceType"]).model_validate(resource) + for item in resource.get("entry", ()): + get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"]) + return resource + + +def get(client, url: str, status: int = 200) -> dict: + response = client.get(url) + assert response.status_code == status, response.get_json() + assert response.mimetype == "application/fhir+json" + return valid(response.get_json()) + + +def resources(bundle: dict, kind: str | None = None, mode: str | None = None) -> list[dict]: + return [e["resource"] for e in bundle["entry"] if (kind is None or e["resource"]["resourceType"] == kind) + and (mode is None or e.get("search", {}).get("mode") == mode)] + + +def test_the_capability_statement_lists_the_measures_and_the_patient_routes(client): + """Pins down: `metadata` is a valid CapabilityStatement naming Measure with `evaluate-measure` and, in DEV, + EpisodeOfCare with its search parameters. Fails if a route drops out of it.""" + body = get(client, "/tea/fhir/metadata") + kinds = {r["type"]: r for r in body["rest"][0]["resource"]} + assert {"Measure", "MeasureReport", "EpisodeOfCare", "Patient"} <= set(kinds) + assert {p["name"] for p in kinds["EpisodeOfCare"]["searchParam"]} >= {"date", "etapa", "fecha-etapa", "alteracion"} + + +def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monkeypatch): + """Pins down: the Measure list has the nine measures without alterations; M30 shows only with the switch on. + Fails if M30 leaks before the domain expert validates the references, or the switch stops showing it.""" + ids = {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} + assert len(ids) == 9 and "M30-resultado-eeg" not in ids + assert get(client, "/tea/fhir/Measure/M30_resultado_eeg", 404)["resourceType"] == "OperationOutcome" + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} + + +def test_a_measure_carries_what_the_page_needs(client): + """Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category + labels. Fails if the page's catalog fields stop reaching the Measure.""" + m28 = get(client, "/tea/fhir/Measure/M28_casos_por_estado") + assert m28["url"] == "https://isssteleon.org/fhir/Measure/M28-casos-por-estado" + assert m28["title"] == "Casos por estatus" and m28["scoring"]["coding"][0]["code"] == "cohort" + assert {e["extension"][0]["valueCode"] for e in m28["extension"] if e["url"].endswith("/categoria")} == { + "SOLO_MCHAT", "PSICOLOGIA", "NEUROPEDIATRIA", "EEG"} + m24 = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico") + assert m24["group"][0]["stratifier"][0]["code"]["coding"][0]["code"] == "grupo_edad" + assert "denominator-exclusion" in {p["code"]["coding"][0]["code"] for p in m24["group"][0]["population"]} + + +def test_evaluate_measure_answers_one_period_as_a_measure_report(client): + """Pins down: `$evaluate-measure` with periodStart and periodEnd answers that period of `dim_periodo`: M28's first + semester of 2025 counts six children by stage, as a cohort whose stages are a stratifier. Fails if the period + lookup, the canonical or the C2 shape changes.""" + report = get(client, "/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure" + "?periodStart=2025-01-01&periodEnd=2025-06-30") + assert report["measure"].startswith("https://isssteleon.org/fhir/Measure/M28-casos-por-estado|") + (group,) = report["group"] + assert group["population"][0]["count"] == 6 + stages = {s["value"]["coding"][0]["code"]: s["population"][0]["count"] for s in group["stratifier"][0]["stratum"]} + assert stages == {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2} + + +def test_a_proportion_reports_its_exclusion_and_its_strata_with_codings(client): + """Pins down: M24's report has the exclusion count (child 2's note without F84.0) and each age group as a coded + stratum. Fails if `denominator-exclusion` or the stratum codings drop out.""" + report = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico/$evaluate-measure?periodo=2025-04") + counts = {p["code"]["coding"][0]["code"]: p["count"] for p in report["group"][0]["population"]} + assert counts == {"denominator": 3, "numerator": 1, "denominator-exclusion": 1} + values = {s["value"]["coding"][0]["code"] for s in report["group"][0]["stratifier"][0]["stratum"]} + assert {"16_23", "30_36"} <= values + + +def test_the_measure_report_search_answers_several_periods_with_paging(client): + """Pins down: `MeasureReport?measure=…&tipo-periodo=mes&period=ge…&period=le…` gives one report per month, and + `_count` pages them with a `next` link. Fails if the search stops selecting `dim_periodo` by type and dates.""" + url = ("/tea/fhir/MeasureReport?measure=https://isssteleon.org/fhir/Measure/M26-dias-mchat-ados2" + "&tipo-periodo=mes&period=ge2025-01-01&period=le2025-03-31") + body = get(client, url) + assert body["total"] == 3 and [r["period"]["start"] for r in resources(body)] == [ + "2025-01-01", "2025-02-01", "2025-03-01"] + paged = get(client, url + "&_count=2") + assert len(paged["entry"]) == 2 and any(link["relation"] == "next" for link in paged["link"]) + + +def test_the_follow_up_list_is_each_child_s_episode_at_the_cut_off(client): + """Pins down: `EpisodeOfCare?date=le…` gives each child who entered by the cut-off, at its stage then: at 31 May, + children 1, 2, 3, 6 and 7 (child 5 enters in June), child 1 finished on its good EEG. A window from 1 June leaves + child 1 out. Fails if the episode's status, stage or window drift from the measures' rules.""" + may = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-05-31")) + assert len(may) == 5 + assert sorted(e["status"] for e in may) == ["active"] * 4 + ["finished"] + assert all(e["meta"]["tag"][0]["code"] == "simulado" for e in may) + june = resources(get(client, "/tea/fhir/EpisodeOfCare?date=ge2025-06-01&date=le2025-06-30")) + assert len(june) == 5 and "finished" in {e["status"] for e in june} + + +@pytest.mark.parametrize(("query", "n"), [ + ("etapa=PSICOLOGIA", 1), ("grupo-edad=24_29", 2), ("mchat=ge12", 3), ("css=ge4", 3), + ("fecha-etapa=ge2025-06-01&fecha-etapa=le2025-06-30", 2), ("status=finished", 2), ("resultado-eeg=sin-eeg-valido", 3), +]) +def test_the_follow_up_filters(client, query, n): + """Pins down each search parameter at the year's end, over the six children who entered by then: child 3 at + psychology; children 2 and 6 in 24 to 29 months (finished episodes still list); M-CHAT of 12 or more for children + 1, 3 and 6; CSS of 4 or more for 1, 2 and 6; a stage dated in June for child 5 (its M-CHAT; its EEG doesn't count) + and child 6 (EEG on 2 June); children 1 and 6 finished; children 2, 3 and 7 without a valid EEG. Fails if a filter + stops reading its column.""" + assert get(client, f"/tea/fhir/EpisodeOfCare?date=le2025-12-31&{query}")["total"] == n + + +def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client): + """Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT, + confirmed diagnosis and study EEG as a DiagnosticReport with its quality observations; no metric observation while + the alterations are hidden. Fails if an included resource drops out or the alterations leak.""" + body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*") + included = resources(body, mode="include") + kinds = {r["resourceType"] for r in included} + assert {"Patient", "CarePlan", "Observation", "Condition", "DiagnosticReport", "Procedure"} <= kinds + assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient") + reports = [r for r in included if r["resourceType"] == "DiagnosticReport"] + assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"} + assert all(len(r["result"]) == 5 for r in reports) + + +def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch): + """Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's + slow posterior rhythm). Fails if the filter leaks alterations before validation.""" + assert get(client, "/tea/fhir/EpisodeOfCare?alteracion=ritmo_posterior", 403)["resourceType"] == "OperationOutcome" + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&alteracion=ritmo_posterior")["total"] == 1 + + +def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(client, monkeypatch): + """Pins down `$resumen-eeg`: children 1, 5 and 6 with a valid EEG, 2, 3 and 7 without; with the alterations + validated, child 1 abnormal (posterior rhythm), 5 and 6 normal. Fails if the summary counts bad EEGs as valid or + shows the split before validation.""" + def counts(body): + return {p["name"]: p.get("valueInteger") for p in body["parameter"] if "valueInteger" in p} + + hidden = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31") + assert counts(hidden) == {"con_eeg_valido": 3, "sin_eeg_valido": 3} + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + shown = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31") + assert counts(shown) == {"con_eeg_valido": 3, "sin_eeg_valido": 3, "normales": 2, "anormales": 1} + + +def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch): + """Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first + good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated, + the metrics against their reference and the electrode values. Fails if the summary takes another EEG or shows the + alterations before validation.""" + episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished")) + (child_1,) = episodes + path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea" + bundle = get(client, path) + assert bundle["type"] == "collection" + (report,) = resources(bundle, "DiagnosticReport") + assert report["effectiveDateTime"] == "2025-05-20" and report["conclusionCode"][0]["coding"][0]["code"] == "BUENO" + ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-")) + codes = {c["code"]["coding"][0]["code"] for c in ados2["component"]} + assert {"ados2.modulo", "ados2.css", "SA", "RRB", "ados2.sa_b1"} <= codes + assert not any("tea-eeg-metrica" in o["code"]["coding"][0]["system"] for o in resources(bundle, "Observation")) + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + shown = get(client, path) + metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")] + rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-")) + assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5 + electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-")) + assert [c["code"]["coding"][0]["code"] for c in electrodes["component"]] == ["O1", "O2", "Pz"] + + +def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client): + """Pins down: errors are OperationOutcomes with the HTTP status: an unknown pseudonym (404), an unknown search + parameter (400). Fails if an error goes back to `{"error": …}`.""" + assert get(client, "/tea/fhir/Patient/P-NADIE/$resumen-tea", 404)["issue"][0]["code"] == "not-found" + assert get(client, "/tea/fhir/EpisodeOfCare?color=azul", 400)["issue"][0]["code"] == "invalid" diff --git a/tests/test_imports_endpoints.py b/tests/test_imports_endpoints.py index 1ab9b57..b98b148 100644 --- a/tests/test_imports_endpoints.py +++ b/tests/test_imports_endpoints.py @@ -124,7 +124,8 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, def test_commit_rejects_a_batch_mixing_domains(client): cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente") - tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes") + tea_source = _json_source([{"pac_id_hospital": "T-MIX-1"}], target="tea.Pacientes", + column_mapping={"pac_id_hospital": "pac_id_hospital"}) response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"}) assert response.status_code == 400 @@ -159,20 +160,21 @@ def test_commit_on_conflict_reject_then_upsert(client): def test_commit_upsert_rejected_for_target_without_natural_key(client): source = _json_source( - [{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"} + [{"pac_id_hospital": "H-NO-KEY"}], target="cacu.BiometriaHematica", + column_mapping={"pac_id_hospital": "pac_id_hospital"}, ) response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}) assert response.status_code == 400 def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client): - mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"} - first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}], + mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento"} + first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-05-01"}], target="tea.Pacientes", column_mapping=mapping) body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json() assert body["results"][0]["created"] == 1 - again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}], + again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-06-01"}], target="tea.Pacientes", column_mapping=mapping) body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json() assert body["results"][0]["created"] == 0 @@ -180,20 +182,22 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client): [paciente] = client.get("/data/tea.Pacientes").get_json()["rows"] assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1" - assert paciente["pac_sexo"] == "M" + assert paciente["pac_fecha_nacimiento"] == "2023-06-01" -def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client): - """The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation. +def test_an_import_into_tea_queues_its_recomputation(client): + """Pins down: TEA's measures come from the cycle like CaCu's and CaMa's, so a TEA import saves its rows and + asks for a recomputation of TEA. - Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500. + Fails if TEA leaves the queue's domains (`DOMAINS` in `webapi.recomputation`). """ - source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes") + source = _json_source([{"pac_id_hospital": "T-RECALC"}], target="tea.Pacientes", + column_mapping={"pac_id_hospital": "pac_id_hospital"}) response = client.post("/imports/commit", json={"sources": [source]}) assert response.status_code == 200 body = response.get_json() assert body["results"][0]["created"] == 1 - assert body["indicadores_en_recalculo"] is False + assert body["indicadores_en_recalculo"] is True @pytest.fixture diff --git a/tests/test_imports_pdf_endpoints.py b/tests/test_imports_pdf_endpoints.py index 2df8d7a..8cb8072 100644 --- a/tests/test_imports_pdf_endpoints.py +++ b/tests/test_imports_pdf_endpoints.py @@ -2,7 +2,7 @@ - detect -> table/preview -> validate -> commit, for the ruled-table path, writing into `cacu.Paciente`. - detect -> page-image -> regions/extract -> validate -> commit, for the - OCR/region path, writing into `tea.Pacientes`. + OCR/region path, writing into `cacu.Paciente` as well. """ import base64 @@ -201,7 +201,7 @@ def test_pdf_page_image_missing_file_returns_400(client): # --------------------------------------------------------------------- # OCR/region path: detect -> page-image -> regions/extract -> validate -> -# commit (tea.Pacientes) +# commit (cacu.Paciente) # --------------------------------------------------------------------- @@ -241,7 +241,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): source = { "source_type": "pdf", - "target": "tea.Pacientes", + "target": "cacu.Paciente", "column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}, "payload": { "file_base64": base64.b64encode(pdf_bytes).decode(), @@ -261,7 +261,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): commit_body = commit_response.get_json() assert commit_body["ok"] is True result = commit_body["results"][0] - assert result["target"] == "tea.Pacientes" + assert result["target"] == "cacu.Paciente" assert result["created"] == 1 diff --git a/tests/test_new_sources.py b/tests/test_new_sources.py index 3fd3d62..f647c74 100644 --- a/tests/test_new_sources.py +++ b/tests/test_new_sources.py @@ -78,31 +78,35 @@ def test_unknown_engine_and_missing_host_are_rejected(client): # -- EEG ----------------------------------------------------------------------------- -def test_edf_preview_maps_onto_eeg_estudio(client): - data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"} +def test_edf_preview_maps_onto_eeg(client): + """Pins down: an EDF previews as one row with the study id, patient, date, channels and duration read from the + file, and its columns suggest the `eeg` fields. Fails if the connector stops reading the header or the column + matcher stops pairing them.""" + data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.Eeg"} body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json() [row] = body["sample_rows"] assert row["id_registro_laboratorio"] == "LAB-778" assert row["paciente"] == "EXP-0042" assert row["fecha_estudio"] == "2024-01-15" - assert row["edad_meses"] == 56.0 - assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3) - assert "3 canales a 128 Hz" in row["descripcion_senal"] + assert row["canales"] == 3 + assert row["duracion_min"] == pytest.approx(8 / 60, abs=0.05) suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]} assert suggested["estudio"] == "eeg_estudio" assert suggested["fecha_estudio"] == "eeg_fecha_estudio" - assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia" + assert suggested["canales"] == "eeg_canales" -def test_several_edf_files_load_into_eeg_estudio_with_the_file(client): +def test_several_edf_files_load_into_eeg_with_the_file(client): + """Pins down: several EDF files commit as one `eeg` row each, keyed by the lab's study id (or the file name), + with the file stored. Fails if the commit drops the file or the key.""" source = { "source_type": "edf", - "target": "tea.EegEstudio", + "target": "tea.Eeg", "column_mapping": { "id_registro_laboratorio": "eeg_id_registro_laboratorio", "fecha_estudio": "eeg_fecha_estudio", "duracion_min": "eeg_duracion_min", - "ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia", + "canales": "eeg_canales", "estudio": "eeg_estudio", }, "payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]}, @@ -110,19 +114,21 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client): result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0] assert result["created"] == 2, result - from persistance.tea import eeg_estudio_repository + from persistance.tea import eeg_repository - stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()} + stored = {row.eeg_id_registro_laboratorio: row for row in eeg_repository.list()} assert set(stored) == {"LAB-778", "b"} + assert stored["LAB-778"].eeg_canales == 3 assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0" assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15) -def test_eeg_estudio_rejects_a_file_mne_cannot_read(): +def test_eeg_rejects_a_file_mne_cannot_read(): + """Pins down: `eeg_estudio` only takes a file MNE can open. Fails if the schema stops validating the EDF.""" from webapi.imports.schemas.service import validate_rows - from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema + from webapi.imports.schemas.tea.eeg import EegImportSchema - result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}]) + result = validate_rows(EegImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}]) [row] = result.rejected assert row.errors[0].field == "eeg_estudio" @@ -228,73 +234,48 @@ def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client): EEG_REPORT = text_pdf( - [ - ["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024", - "Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"], - ["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."], - ], - image_on_page=2, + [["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024"]], ) # A second study id, distinct from LAB-778 (already used by an earlier test # against this module-scoped client/database), for the merge test below. EEG_REPORT_2 = text_pdf( - [ - ["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024", - "Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"], - ["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."], - ], + [["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024"]], ) -def test_eeg_report_scattered_across_pages_merges_into_one_record(client): - """The report's demographics are on page 1, its conclusion on page 2 — - non-contiguous fields the same way a multi-file upload would be, just - without the file boundary. Proves the extractor merges by the lab's own - study id, not by page adjacency.""" +def test_an_eeg_report_gives_its_study_id_and_date(client): + """Pins down: a report read with NLP lands on `eeg` by the lab's own study id, with the study date. Fails if + the extractor stops keying EEG records by `eeg_id_registro_laboratorio` or stops reading the date.""" body = client.post( "/imports/sources/document/extract", - json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"}, + json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.Eeg"}, ).get_json() assert body["key_field"] == "eeg_id_registro_laboratorio" [record] = body["records"] assert record["key"] == "LAB-778" - assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}] - assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO" assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15" - assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"] - assert [image["page_number"] for image in record["images"]] == [2] -def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client): - """The EDF connector computes signal fields from the file itself; the - report PDF (read with NLP, across two pages) carries the clinician's - interpretation. Different sources, same study — `eeg_id_registro_ - laboratorio` (the lab's own code, read from the EDF header by one side - and from the report text by the other) is what lets them land on one - `eeg_estudio` row instead of two half-populated ones.""" +def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_row(client): + """Pins down: the EDF and its report, two sources of the same study, land on one `eeg` row through the lab's + study id (read from the EDF header by one and from the report text by the other). Fails if + `merge_duplicates` stops matching them on `eeg_id_registro_laboratorio`.""" edf_source = { "source_type": "edf", - "target": "tea.EegEstudio", + "target": "tea.Eeg", "label": "estudio.edf", "column_mapping": { "id_registro_laboratorio": "eeg_id_registro_laboratorio", - "fecha_estudio": "eeg_fecha_estudio", "duracion_min": "eeg_duracion_min", - "ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia", "estudio": "eeg_estudio", }, "payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]}, } document_source = _document_source( [("reporte.pdf", EEG_REPORT_2)], - "tea.EegEstudio", - { - "eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", - "eeg_simetria": "eeg_simetria", - "eeg_conclusion_texto": "eeg_conclusion_texto", - "eeg_medico_interpreta": "eeg_medico_interpreta", - }, + "tea.Eeg", + {"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", "eeg_fecha_estudio": "eeg_fecha_estudio"}, ) body = client.post( "/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True} @@ -303,16 +284,14 @@ def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client): assert edf_result["created"] == 1, body assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again - from persistance.tea import eeg_estudio_repository + from persistance.tea import eeg_repository - [row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900") + [row] = eeg_repository.list(eeg_id_registro_laboratorio="LAB-900") # From the EDF file itself: assert row.eeg_duracion_min is not None assert row.eeg_estudio[:8].strip() == b"0" - # From the scanned report, on the very same row: - assert row.eeg_simetria == "SIMETRICO" - assert "sin eventos epileptiformes" in row.eeg_conclusion_texto - assert row.eeg_medico_interpreta == "Dra. Ruiz" + # From the report, on the very same row: + assert row.eeg_fecha_estudio == date(2024, 2, 20) def test_citologia_table_and_scanned_report_merge_on_the_order_number(client): diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 63cde16..480e5cc 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -27,7 +27,7 @@ CONSULTA = text(""" -@pytest.fixture(scope="module", params=["cacu", "cama"]) +@pytest.fixture(scope="module", params=["cacu", "cama", "tea"]) def bases(request, tmp_path_factory): proyecto = request.param carpeta = tmp_path_factory.mktemp(proyecto) diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 9da68bd..dee138d 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -84,10 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.run("definitions")["definitions"] - # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata. - assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto] + # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata; TEA: the age group and its + # ten measures. + assert resumen["definitions"] == {"cacu": 10, "cama": 7, "tea": 11}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain + assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 7, "tea": 10}[base.proyecto] assert base.run("definitions")["definitions"]["borradas"] == 0 diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index e8ded34..df737f4 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -23,7 +23,7 @@ def antes(deps: dict[str, set[str]], paso: str) -> set[str]: return previos -@pytest.mark.parametrize("proyecto", ["cacu", "cama"]) +@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto): deps = dependencias(proyecto) assert deps["migrate"] == set() diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 57d5940..ae67df9 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -26,6 +26,7 @@ from sqlmodel import select CAMBIO = { "cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"), "cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"), + "tea": ("mchat", "mch_puntaje", 19), } CORTE = date(2025, 12, 31) diff --git a/tests/test_orquestacion_regla_repositorios.py b/tests/test_orquestacion_regla_repositorios.py index 048a27d..0c82bb5 100644 --- a/tests/test_orquestacion_regla_repositorios.py +++ b/tests/test_orquestacion_regla_repositorios.py @@ -23,7 +23,7 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo): assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos" -@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)]) +@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)]) def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes): repos = repositories_of(proyecto) assert (repos.gold.cohorts is not None) == con_cohortes diff --git a/tests/test_schemas.py b/tests/test_schemas.py index d02f5fb..1881fe9 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -48,14 +48,15 @@ def test_tea_pacientes_schema_is_fully_optional(): assert schema.pac_id_hospital is None -def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict(): - schema = PacientesImportSchema(pac_sexo="f") - assert schema.pac_sexo == "F" +def test_tea_neuropediatrics_note_takes_icd10_with_or_without_the_dot(): + """Pins down: the note's ICD-10 is upper-cased and accepted with or without its dot; anything else is + rejected. Fails if the pattern of `neu_cie_codigo` changes.""" + from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema as Nota - -def test_tea_pacientes_schema_coerces_parentesco(): - schema = PacientesImportSchema(pac_parentesco="hijo") - assert schema.pac_parentesco == "HIJO" + assert Nota(neu_cie_codigo=" f84.0 ").neu_cie_codigo == "F84.0" + assert Nota(neu_cie_codigo="F840").neu_cie_codigo == "F840" + with pytest.raises(ValidationError): + Nota(neu_cie_codigo="autismo") def test_classify_error_missing(): @@ -243,5 +244,5 @@ def test_catalog_aliases_for_values_the_indicator_kit_uses(): cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO") assert cito.cit_celulas_escamosas == "NORMAL" assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA" - assert TeaOrdenes(ord_tipo_estudio="POTENCIALES_EVOCADOS").ord_tipo_estudio == "POTENCIALES_EVOCADOS_AUDITIVOS" - assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "EVALUACION_PSICOLOGICA_TEA" + assert TeaOrdenes(ord_tipo_estudio="electroencefalograma").ord_tipo_estudio == "EEG" + assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "ADOS2" diff --git a/tests/test_schemas_registry.py b/tests/test_schemas_registry.py index bdef2e5..fdccba4 100644 --- a/tests/test_schemas_registry.py +++ b/tests/test_schemas_registry.py @@ -5,7 +5,8 @@ from pydantic import ValidationError from webapi.imports.schemas.registry import ENTITY_REGISTRY from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema -from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema +from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema +from webapi.imports.schemas.tea.mchat import MchatImportSchema from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema @@ -48,11 +49,21 @@ def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio( assert schema.ord_tipo_estudio == "BIOPSIA_CHICA" -# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds -# a Catalog from the Enum alone, as in tea/pacientes.py. -def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict(): - schema = EegEstudioImportSchema(eeg_simetria="simetrico") - assert schema.eeg_simetria == "SIMETRICO" +def test_tea_ados2_coerces_module_and_classification_aliases(): + """Pins down: the ADOS-2's module comes from the bare enum and its classification takes the old spelling + `NO_TEA`. Fails if either catalog stops normalizing case or aliases.""" + schema = Ados2ImportSchema(ado_modulo="modulo_1", ado_clasificacion="no_tea") + assert (schema.ado_modulo, schema.ado_clasificacion) == ("MODULO_1", "NO_ESPECTRO") + + +@pytest.mark.parametrize(("schema", "field", "value"), [ + (MchatImportSchema, "mch_puntaje", 21), (Ados2ImportSchema, "ado_css", 0), (Ados2ImportSchema, "ado_sa_b1", 4), +]) +def test_tea_scores_out_of_their_range_are_rejected(schema, field, value): + """Pins down: an M-CHAT score above 20, a CSS below 1 and an ADOS-2 item above 3 are validation errors. Fails if + a bound of `Bounded` is dropped from the schemas.""" + with pytest.raises(ValidationError): + schema(**{field: value}) # CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS). diff --git a/tests/test_source_ids.py b/tests/test_source_ids.py index e8f2f2e..98c1556 100644 --- a/tests/test_source_ids.py +++ b/tests/test_source_ids.py @@ -76,31 +76,31 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client): sources = [ _json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"), _json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"), - _json([{"psi_id": "psi-1", "psi_ord_id": "ord-1", "psi_pac_id": 1}], "tea.EvaluacionPsicologica"), - _json([{"ins_psi_id": "psi-1", "ins_instrumento": "ADOS-2"}], "tea.InstrumentoAplicado"), - _json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.EegEstudio"), - _json([{"seg_eeg_id": "eeg-1", "seg_duracion_s": 30}], "tea.EegSegmento"), + _json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"), + _json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"), + _json([{"met_id": "met-1", "met_eeg_id": "eeg-1", "met_codigo": "RITMO_POSTERIOR", "met_valor": 5.5}], "tea.EegMetrica"), + _json([{"mel_met_id": "met-1", "mel_electrodo": "O1", "mel_valor": -1.2}], "tea.EegMetricaElectrodo"), ] body = tea_client.post("/imports/commit", json={"sources": sources}).get_json() assert all(r["rejected"] == 0 for r in body["results"]), body from persistance.tea import ( - eeg_estudio_repository, - eeg_segmento_repository, - evaluacion_psicologica_repository, - instrumento_aplicado_repository, + ados2_repository, + eeg_metrica_electrodo_repository, + eeg_metrica_repository, + eeg_repository, ) - assert eeg_estudio_repository.get(eeg_segmento_repository.list()[0].seg_eeg_id).eeg_id_registro_laboratorio == "L-1" - evaluacion = evaluacion_psicologica_repository.get(instrumento_aplicado_repository.list()[0].ins_psi_id) - assert evaluacion.psi_ord_id == "ord-1" + metrica = eeg_metrica_repository.get(eeg_metrica_electrodo_repository.list()[0].mel_met_id) + assert eeg_repository.get(metrica.met_eeg_id).eeg_id_registro_laboratorio == "L-1" + assert ados2_repository.get("ado-1").ado_ord_id == "ord-1" def test_tea_rows_without_a_source_id_get_one(tea_client): - eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio") + eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.Eeg") assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1 - from persistance.tea import eeg_estudio_repository + from persistance.tea import eeg_repository - [fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"] + [fila] = [e for e in eeg_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"] assert len(fila.eeg_id) == 36 diff --git a/tests/test_tea_measures.py b/tests/test_tea_measures.py new file mode 100644 index 0000000..6139462 --- /dev/null +++ b/tests/test_tea_measures.py @@ -0,0 +1,245 @@ +"""What this module covers: TEA's ten measures answered on request from dbt's semantic layer, on hand-written +expectations for the synthetic children of `staging.tea`, period by period: who each period counts (the children in +the screening during it, at their stage at its end, leaving after the period of their good EEG), the day counts, the +EEGs by quality and the alterations of each child's first good EEG. + +Fixtures: `base`, TEA's fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's +`manifest.json` (`DBT_MANIFEST`; skipped without it). The expectations are worked out by hand from the children's +dates in `staging/tea.py`; each test says which child makes each number. +""" + +import os +from dataclasses import replace +from datetime import date, datetime, timezone +from pathlib import Path + +import pytest +from sqlalchemy import text +from sqlmodel import select + +import staging.tea as fixture +from conftest import base_de +from core.tea.models import Eeg, EegMetrica +from webapi.compositions import answer_composition, composition_definitions +from webapi.durations import answer_duration, duration_definitions +from webapi.metrics import Question, answer, measure_definitions + +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@pytest.fixture(scope="module") +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture(scope="module") +def base(tmp_path_factory, manifest): + """The seven children of `staging.tea`, loaded once, with dbt's TEA views created.""" + base = base_de("tea", tmp_path_factory.mktemp("tea")) + base.run(*UNTIL_MODELS, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, allow_undecided=True)) + base.motor.dispose() + + +def repositories(base) -> dict: + d = base.dominio + return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, + "history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True} + + +def composition(base, manifest, measure_id, period, **question): + url = f"tea/{measure_id}" + result = answer_composition("tea", composition_definitions(manifest)[url], Question(url, period, **question), + **repositories(base)) + return {k: v for k, v in result.categories.items() if v} + + +def proportion(base, manifest, measure_id, period, **question): + url = f"tea/{measure_id}" + return answer("tea", measure_definitions(manifest)[url], Question(url, period, **question), **repositories(base)) + + +def duration(base, manifest, measure_id, period): + url = f"tea/{measure_id}" + return answer_duration("tea", duration_definitions(manifest)[url], Question(url, period), **repositories(base)) + + +STAGES = { + "2025-01": {"SOLO_MCHAT": 2}, + "2025-02": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2}, + "2025-03": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 1}, + "2025-04": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}, + "2025-05": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 1, "EEG": 1}, + "2025-06": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 1}, + "2025-07": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1}, + "2025-12": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1}, + "2025-S1": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2}, + "2025-S2": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1}, +} + + +@pytest.mark.parametrize("period", sorted(STAGES)) +def test_m28_counts_every_child_in_the_screening_at_its_stage_at_the_period_s_end(base, manifest, period): + """Pins down M28: a period counts every cohort child who entered by its end and hadn't finished before its start, + at the furthest step reached by its end, whether or not anything of theirs happened in it. Child 1 is at + psychology in February and March's stage moves with its note; it reaches EEG in May and is gone from June. Child 2 + stays at neuropediatrics all year; child 5 stays at M-CHAT (no ADOS-2); child 6 reaches EEG on its note's day, + 2 June; child 4 (39 months) never counts; child 7 (no birth date) counts from May. + + Fails if the population goes back to the children with a fact in the period, if a child stops leaving after the + period of its good EEG, or if a step stops needing the previous one.""" + assert composition(base, manifest, "M28_casos_por_estado", period) == STAGES[period] + + +def test_m28_an_event_cut_off_leaves_out_what_came_after_it(base, manifest): + """Pins down: facts dated after the event cut-off don't count. With a cut-off of 10 May, child 1's good EEG of + 20 May isn't there, so May counts it at neuropediatrics. Fails if the status rows stop applying the cut-off.""" + assert composition(base, manifest, "M28_casos_por_estado", "2025-05", event_cutoff=date(2025, 5, 10)) == { + "SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2} + + +RESULTS = { + "2025-01": {"EN_PROCESO": 2}, + "2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3}, + "2025-07": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3}, + "2025-S2": {"CONFIRMADO": 1, "EN_PROCESO": 2}, +} + + +@pytest.mark.parametrize("period", sorted(RESULTS)) +def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period): + """Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's + note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note + confirms it in July even without the ADOS-2. Fails if F84 counts as a confirmation or a note without F84.0 counts + as in process.""" + assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period] + + +@pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [ + ("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 1, 3, 1), ("2025-S1", 2, 5, 1), +]) +def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator, + excluded): + """Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion + from April. Fails if the denominator takes the children without TEA or the exclusion stops being counted.""" + result = proportion(base, manifest, "M24_confirmacion_diagnostico", period) + assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded) + + +def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest): + """Pins down: the age group is the child's at its first M-CHAT, one per child, the page's windows. In March, child + 1 (19 months) is confirmed, child 2 (26) and child 3 (35) are in process. Fails if the stratum goes back to the age + at the period's start or loses a window.""" + result = proportion(base, manifest, "M24_confirmacion_diagnostico", "2025-03") + strata = {v: (c.numerator, c.denominator) for v, c in result.strata["grupo_edad"].items()} + assert strata == {"16_23": (1, 1), "24_29": (0, 1), "30_36": (0, 1)} + + +@pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [ + ("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 1, 1), + ("2025-S1", 2, 0, 2), ("2025-S2", 0, 1, 1), +]) +def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg, + without_eeg, confirmed): + """Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG + by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5, confirmed in July, + has a good EEG but no ADOS-2, so its chain never reaches it. Fails if the EEG is read beyond the period's end or + outside the chain.""" + m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period) + m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period) + assert (m21.numerator, m21.denominator) == (with_eeg, confirmed) + assert (m22.numerator, m22.denominator) == (without_eeg, confirmed) + + +@pytest.mark.parametrize(("measure_id", "period", "initial", "n", "median"), [ + ("M26_dias_mchat_ados2", "2025-01", 2, 0, None), + ("M26_dias_mchat_ados2", "2025-02", 3, 2, 20.0), + ("M26_dias_mchat_ados2", "2025-03", 3, 3, 26.0), + ("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5), + ("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0), + ("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5), + ("M25_dias_mchat_diagnostico", "2025-S2", 4, 1, 16.0), +]) +def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period, + initial, n, median): + """Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval + ended by the period's end have days (repeated in each period that counts them), the rest count as without event. + In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of + 1 July gives 16 days in the second semester only. Fails if the value is read beyond the period's end or the + population goes back to the facts in the period.""" + result = duration(base, manifest, measure_id, period) + assert (result.initial, result.n, result.median) == (initial, n, median) + + +@pytest.mark.parametrize(("period", "expected"), [ + ("2025-04", {"MALO": 1}), ("2025-05", {"BUENO": 1}), ("2025-09", {"BUENO": 1}), + ("2025-S1", {"BUENO": 2, "MALO": 1}), ("2025-S2", {"BUENO": 2}), +]) +def test_m29_counts_the_period_s_eegs_good_or_bad(base, manifest, period, expected): + """Pins down M29: the EEGs of the cohort's children dated in the period, by exam, good or bad. Child 1's bad EEG of + April and its second good one of September count; so does child 5's, though its chain never reaches it. Fails if + M29 stops counting exams, or a bad EEG stops showing.""" + assert composition(base, manifest, "M29_calidad_eeg", period) == expected + + +@pytest.mark.parametrize(("period", "total", "ritmo_posterior"), [ + ("2025-05", (1, 1), (1, 1)), ("2025-06", (0, 1), (0, 1)), ("2025-S1", (1, 2), (1, 2)), ("2025-S2", (0, 1), (0, 1)), +]) +def test_m30_reads_the_alterations_of_each_child_s_first_good_eeg(base, manifest, period, total, ritmo_posterior): + """Pins down M30: of the children whose first good EEG falls in the period, those with an alteration in it, in + total and in one group per alteration. Child 1's EEG of 20 May has a slow posterior rhythm (3.2 Hz at 23 months, + against 4.5 to 7.0); its second good EEG of September doesn't count. Fails if a later EEG counts, or the groups + stop being answered one by one.""" + result = proportion(base, manifest, "M30_resultado_eeg", period) + assert (result.numerator, result.denominator) == total + assert (result.groups["ritmo_posterior"].numerator, result.groups["ritmo_posterior"].denominator) == ritmo_posterior + assert result.groups["husos_sueno_n2"].numerator == 0 + + +def test_m30_read_back_from_the_history_keeps_its_groups(base, manifest): + """Pins down: asking again reads the stored answer, groups included. Fails if a stored answer loses its groups or + counts every group's units in the total.""" + first = proportion(base, manifest, "M30_resultado_eeg", "2025-S1") + again = proportion(base, manifest, "M30_resultado_eeg", "2025-S1") + assert again.stored_before and (again.numerator, again.denominator) == (first.numerator, first.denominator) + assert again.groups == first.groups + + +def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest): + """Pins down: a step known after the knowledge cut-off doesn't move the child. Child 1's good EEG and its metrics + arrive in a second load; asked as of the first load, May still counts child 1 at neuropediatrics and it hasn't + left in June. Fails if the status rows stop applying the knowledge cut-off to the steps or to the exit.""" + def without_the_good_eeg(session): + fixture.insertar(session) + session.flush() + for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")): + for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")): + session.delete(row) + + base = base_de("tea", tmp_path, without_the_good_eeg) + try: + base.run(*UNTIL_MODELS, allow_undecided=True) + with base.motor.begin() as connection: + (first_load,) = connection.execute(text("select max(fin) from carga")).one() + known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc) + with base.staging() as session: + session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1, + eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0, + eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0, + eeg_ruido_linea_db=3.5)) + session.commit() + base.run("load", allow_undecided=True) + later = replace(base, ctx=replace(base.ctx, allow_undecided=True)) + assert composition(later, manifest, "M28_casos_por_estado", "2025-05", knowledge_cutoff=known) == { + "SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2} + assert composition(later, manifest, "M28_casos_por_estado", "2025-06", knowledge_cutoff=known)[ + "NEUROPEDIATRIA"] == 2 + assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1 + finally: + base.motor.dispose() diff --git a/uv.lock b/uv.lock index 1c55eb9..85cf813 100644 --- a/uv.lock +++ b/uv.lock @@ -1,15 +1,15 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version < '3.13' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version < '3.13' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.13' and sys_platform == 'win32'", + "python_full_version < '3.13' and sys_platform == 'emscripten'", "python_full_version < '3.13' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] @@ -768,6 +768,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/2a/101012d82931d9de3855384e1667e49c0e07a0048e3868f9fec1697293a9/fastapi-0.161.1-py3-none-any.whl", hash = "sha256:a1363080cf9aeedecd99f4e1a23669d7e77542227f6536f4d7bbd59f07ecaa94", size = 149049, upload-time = "2026-10-22T22:22:06.139Z" }, ] +[[package]] +name = "fhir-core" +version = "1.1.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f7/1b/0072a6ec7716df558bbcc134611df02d8ba22e286cbf64070fe6190f9d75/fhir_core-1.1.12.tar.gz", hash = "sha256:8f1674104ff575ff00dd2b4ff7ed6caf043d6d5a306990536e1b6ee2ccd06732", size = 40415, upload-time = "2026-10-18T20:20:47.011Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/22/4a118da089892195692b5e3519992708dc67fb84d49fddee5d9a1f3f43b4/fhir_core-1.1.12-py2.py3-none-any.whl", hash = "sha256:2ae218ed43b32705ce1c37150253942bd88350248a77f66e8ca2b6c3ed8263b2", size = 34264, upload-time = "2026-10-18T20:20:45.735Z" }, +] + +[[package]] +name = "fhir-resources" +version = "8.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fhir-core" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/06/331d78ad6db6903be6b912701c44b32af295279907b3a2e6ad6c2e2f97b1/fhir_resources-8.3.0.tar.gz", hash = "sha256:bdfd1c7bd1b89bfa269c1f435727771f6c632cd857e2848221713b3f8b9f46e8", size = 1617996, upload-time = "2026-07-03T15:23:54.01Z" } +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 = "flask" version = "3.1.3" @@ -3284,6 +3308,7 @@ sql-drivers = [ [package.dev-dependencies] dev = [ + { name = "fhir-resources" }, { name = "pytest" }, { name = "reportlab" }, ] @@ -3314,6 +3339,7 @@ provides-extras = ["sql-drivers"] [package.metadata.requires-dev] dev = [ + { name = "fhir-resources", specifier = ">=8" }, { name = "pytest", specifier = ">=8.0.0" }, { name = "reportlab", specifier = ">=4.0" }, ] diff --git a/webapi/__init__.py b/webapi/__init__.py index b217175..ca77ab5 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -78,11 +78,15 @@ def create_app() -> Flask: from importlib import import_module from pathlib import Path + from webapi.fhir import fhir_blueprint from webapi.kpis import kpis_blueprint - for domain in ("cacu", "cama"): - app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"), - Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}") + for domain in ("cacu", "cama", "tea"): + repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"]) + app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}") + # The same measures in FHIR R4, and TEA's patients only in DEV (simulated data). + app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=in_dev()), + url_prefix=f"/{domain}/fhir") # Patient-level follow-up list and individual risk: only in DEV, with simulated data. if in_dev(): from persistance.db import get_cacu_session diff --git a/webapi/compositions.py b/webapi/compositions.py index 91322b8..751ca0a 100644 --- a/webapi/compositions.py +++ b/webapi/compositions.py @@ -29,6 +29,7 @@ from webapi.metrics import ( MeasureQueries, Population, Question, + StatusAtEnd, Stratum, _population, _semantic_model_of, @@ -80,6 +81,8 @@ class CompositionDefinition: basis: str rules: dict[str, str] strata: tuple[Stratum, ...] + population: StatusAtEnd | None = None + meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) @property def measure_id(self) -> str: @@ -121,6 +124,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]: tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))), group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), + population=StatusAtEnd.of(meta.get("poblacion")), meta=meta, ) return definitions diff --git a/webapi/durations.py b/webapi/durations.py index 8c8ff95..b1d009b 100644 --- a/webapi/durations.py +++ b/webapi/durations.py @@ -6,7 +6,8 @@ cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`). -The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. +The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. With a population at +the period's end (`webapi.metrics.StatusAtEnd`), a unit's interval has a value only if it ended by the period's end. """ import dataclasses @@ -28,6 +29,7 @@ from webapi.metrics import ( MeasureQueries, Population, Question, + StatusAtEnd, _population, _semantic_model_of, key_of, @@ -90,6 +92,8 @@ class DurationDefinition: rules: dict[str, str] improvement_notation: str | None = None strata: tuple = () + population: StatusAtEnd | None = None + meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) @property def measure_id(self) -> str: @@ -127,7 +131,8 @@ def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]: rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"], int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None), group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), - improvement_notation=meta.get("improvement_notation"), + improvement_notation=meta.get("improvement_notation"), population=StatusAtEnd.of(meta.get("poblacion")), + meta=meta, ) return definitions @@ -145,6 +150,9 @@ class DurationQueries(MeasureQueries): o, q = self.d.observation, self.q conditions = [self._column(o.value).is_not(None)] conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at] + if self.status is not None: + # Counted at the period's end: the interval has to have ended by then. + conditions += [self._column(n) < self.events.c.periodo_fin for n in o.dated_at] if q.knowledge_cutoff is not None: conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at] return and_(*conditions) diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py new file mode 100644 index 0000000..c039626 --- /dev/null +++ b/webapi/fhir/__init__.py @@ -0,0 +1,360 @@ +"""A domain's FHIR R4 endpoint, `//fhir/`: its measures and, for TEA, its patients' screening. + + GET metadata CapabilityStatement + GET Measure, Measure/ the measures (dbt's definitions) + GET Measure//$evaluate-measure one period: periodStart and periodEnd, or `periodo` + GET MeasureReport?measure=&periodo=|period= several periods (one report each), with `tipo-periodo` + POST Measure/$recalcular queues the domain's recomputation + GET CodeSystem, CodeSystem/, ValueSet/ the project's code systems + GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only) + GET Patient//$resumen-tea TEA's patient summary (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`. +""" + +from collections.abc import Callable +from datetime import date, datetime, timedelta, timezone +from pathlib import Path + +from flask import Blueprint, request +from werkzeug.exceptions import HTTPException + +from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data +from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url +from webapi.fhir.terminology import code_systems, metric_value_set +from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of +from webapi.metrics import Question, UndecidedRule + +TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion") + + +def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: bool = False, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: + """The blueprint of a domain, to register with `url_prefix="//fhir"`. `repositories` is the domain's + `persistance.` module; `with_patients` adds TEA's patient routes (only in DEV).""" + blueprint = Blueprint(f"{project}_fhir", __name__) + titles = labels(manifest) + patients = with_patients and project == "tea" + + def definitions() -> dict: + """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" + every = {fhir_id(d): d for d in definitions_of(project, manifest).values()} + if project == "tea": + from webapi.fhir.tea import alterations_validated + + if not alterations_validated(): + every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")} + return every + + def definition_of(measure_id: str): + return definitions().get(measure_id.replace("_", "-")) + + def measure(definition) -> dict: + title, description = titles.get(definition.metric, (definition.measure_id, "")) + return measure_resource(definition, title, description) + + @blueprint.app_errorhandler(HTTPException) + def http_error(error: HTTPException): + """Under `//fhir/`, an error is an `OperationOutcome`, also for a route that doesn't exist there; + elsewhere, Flask's own answer.""" + if "/fhir/" not in request.path and not request.path.endswith("/fhir"): + return error + code = {404: "not-found", 405: "not-supported"}.get(error.code, "exception") + return outcome(error.code, code, error.description or error.name) + + @blueprint.get("/metadata") + def capability_statement(): + resources = [ + {"type": "Measure", "interaction": [{"code": "read"}, {"code": "search-type"}], + "operation": [{"name": "evaluate-measure", "definition": "http://hl7.org/fhir/OperationDefinition/Measure-evaluate-measure"}, + {"name": "recalcular", "definition": canonical("OperationDefinition/recalcular")}]}, + {"type": "MeasureReport", "interaction": [{"code": "search-type"}], + "searchParam": [{"name": n, "type": t} for n, t in (("measure", "reference"), ("period", "date"), + ("periodo", "token"), ("tipo-periodo", "token"))]}, + {"type": "CodeSystem", "interaction": [{"code": "read"}, {"code": "search-type"}]}, + ] + if patients: + resources += [ + {"type": "EpisodeOfCare", "interaction": [{"code": "search-type"}], + "searchParam": [{"name": n, "definition": canonical(f"SearchParameter/episode-{n}"), + "type": "date" if n in ("date", "fecha-etapa") else + "number" if n in ("mchat", "css") else "token"} for n in TEA_SEARCH], + "searchInclude": ["*"], + "operation": [{"name": "resumen-eeg", "definition": canonical("OperationDefinition/resumen-eeg")}]}, + {"type": "Patient", "operation": [{"name": "resumen-tea", + "definition": canonical("OperationDefinition/resumen-tea")}]}, + {"type": "ValueSet", "interaction": [{"code": "read"}]}, + ] + 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}, + "rest": [{"mode": "server", "resource": resources}]}) + + @blueprint.get("/Measure") + def measures(): + found = [measure(d) for _, d in sorted(definitions().items())] + if url := request.args.get("url"): + found = [m for m in found if m["url"] == url] + count, offset = page() + return fhir(searchset([entry(m) for m in found[offset:offset + count]], len(found), count, offset)) + + @blueprint.get("/Measure/") + def read_measure(measure_id: str): + definition = definition_of(measure_id) + if definition is None: + return outcome(404, "not-found", f"no hay un indicador {measure_id!r}") + return fhir(measure(definition)) + + def ask(definition, period, event_cutoff, knowledge_cutoff): + question = Question(definition.url, period.periodo_id, event_cutoff, knowledge_cutoff) + answer_of, _ = ANSWERS[scoring_of(definition)] + result = answer_of(project, definition, question, parameters=repositories.def_parametro_repository, + periods=repositories.dim_periodo_repository, history=repositories.history_repository, + queries=repositories.dbt_query_repository) + return measure_report(definition, question, result, period, now()) + + def cutoffs(): + return (_date(request.args.get("corte_evento")), + _datetime(request.args.get("corte_conocimiento")) or _last_load(repositories)) + + @blueprint.get("/Measure//$evaluate-measure") + def evaluate_measure(measure_id: str): + definition = definition_of(measure_id) + if definition is None: + return outcome(404, "not-found", f"no hay un indicador {measure_id!r}") + try: + event_cutoff, knowledge_cutoff = cutoffs() + period = _period_asked(repositories) + except ValueError as error: + return outcome(400, "invalid", str(error)) + except LookupError as error: + return outcome(404, "not-found", str(error)) + try: + return fhir(ask(definition, period, event_cutoff, knowledge_cutoff)) + except UndecidedRule as error: + return outcome(409, "business-rule", str(error)) + + @blueprint.get("/MeasureReport") + def measure_reports(): + asked = request.args.get("measure", "") + by_url = {measure_url(d): d for d in definitions().values()} + definition = by_url.get(asked.split("|")[0]) or definition_of(asked) + if definition is None: + return outcome(400, "required", "falta `measure` (el canónico o el id de un indicador)") + try: + event_cutoff, knowledge_cutoff = cutoffs() + periods = _periods_searched(repositories) + count, offset = page() + except ValueError as error: + return outcome(400, "invalid", str(error)) + except LookupError as error: + return outcome(404, "not-found", str(error)) + try: + reports = [ask(definition, p, event_cutoff, knowledge_cutoff) for p in periods[offset:offset + count]] + except UndecidedRule as error: + return outcome(409, "business-rule", str(error)) + return fhir(searchset([entry(r) for r in reports], len(periods), count, offset)) + + @blueprint.post("/Measure/$recalcular") + def recompute(): + from webapi.recomputation import RecomputationQueue + + RecomputationQueue().request_run(project) + return outcome(202, "informational", f"se pidió recalcular los indicadores de {project}", severity="information") + + @blueprint.get("/CodeSystem") + def code_system_search(): + systems = list(code_systems(project).values()) + return fhir(searchset([entry(s) for s in systems], len(systems), len(systems) or 1, 0)) + + @blueprint.get("/CodeSystem/") + def read_code_system(system_id: str): + system = code_systems(project).get(system_id) + return fhir(system) if system else outcome(404, "not-found", f"no hay un sistema de códigos {system_id!r}") + + if patients: + _patient_routes(blueprint, repositories, now) + return blueprint + + +def _period_asked(repositories): + """The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive).""" + if periodo := request.args.get("periodo"): + period = repositories.dim_periodo_repository.get(periodo) + if period is None: + raise LookupError(f"no hay un periodo {periodo!r}") + return period + start, end = request.args.get("periodStart"), request.args.get("periodEnd") + if not (start and end): + raise ValueError("falta el periodo: `periodStart` y `periodEnd`, o `periodo`") + start, end = date.fromisoformat(start), date.fromisoformat(end) + for period in repositories.dim_periodo_repository.list(limit=10000, inicio=start): + if period.fin - timedelta(days=1) == end: + return period + raise LookupError(f"no hay un periodo de {start} a {end}") + + +def _periods_searched(repositories) -> list: + """The periods of a `MeasureReport` search: `periodo` (comma-separated ids), or the periods of `tipo-periodo` + within `period=ge…` and `period=le…`.""" + if ids := [p for p in request.args.get("periodo", "").split(",") if p]: + periods = [repositories.dim_periodo_repository.get(i) for i in ids] + if missing := [i for i, p in zip(ids, periods) if p is None]: + raise LookupError(f"no hay un periodo {missing[0]!r}") + return periods + kind = request.args.get("tipo-periodo") + if not kind: + raise ValueError("falta `periodo` o `tipo-periodo` con `period`") + low, high = date.min, date.max + for value in request.args.getlist("period"): + if value.startswith("ge"): + low = date.fromisoformat(value[2:]) + elif value.startswith("le"): + high = date.fromisoformat(value[2:]) + else: + raise ValueError(f"`period` admite ge y le: {value!r}") + found = repositories.dim_periodo_repository.list(limit=10000, tipo=kind) + return sorted((p for p in found if p.inicio >= low and p.fin - timedelta(days=1) <= high), key=lambda p: p.inicio) + + +def _bound(name: str) -> tuple[float | None, float | None]: + """A number search parameter's bounds: `mchat=ge8&mchat=le20`, or one exact value.""" + low = high = None + for value in request.args.getlist(name): + if value.startswith("ge"): + low = float(value[2:]) + elif value.startswith("le"): + high = float(value[2:]) + else: + low = high = float(value) + return low, high + + +def _dates(name: str) -> tuple[date | None, date | None]: + low = high = None + for value in request.args.getlist(name): + if value.startswith("ge"): + low = date.fromisoformat(value[2:]) + elif value.startswith("le"): + high = date.fromisoformat(value[2:]) + else: + low = high = date.fromisoformat(value) + return low, high + + +def _patient_routes(blueprint: Blueprint, repositories, now) -> None: + from webapi.fhir import tea + + queries = repositories.dbt_query_repository + + def matching(): + """The episodes the search's parameters select, at its cut-off (`date=le…`, by default today).""" + unknown = [k for k in request.args if not k.startswith("_") and k not in TEA_SEARCH] + if unknown: + raise ValueError(f"parámetro de búsqueda no admitido: {unknown[0]!r}") + if request.args.get("alteracion") and not tea.alterations_validated(): + raise PermissionError("las alteraciones del EEG no se muestran hasta validar sus referencias") + since, cutoff = _dates("date") + cutoff = cutoff or now().date() + stage_from, stage_to = _dates("fecha-etapa") + mchat, css = _bound("mchat"), _bound("css") + + def within(value, bounds): + low, high = bounds + return value is not None and (low is None or value >= low) and (high is None or value <= high) + + found = [] + for e in tea.episodes(queries, cutoff): + stage = e.stage + if since is not None and e.finished and stage[1] < since: + continue + if (status := request.args.get("status")) and status != ("finished" if e.finished else "active"): + continue + if (etapa := request.args.get("etapa")) and (stage is None or stage[0] not in etapa.split(",")): + continue + if (stage_from or stage_to) and (stage is None or not within(stage[1].toordinal(), ( + stage_from and stage_from.toordinal(), stage_to and stage_to.toordinal()))): + continue + if (group := request.args.get("grupo-edad")) and e.child["grupo_edad"] not in group.split(","): + continue + if request.args.getlist("mchat") and not within(e.child["mchat"], mchat): + continue + if request.args.getlist("css") and not within(e.child["css_ados2"], css): + continue + if result := request.args.get("resultado-eeg"): + shown = e.eeg_result if tea.alterations_validated() else ( + "sin-eeg-valido" if e.eeg_result == "sin-eeg-valido" else "valido") + if shown not in result.split(","): + continue + if (alteration := request.args.get("alteracion")) and alteration not in e.alterations(): + continue + found.append(e) + return sorted(found, key=lambda e: e.pseudonym) + + @blueprint.get("/EpisodeOfCare") + def episodes_of_care(): + try: + found = matching() + count, offset = page() + except ValueError as error: + return tea_outcome(400, "invalid", error) + except PermissionError as error: + return tea_outcome(403, "forbidden", error) + simulated = simulated_data() + shown = found[offset:offset + count] + entries = [entry(tea.episode_of_care(e, simulated)) for e in shown] + if request.args.get("_include"): + entries += [entry(r, "include") for e in shown for r in _included(tea, queries, e, simulated)] + return fhir(searchset(entries, len(found), count, offset)) + + @blueprint.get("/EpisodeOfCare/$resumen-eeg") + def eeg_summary(): + try: + found = matching() + except ValueError as error: + return tea_outcome(400, "invalid", error) + except PermissionError as error: + return tea_outcome(403, "forbidden", error) + valid = [e for e in found if e.eeg_result != "sin-eeg-valido"] + parameters = [{"name": "con_eeg_valido", "valueInteger": len(valid)}, + {"name": "sin_eeg_valido", "valueInteger": len(found) - len(valid)}] + if tea.alterations_validated(): + by_alteration: dict[str, int] = {} + for e in valid: + for code in e.alterations(): + by_alteration[code] = by_alteration.get(code, 0) + 1 + parameters += [{"name": "normales", "valueInteger": sum(e.eeg_result == "normal" for e in valid)}, + {"name": "anormales", "valueInteger": sum(e.eeg_result == "anormal" for e in valid)}, + *({"name": "por_alteracion", "part": [{"name": "alteracion", "valueCode": code}, + {"name": "pacientes", "valueInteger": n}]} + for code, n in sorted(by_alteration.items()))] + return fhir({"resourceType": "Parameters", "parameter": parameters}) + + @blueprint.get("/Patient//$resumen-tea") + def patient_summary(pseudonym: str): + pac_id = tea.patient_of(queries, pseudonym) + if pac_id is None: + return outcome(404, "not-found", f"no hay un paciente {pseudonym!r}") + return fhir(tea.patient_summary(queries, pac_id, now().date(), simulated_data())) + + @blueprint.get("/ValueSet/tea-alteracion") + def alteration_types(): + return fhir(metric_value_set()) + + +def tea_outcome(status: int, code: str, error: Exception): + return outcome(status, code, str(error)) + + +def _included(tea, queries, e, simulated: bool) -> list[dict]: + """What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG.""" + from sqlalchemy import select + + persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"])) + resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated), + tea.care_plan(e, simulated)] + resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r] + if (eeg := e.study_eeg()) is not None: + resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated) + return resources diff --git a/webapi/fhir/common.py b/webapi/fhir/common.py new file mode 100644 index 0000000..4b01062 --- /dev/null +++ b/webapi/fhir/common.py @@ -0,0 +1,93 @@ +"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with +their paging links, the simulated-data tag and the project's canonical URLs.""" + +import json +import os +from urllib.parse import urlencode + +from flask import Response, request + +FHIR_VERSION = "4.0.1" +MEDIA_TYPE = "application/fhir+json" +BASE = "https://isssteleon.org/fhir" +CODE_SYSTEM = f"{BASE}/CodeSystem" +VALUE_SET = f"{BASE}/ValueSet" +STRUCTURE = f"{BASE}/StructureDefinition" +SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"} +MAX_COUNT = 200 +DEFAULT_COUNT = 50 + + +def fhir(resource: dict, status: int = 200) -> Response: + """A resource as the answer, in FHIR's JSON media type.""" + return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE) + + +def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response: + """An error as an `OperationOutcome` (`code` from FHIR's issue-type), with the HTTP status it goes with.""" + return fhir({"resourceType": "OperationOutcome", + "issue": [{"severity": severity, "code": code, "diagnostics": diagnostics}]}, status) + + +def canonical(path: str) -> str: + """The absolute canonical of a project resource: `Measure/`, `CodeSystem/`…""" + return f"{BASE}/{path}" + + +def coding(system: str, code: str, display: str | None = None) -> dict: + return {"system": system, "code": code, **({"display": display} if display else {})} + + +def concept(system: str, code: str, display: str | None = None, text: str | None = None) -> dict: + return {"coding": [coding(system, code, display)], **({"text": text} if text else {})} + + +def tagged(resource: dict, simulated: bool) -> dict: + """The resource with the simulated-data tag in its `meta`, when its data are simulated.""" + if simulated: + resource.setdefault("meta", {}).setdefault("tag", []).append(SIMULATED) + return resource + + +def simulated_data() -> bool: + """Patient data are simulated in the DEV deployment (`DEV_REVISION`), the only one that serves them.""" + return bool(os.environ.get("DEV_REVISION")) + + +def page() -> tuple[int, int]: + """`_count` (at most `MAX_COUNT`) and `_offset` of the search. `ValueError` if one isn't a number.""" + count = int(request.args.get("_count", DEFAULT_COUNT)) + offset = int(request.args.get("_offset", 0)) + if count < 0 or offset < 0: + raise ValueError("`_count` y `_offset` no pueden ser negativos") + return min(count, MAX_COUNT), offset + + +def searchset(entries: list[dict], total: int, count: int, offset: int) -> dict: + """A `searchset` Bundle with the page's entries, the total and the `self`, `next` and `previous` links.""" + def link(relation: str, at: int) -> dict: + args = [(k, v) for k, v in request.args.items(multi=True) if k not in ("_count", "_offset")] + return {"relation": relation, "url": f"{request.base_url}?{urlencode([*args, ('_count', count), ('_offset', at)])}"} + + links = [link("self", offset)] + if offset + count < total: + links.append(link("next", offset + count)) + if offset > 0: + links.append(link("previous", max(0, offset - count))) + return {"resourceType": "Bundle", "type": "searchset", "total": total, "link": links, "entry": entries} + + +def fhir_base() -> str: + """This request's FHIR endpoint, `…//fhir/`: what a `fullUrl` is relative to.""" + url = request.base_url + return url[:url.index("/fhir/") + len("/fhir/")] if "/fhir/" in url else url.rstrip("/") + "/" + + +def entry(resource: dict, mode: str | None = "match") -> dict: + """A Bundle entry: its `fullUrl` when the resource has an id, and its search mode in a searchset.""" + item = {"resource": resource} + if "id" in resource: + item = {"fullUrl": f"{fhir_base()}{resource['resourceType']}/{resource['id']}", **item} + if mode: + item["search"] = {"mode": mode} + return item diff --git a/webapi/fhir/measures.py b/webapi/fhir/measures.py new file mode 100644 index 0000000..0cd6e11 --- /dev/null +++ b/webapi/fhir/measures.py @@ -0,0 +1,194 @@ +"""A domain's measures as FHIR R4 `Measure` resources, and their answers as `MeasureReport`s. + +The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from +each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as +extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier +has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds +its category as a `component`. A duration reports the units without a value as their own population. +""" + +import json +from datetime import datetime, timedelta +from pathlib import Path + +from webapi.compositions import CompositionAnswer, CompositionDefinition +from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition +from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept +from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts + +SCORING_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-scoring" +IMPROVEMENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation" +GROUP_SYSTEM = f"{CODE_SYSTEM}/grupo-medida" +STRATIFIER_SYSTEM = f"{CODE_SYSTEM}/estratificador" +EXCLUDED = "measure-population-exclusion" +FIGURES = f"{STRUCTURE}/figuras" +PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo" +CATEGORY_LABEL = f"{STRUCTURE}/categoria" +CONTRACT = f"{STRUCTURE}/contrato" +REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion" +POPULATION_LABELS = { + "initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador", + "denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor", + EXCLUDED: "Unidades sin valor", +} + + +def scoring(definition) -> str: + """The FHIR scoring: a composition is a `cohort` (its categories are a stratifier).""" + if isinstance(definition, CompositionDefinition): + return "cohort" + return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion" + + +def labels(manifest: Path) -> dict[str, tuple[str, str]]: + """Each metric's (title, description) in the manifest: `meta.titulo` when the label had to differ.""" + metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() + return {m["name"]: (m["config"].get("meta", {}).get("titulo") or m["label"], (m.get("description") or "").strip()) + for m in metrics} + + +def fhir_id(definition) -> str: + """The measure's id as FHIR allows one (letters, digits, `-` and `.`): `M21_diagnosticados_con_eeg` -> + `M21-diagnosticados-con-eeg`.""" + return definition.measure_id.replace("_", "-") + + +def measure_url(definition) -> str: + return canonical(f"Measure/{fhir_id(definition)}") + + +def _populations(definition) -> list[dict]: + """Each population with the dbt metric that counts it as its criteria.""" + if scoring(definition) == "proportion": + metrics = {**{c: definition.denominator.metric for c in definition.denominator.codes}, + **{c: definition.numerator.metric for c in definition.numerator.codes}, + **({c: definition.exclusion.metric for c in definition.exclusion.codes} + if getattr(definition, "exclusion", None) else {})} + else: + codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION, + EXCLUDED] + metrics = {c: definition.metric for c in codes} + return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c), + "criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()] + + +def measure_resource(definition, title: str, description: str) -> dict: + """The `Measure` of a definition: one group per group it publishes, each with its populations and strata.""" + meta = getattr(definition, "meta", {}) or {} + strata = [{"code": concept(STRATIFIER_SYSTEM, s.name, text=s.spec.get("etiqueta", s.name))} + for s in definition.strata] + if isinstance(definition, CompositionDefinition): + strata.insert(0, {"code": concept(STRATIFIER_SYSTEM, definition.category.value)}) + groups = [{"code": concept(GROUP_SYSTEM, definition.group), "population": _populations(definition), + **({"stratifier": strata} if strata else {})}] + groups += [{"code": concept(GROUP_SYSTEM, g.name, g.label), "population": _populations(definition)} + for g in getattr(definition, "groups", ())] + extensions = [{"url": CONTRACT, "valueCode": meta.get("contrato", "")}, + *({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())), + *({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))] + category = meta.get("categoria", {}) + extensions += [{"url": CATEGORY_LABEL, "extension": [ + {"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]}, + {"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()] + if meta.get("requiere_validacion"): + extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]}) + resource = { + "resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition), + "version": definition.version, "name": definition.metric, "title": title, "status": "active", + "description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)], + "scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups, + } + if definition.basis: + resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis) + if definition.improvement_notation: + resource["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation) + return resource + + +def _count(code: str, n: int) -> dict: + return {"code": concept(POPULATION_SYSTEM, code), "count": n} + + +def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -> dict: + cells = {"population": [*(_count(c, counts.denominator) for c in definition.denominator.codes), + *(_count(c, counts.numerator) for c in definition.numerator.codes)]} + if excluded is not None and getattr(definition, "exclusion", None): + cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes] + if counts.proportion is not None: + cells["measureScore"] = {"value": counts.proportion} + return cells + + +def _label(spec: dict, value: str) -> str | None: + """A stratum value's label, when the stratum's `valores` maps values to labels.""" + labels_of = spec.get("valores") + return labels_of.get(value) if isinstance(labels_of, dict) else None + + +def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict: + return concept(f"{CODE_SYSTEM}/{stratifier.replace('_', '-')}", value, display) + + +def _groups(definition, result) -> list[dict]: + if isinstance(result, CompositionAnswer): + group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [_count("initial-population", + result.total)]} + labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()} + category = definition.category.value + stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [ + {"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]} + for c, n in sorted(result.categories.items())]}] + for name, by_value in result.strata.items(): + stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)], + "stratum": [{"component": [ + {"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)}, + {"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)}, + ], "population": [_count("initial-population", n)]} + for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]}) + group["stratifier"] = stratifiers + return [group] + if isinstance(result, DurationAnswer): + group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [ + _count("initial-population", result.initial), _count(OBSERVATION, result.n), + _count(EXCLUDED, result.excluded)]} + if result.median is not None: + group["measureScore"] = {"value": result.median, "unit": "d", "extension": [ + {"url": f"{STRUCTURE}/q1", "valueDecimal": result.q1}, + {"url": f"{STRUCTURE}/q3", "valueDecimal": result.q3}]} + return [group] + assert isinstance(result, Answer) + spec_of = {s.name: s.spec for s in definition.strata} + group = {"code": concept(GROUP_SYSTEM, definition.group), **_proportion_cells(definition, result.total, + result.excluded)} + if result.strata: + group["stratifier"] = [{"code": [concept(STRATIFIER_SYSTEM, name, text=spec_of[name].get("etiqueta"))], + "stratum": [{"value": _stratum_value(name, value, _label(spec_of[name], value)), + **_proportion_cells(definition, c)} + for value, c in sorted(values.items())]} + for name, values in result.strata.items()] + groups = [group] + labels_of = {g.name: g.label for g in getattr(definition, "groups", ())} + groups += [{"code": concept(GROUP_SYSTEM, name, labels_of.get(name)), **_proportion_cells(definition, counts)} + for name, counts in result.groups.items()] + return groups + + +def measure_report(definition, question, result, period, generated_at: datetime) -> dict: + """An answer as a FHIR R4 `MeasureReport` (summary), naming its measure by its absolute canonical.""" + cutoff = getattr(result, "event_cutoff", None) or question.event_cutoff + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}] + if cutoff is not None: + extensions.append({"url": EVENT_CUTOFF, "valueDate": cutoff.isoformat()}) + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + report = { + "resourceType": "MeasureReport", "id": f"{fhir_id(definition)}-{result.report_id}", "status": "complete", + "type": "summary", "measure": f"{measure_url(definition)}|{definition.version}", + "date": generated_at.isoformat(), + # FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`. + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, "group": _groups(definition, result), + } + if definition.improvement_notation: + report["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation) + return report diff --git a/webapi/fhir/tea.py b/webapi/fhir/tea.py new file mode 100644 index 0000000..a16d3e8 --- /dev/null +++ b/webapi/fhir/tea.py @@ -0,0 +1,352 @@ +"""TEA's patients as FHIR R4 resources: the follow-up list as `EpisodeOfCare`s and the patient summary. + +Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, not states: every state here is taken +at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its +stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a +`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not +valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. + +Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`): +the alteration filter, the abnormal/normal split, and the metric and electrode observations. +""" + +import os +from dataclasses import dataclass +from datetime import date + +from sqlalchemy import column, select, table + +from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged +from webapi.follow_up.listing import seudonimo + +STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"), + ("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"), + ("EEG", "fecha_eeg", "EEG de buena calidad")) +CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"), + ("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"), + ("calidad_correlacion", "Baja correlación entre canales", "canales"), + ("calidad_sin_senal", "Canales planos o sin señal", "canales"), + ("calidad_linea", "Ruido de la línea eléctrica", "dB")) +ALTERED = ("aumentado", "disminuido") +INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation" +ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason" +ICD10 = "http://hl7.org/fhir/sid/icd-10" +CATALOG = f"{CODE_SYSTEM}/tea-catalogo" +STAGE_DATE = f"{STRUCTURE}/fecha-etapa" +AGE_GROUP = f"{STRUCTURE}/grupo-edad" +DEFAULT_SALT = "dev-simulado" + +FOLLOW_UP = table("tea_seguimiento", *map(column, ( + "pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2", + "fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg"))) +EEGS = table("tea_paciente_eegs", *map(column, ( + "procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido", + *(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno"))))) +METRICS = table("tea_paciente_eeg_metricas", *map(column, ( + "procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado"))) +ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo", + "valor"))) +ADOS2 = table("tea_paciente_ados2", *map(column, ( + "procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo", + "etiqueta", "puntaje", "puntaje_algoritmo"))) +PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento")) + + +def alterations_validated() -> bool: + """Whether the domain expert validated the reference ranges, effect texts and quality thresholds + (`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown.""" + return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si") + + +def salt() -> str: + return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT) + + +def _date(value) -> date | None: + if value is None or isinstance(value, date): + return value + return date.fromisoformat(str(value)[:10]) + + +def _rows(queries, query) -> list[dict]: + columns, rows = queries.rows(query) + return [dict(zip(columns, row)) for row in rows] + + +@dataclass +class Episode: + """A child's screening at the cut-off: its follow-up row, the steps reached, the study's EEG and its metrics.""" + + child: dict + cutoff: date + eegs: list[dict] + metrics: list[dict] + + @property + def pseudonym(self) -> str: + return seudonimo(self.child["pac_id"], salt()) + + def reached(self) -> list[tuple[str, date, str]]: + steps = [] + for code, field, label in STEPS: + when = _date(self.child[field]) + if when is None or when > self.cutoff: + break + steps.append((code, when, label)) + return steps + + @property + def stage(self) -> tuple[str, date] | None: + steps = self.reached() + return (steps[-1][0], steps[-1][1]) if steps else None + + @property + def finished(self) -> bool: + return any(code == "EEG" for code, _, _ in self.reached()) + + @property + def pending(self) -> list[str]: + done = {code for code, _, _ in self.reached()} + return [label for code, _, label in STEPS if code not in done] + + @property + def diagnosis(self) -> bool | None: + """True with a F84.0 note by the cut-off, False with only notes without it, None without a note.""" + if (_date(self.child["fecha_tea"]) or date.max) <= self.cutoff: + return True + if (_date(self.child["fecha_sin_tea"]) or date.max) <= self.cutoff: + return False + return None + + def study_eeg(self) -> dict | None: + """The first good EEG by the cut-off; without one, the latest by then (not valid).""" + known = sorted((e for e in self.eegs if (_date(e["fecha_eeg"]) or date.max) <= self.cutoff), + key=lambda e: (_date(e["fecha_eeg"]), e["procedimiento_id"])) + good = [e for e in known if e["valido"] == 1] + return good[0] if good else (known[-1] if known else None) + + def alterations(self) -> list[str]: + eeg = self.study_eeg() + if eeg is None or eeg["valido"] != 1: + return [] + return sorted(m["metrica"] for m in self.metrics + if m["procedimiento_id"] == eeg["procedimiento_id"] and m["estado"] in ALTERED) + + @property + def eeg_result(self) -> str: + eeg = self.study_eeg() + if eeg is None or eeg["valido"] != 1: + return "sin-eeg-valido" + return "anormal" if self.alterations() else "normal" + + +def episodes(queries, cutoff: date) -> list[Episode]: + """Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics.""" + eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS)) + by_child = {} + for child in _rows(queries, select(FOLLOW_UP)): + if (_date(child["fecha_mchat"]) or date.max) <= cutoff: + by_child[child["pac_id"]] = Episode(child, cutoff, [], []) + for eeg in eegs: + if eeg["pac_id"] in by_child: + by_child[eeg["pac_id"]].eegs.append(eeg) + for metric in metrics: + if metric["pac_id"] in by_child: + by_child[metric["pac_id"]].metrics.append(metric) + return list(by_child.values()) + + +def patient_of(queries, pseudonym: str) -> int | None: + """The `pac_id` behind a pseudonym, among the cohort's children.""" + for child in _rows(queries, select(FOLLOW_UP.c.pac_id)): + if seudonimo(child["pac_id"], salt()) == pseudonym: + return child["pac_id"] + return None + + +# --- resources ------------------------------------------------------------------------------------------------------- + + +def patient(pac_id: int, birth: date | None, simulated: bool) -> dict: + resource = {"resourceType": "Patient", "id": seudonimo(pac_id, salt())} + if birth is not None: + resource["birthDate"] = _date(birth).strftime("%Y-%m") + return tagged(resource, simulated) + + +def episode_of_care(e: Episode, simulated: bool) -> dict: + stage = e.stage + resource = { + "resourceType": "EpisodeOfCare", "id": e.pseudonym, "status": "finished" if e.finished else "active", + "patient": {"reference": f"Patient/{e.pseudonym}"}, + "period": {"start": _date(e.child["fecha_mchat"]).isoformat(), + **({"end": stage[1].isoformat()} if e.finished else {})}, + "extension": [{"url": AGE_GROUP, "valueCoding": {"system": f"{CODE_SYSTEM}/grupo-edad", + "code": e.child["grupo_edad"]}}], + } + if stage is not None: + resource["type"] = [concept(f"{CODE_SYSTEM}/paso", stage[0])] + resource["extension"].append({"url": STAGE_DATE, "valueDate": stage[1].isoformat()}) + return tagged(resource, simulated) + + +def care_plan(e: Episode, simulated: bool) -> dict: + """The episode's steps, each `completed` with its date or `not-started`.""" + done = {code: when for code, when, _ in e.reached()} + activities = [{"detail": { + "code": concept(f"{CODE_SYSTEM}/paso", code, text=label), + "status": "completed" if code in done else "not-started", + **({"scheduledString": done[code].isoformat()} if code in done else {})}} for code, _, label in STEPS] + return tagged({"resourceType": "CarePlan", "id": f"pasos-{e.pseudonym}", "status": "active" if not e.finished + else "completed", "intent": "plan", "subject": {"reference": f"Patient/{e.pseudonym}"}, + "extension": [{"url": f"{STRUCTURE}/episodio", "valueReference": { + "reference": f"EpisodeOfCare/{e.pseudonym}"}}], + "activity": activities}, simulated) + + +def mchat_observation(e: Episode, simulated: bool) -> dict | None: + if e.child["mchat"] is None: + return None + return tagged({"resourceType": "Observation", "id": f"mchat-{e.pseudonym}", "status": "final", + "code": concept(CATALOG, "mchat.puntaje", "M-CHAT-R/F: puntaje total"), + "subject": {"reference": f"Patient/{e.pseudonym}"}, + "effectiveDateTime": _date(e.child["fecha_mchat"]).isoformat(), + "valueInteger": int(e.child["mchat"])}, simulated) + + +def condition(e: Episode, simulated: bool) -> dict | None: + if not e.diagnosis: + return None + return tagged({"resourceType": "Condition", "id": f"tea-{e.pseudonym}", + "code": concept(ICD10, "F84.0", "Autismo en la niñez"), + "subject": {"reference": f"Patient/{e.pseudonym}"}, + "recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated) + + +def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]: + observations = [] + for name, label, unit in CRITERIA: + if eeg[name] is None: + continue + value = ({"valueInteger": int(eeg[name])} if unit == "canales" + else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}}) + observations.append(tagged({ + "resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}", + "status": "final", "code": concept(CATALOG, f"eeg.{name}", label), + "subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(), + **value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")], + }, simulated)) + return observations + + +def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str, + simulated: bool) -> list[dict]: + """One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or + why it couldn't be evaluated) and one per metric with a component per electrode.""" + from webapi.fhir.terminology import TEA_EEG + + observations = [] + for m in sorted((m for m in metrics if m["procedimiento_id"] == eeg["procedimiento_id"]), key=lambda m: m["metrica"]): + spec = TEA_EEG["metricas"].get(m["metrica"], {"etiqueta": m["metrica"], "unidad": ""}) + code = concept(f"{CODE_SYSTEM}/tea-eeg-metrica", m["metrica"], spec["etiqueta"]) + resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}", + "status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()} + if m["valor"] is None or m["valor_z"] is None: + resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown") + else: + resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]} + resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get( + m["estado"], "N"))] + resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"), + "valueQuantity": {"value": round(float(m["valor_z"]), 2)}}] + if m["ref_min"] is not None: + resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]}, + "high": {"value": float(m["ref_max"]), "unit": spec["unidad"]}, + "text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}] + observations.append(tagged(resource, simulated)) + at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]] + if at: + observations.append(tagged({ + "resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}", + "status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(), + "component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]), + "valueQuantity": {"value": float(x["valor"])}} + for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated)) + return observations + + +def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]: + """The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has + no result beyond its quality, and the alterations stay out until validated.""" + quality = quality_observations(eeg, pseudonym, simulated) + altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated) + if eeg["valido"] == 1 and alterations_validated() else []) + procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed", + "code": concept(CATALOG, "eeg", "Electroencefalograma"), + "subject": {"reference": f"Patient/{pseudonym}"}, + "performedDateTime": _date(eeg["fecha_eeg"]).isoformat()}, simulated) + report = {"resourceType": "DiagnosticReport", "id": f"eeg-{eeg['procedimiento_id']}", "status": "final", + "code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(), + "result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered], + "conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]} + if eeg["duracion_min"] is not None or eeg["canales"] is not None: + report["extension"] = [e for e in ( + {"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])} + if eeg["duracion_min"] is not None else None, + {"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None, + ) if e] + if eeg["valido"] != 1: + report["conclusion"] = "EEG de mala calidad: no es válido para el estudio." + return [procedure, tagged(report, simulated), *quality, *altered] + + +def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None: + """The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the + items, each item with its algorithm score.""" + if not rows: + return None + first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"])) + items = [r for r in rows if r["procedimiento_id"] == first["procedimiento_id"] and r["reactivo"]] + components = [] + if first["modulo"]: + components.append({"code": concept(CATALOG, "ados2.modulo", "Módulo"), + "valueCodeableConcept": concept(CATALOG, f"ados2.modulo.{first['modulo']}")}) + if first["algoritmo"]: + components.append({"code": concept(CATALOG, "ados2.algoritmo", "Algoritmo"), "valueString": first["algoritmo"]}) + if first["css"] is not None: + components.append({"code": concept(CATALOG, "ados2.css", "Puntaje de severidad (CSS)"), + "valueInteger": int(first["css"])}) + if first["clasificacion"]: + components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"), + "valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")}) + for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")): + total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain) + components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total}) + components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]), + "extension": [{"url": f"{STRUCTURE}/puntaje-algoritmo", "valueInteger": int(r["puntaje_algoritmo"])}, + {"url": f"{STRUCTURE}/dominio", "valueCode": r["dominio"]}]} + for r in sorted(items, key=lambda r: r["reactivo"])] + return tagged({"resourceType": "Observation", "id": f"ados2-{first['procedimiento_id']}", "status": "final", + "code": concept(CATALOG, "ados2", "ADOS-2"), "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(first["fecha_ados2"]).isoformat(), "component": components}, simulated) + + +def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict: + """The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today.""" + pseudonym = seudonimo(pac_id, salt()) + persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id)) + resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)] + ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated) + resources += [ados2] if ados2 else [] + (child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None] + if child is not None: + e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)), + _rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id))) + eeg = e.study_eeg() + if eeg is not None: + electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id)) + resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated) + return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]} diff --git a/webapi/fhir/tea_eeg.toml b/webapi/fhir/tea_eeg.toml new file mode 100644 index 0000000..709e3ae --- /dev/null +++ b/webapi/fhir/tea_eeg.toml @@ -0,0 +1,53 @@ +# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where +# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1). +# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`. + +[metricas.ritmo_posterior] +etiqueta = "Ritmo posterior" +unidad = "Hz" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."] + +[metricas.husos_sueno_n2] +etiqueta = "Husos de sueño N2" +unidad = "husos/min" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."] + +[metricas.husos_sueno_n3] +etiqueta = "Husos de sueño N3" +unidad = "husos/min" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."] + +[metricas.picos_paroxisticos] +etiqueta = "Picos paroxísticos" +unidad = "picos/min" +efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."] + +[metricas.gradiente_anteroposterior] +etiqueta = "Gradiente anteroposterior" +unidad = "razón posterior/anterior" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."] + +[electrodos] +Fp1 = [-0.25, 0.77] +Fp2 = [0.25, 0.77] +F7 = [-0.65, 0.47] +F3 = [-0.33, 0.4] +Fz = [0.0, 0.38] +F4 = [0.33, 0.4] +F8 = [0.65, 0.47] +T3 = [-0.8, 0.0] +C3 = [-0.4, 0.0] +Cz = [0.0, 0.0] +C4 = [0.4, 0.0] +T4 = [0.8, 0.0] +T5 = [-0.65, -0.47] +P3 = [-0.33, -0.4] +Pz = [0.0, -0.38] +P4 = [0.33, -0.4] +T6 = [0.65, -0.47] +O1 = [-0.25, -0.77] +O2 = [0.25, -0.77] diff --git a/webapi/fhir/terminology.py b/webapi/fhir/terminology.py new file mode 100644 index 0000000..4259326 --- /dev/null +++ b/webapi/fhir/terminology.py @@ -0,0 +1,74 @@ +"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's +catalog (`core/catalogos/.toml`: studies, results and their values), TEA's screening stages and diagnostic +results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`).""" + +import tomllib +from pathlib import Path + +from webapi.fhir.common import CODE_SYSTEM, canonical +from webapi.orchestration.reference.catalogs import ruta_de_catalogo + +TEA_EEG = tomllib.loads((Path(__file__).parent / "tea_eeg.toml").read_text(encoding="utf-8")) +STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psicológica"), + ("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG")) +DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado")) +QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar")) + + +def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict: + resource = {"resourceType": "CodeSystem", "id": id_, "url": f"{CODE_SYSTEM}/{id_}", "name": id_.replace("-", "_"), + "title": title, "status": "active", "content": "complete", "concept": concepts} + if hierarchy: + resource["hierarchyMeaning"] = "part-of" + return resource + + +def catalog(domain: str) -> dict: + """The domain's catalog: each study, its results under it and each coded result's values under the result.""" + studies = tomllib.loads(ruta_de_catalogo(domain).read_text(encoding="utf-8")) + concepts = [] + for study_id, study in studies.items(): + results = [] + for name, result in study.get("resultados", {}).items(): + values = [{"code": f"{study_id}.{name}.{v['valor']}", "display": v["etiqueta"]} + for v in result.get("valores", ())] + results.append({"code": f"{study_id}.{name}", "display": result["etiqueta"], + **({"concept": values} if values else {})}) + concepts.append({"code": study_id, "display": study["etiqueta"], **({"concept": results} if results else {})}) + return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True) + + +def tea_code_systems() -> dict[str, dict]: + metrics = [{"code": code, "display": spec["etiqueta"], "property": [ + {"code": "unidad", "valueString": spec["unidad"]}, + *({"code": f"efecto-{state}", "valueString": text} for state, texts in spec.get("efectos", {}).items() + for text in texts)]} for code, spec in TEA_EEG["metricas"].items()] + systems = [ + _code_system("paso", "Etapa del tamizaje de TEA", [{"code": c, "display": d} for c, d in STAGES]), + _code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]), + _code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]), + {**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics), + "property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"}, + {"code": "efecto-disminuido", "type": "string"}]}, + _code_system("electrodo-10-20", "Electrodos del sistema 10-20", + [{"code": e, "display": e} for e in TEA_EEG["electrodos"]]), + _code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [ + {"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"}, + {"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]), + ] + return {s["id"]: s for s in systems} + + +def code_systems(domain: str) -> dict[str, dict]: + """Every code system the domain's FHIR endpoint serves, by id.""" + systems = {f"{domain}-catalogo": catalog(domain)} + if domain == "tea": + systems.update(tea_code_systems()) + return systems + + +def metric_value_set() -> dict: + """The alteration types: the EEG metrics' `ValueSet`.""" + return {"resourceType": "ValueSet", "id": "tea-alteracion", "url": canonical("ValueSet/tea-alteracion"), + "name": "tea_alteracion", "title": "Tipos de alteración del EEG", "status": "active", + "compose": {"include": [{"system": f"{CODE_SYSTEM}/tea-eeg-metrica"}]}} diff --git a/webapi/imports/connectors/edf.py b/webapi/imports/connectors/edf.py index d132f00..cd2dfa8 100644 --- a/webapi/imports/connectors/edf.py +++ b/webapi/imports/connectors/edf.py @@ -1,4 +1,3 @@ -from datetime import date, timedelta from pathlib import PurePath from typing import Any @@ -11,15 +10,12 @@ from webapi.imports.connectors.errors import ConnectorError from webapi.imports.connectors.registry import register_connector from webapi.imports.connectors.tabular import FileConnector -MAX_LISTED_EVENTS = 20 - @register_connector class EdfConnector(FileConnector): - """EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`: - patient and dates from the header, an estimated background rhythm from - the posterior channels, a text summary of the recording, and the file - itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`).""" + """EEG recordings (`.edf`), one row per file, shaped for `tea.Eeg`: the laboratory's study id, the patient + and the study date from the header, the channels and duration of the recording, and the file itself (column + `estudio`, stored in `eeg.eeg_estudio`). The quality criteria, sleep and metrics are the EEG analysis'.""" kind = "edf" label = "EEG (EDF)" @@ -57,49 +53,12 @@ class EdfConnector(FileConnector): eeg = EegRecording.read(raw) except ExtractionError as exc: raise ConnectorError(f"{name}: {exc}") from exc - patient = eeg.patient - study_date = eeg.start.date() if eeg.start else None - rhythm = eeg.background_rhythm() return { "id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem, - "paciente": patient.code, - "sexo": patient.sex, - "fecha_nacimiento_declarada": patient.birthdate, - "edad_meses": age_in_months(patient.birthdate, study_date), - "fecha_estudio": study_date, - "duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None, - "ritmo_base_frecuencia": rhythm["frequency_hz"], - "ritmo_base_amplitud": rhythm["amplitude_uv"], - "descripcion_senal": describe(eeg), + "paciente": eeg.patient.code, + "fecha_estudio": eeg.start.date() if eeg.start else None, + "canales": len(eeg.channels), + "duracion_min": round(eeg.duration_seconds / 60, 1) if eeg.duration_seconds else None, "archivo": name, "estudio": raw, } - - -def describe(eeg: EegRecording) -> str: - channels = eeg.channels - parts = [ - f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant, - f"duración {timedelta(seconds=round(eeg.duration_seconds))}", - "montaje: " + ", ".join(c.label for c in channels), - ] - fields = eeg.recording_fields - if fields["equipment"]: - parts.append(f"equipo: {fields['equipment']}") - if fields["technician"]: - parts.append(f"técnico: {fields['technician']}") - events = eeg.annotations() - if events: - listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS]) - more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else "" - parts.append(f"eventos: {listed}{more}") - return ". ".join(parts) + "." - - -def age_in_months(birthdate: date | None, on: date | None) -> float | None: - if birthdate is None or on is None or on < birthdate: - return None - months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month) - if on.day < birthdate.day: - months -= 1 - return float(months) diff --git a/webapi/imports/schemas/coercion.py b/webapi/imports/schemas/coercion.py index 6b07a43..c84e929 100644 --- a/webapi/imports/schemas/coercion.py +++ b/webapi/imports/schemas/coercion.py @@ -7,7 +7,7 @@ from datetime import date, datetime from enum import Enum from typing import Annotated, Any, Optional, Type -from pydantic import BeforeValidator, StringConstraints, ValidationInfo +from pydantic import BeforeValidator, Field, StringConstraints, ValidationInfo from core.columns import HOSPITAL_ID_LENGTH from extraction import ExtractionError @@ -140,7 +140,7 @@ CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")] def edf_file(v: Any) -> Any: - """`eeg_estudio.eeg_estudio`: an EDF file MNE can open (TEA amendment). + """`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment). JSON sources may carry it base64-encoded.""" if v is None or (isinstance(v, str) and not v.strip()): return None @@ -168,3 +168,9 @@ FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)] RequiredDate = Annotated[date, BeforeValidator(required_date)] PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)] EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)] + + +def Bounded(kind: type, low: float | None = None, high: float | None = None): # noqa: N802 (used like a type) + """An optional number within [low, high], either bound open when None: a score or a count out of range is a + validation error, not a stored value.""" + return Optional[Annotated[kind, Field(ge=low, le=high)]] diff --git a/webapi/imports/schemas/registry.py b/webapi/imports/schemas/registry.py index a8d546f..b22ca32 100644 --- a/webapi/imports/schemas/registry.py +++ b/webapi/imports/schemas/registry.py @@ -24,18 +24,14 @@ from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_ from persistance.cama import paciente_repository as cama_paciente_repository from persistance.repository import Repository from webapi.imports.schemas.base import ImportSchema -from persistance.tea import antecedentes_maternos_gestacion_repository as tea_antecedentes_maternos_gestacion_repository -from persistance.tea import eeg_estudio_repository as tea_eeg_estudio_repository -from persistance.tea import eeg_segmento_repository as tea_eeg_segmento_repository -from persistance.tea import evaluacion_psicologica_repository as tea_evaluacion_psicologica_repository -from persistance.tea import instrumento_aplicado_repository as tea_instrumento_aplicado_repository -from persistance.tea import nota_medica_repository as tea_nota_medica_repository +from persistance.tea import ados2_repository as tea_ados2_repository +from persistance.tea import eeg_metrica_electrodo_repository as tea_eeg_metrica_electrodo_repository +from persistance.tea import eeg_metrica_repository as tea_eeg_metrica_repository +from persistance.tea import eeg_repository as tea_eeg_repository +from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluacion_neuropediatrica_repository +from persistance.tea import mchat_repository as tea_mchat_repository from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository from persistance.tea import pacientes_repository as tea_pacientes_repository -from persistance.tea import parto_neonatal_repository as tea_parto_neonatal_repository -from persistance.tea import ( - potenciales_evocados_auditivos_repository as tea_potenciales_evocados_auditivos_repository, -) from webapi.imports.schemas.cacu.biometria_hematica import ( BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema, ) @@ -62,22 +58,16 @@ from webapi.imports.schemas.cama.ordenes_estudio import ( OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema, ) from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema -from webapi.imports.schemas.tea.antecedentes_maternos_gestacion import ( - AntecedentesMaternosGestacionImportSchema, -) -from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema -from webapi.imports.schemas.tea.eeg_segmento import EegSegmentoImportSchema -from webapi.imports.schemas.tea.evaluacion_psicologica import EvaluacionPsicologicaImportSchema -from webapi.imports.schemas.tea.instrumento_aplicado import InstrumentoAplicadoImportSchema -from webapi.imports.schemas.tea.nota_medica import NotaMedicaImportSchema as TeaNotaMedicaImportSchema +from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema +from webapi.imports.schemas.tea.eeg import EegImportSchema +from webapi.imports.schemas.tea.eeg_metrica import EegMetricaImportSchema +from webapi.imports.schemas.tea.eeg_metrica_electrodo import EegMetricaElectrodoImportSchema +from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema +from webapi.imports.schemas.tea.mchat import MchatImportSchema from webapi.imports.schemas.tea.ordenes_estudio import ( OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema, ) from webapi.imports.schemas.tea.pacientes import PacientesImportSchema -from webapi.imports.schemas.tea.parto_neonatal import PartoNeonatalImportSchema -from webapi.imports.schemas.tea.potenciales_evocados_auditivos import ( - PotencialesEvocadosAuditivosImportSchema, -) @dataclass(frozen=True) @@ -131,8 +121,7 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = { "cacu.EpisodioClinico": EntitySpec( schema=CacuEpisodioClinicoImportSchema, repository=cacu_episodio_clinico_repository, - # No hospital-visible identifier of its own, like EvaluacionPsicologica - # or PartoNeonatal; a patient can have several episodes. + # No hospital-visible identifier of its own; a patient can have several episodes. conflict_fields=None, ), "cama.Paciente": EntitySpec( @@ -175,48 +164,37 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = { repository=tea_ordenes_estudio_repository, conflict_fields=("ord_id_hospital",), ), - "tea.NotaMedica": EntitySpec( - schema=TeaNotaMedicaImportSchema, - repository=tea_nota_medica_repository, - conflict_fields=("nm_id_hospital",), + "tea.Mchat": EntitySpec( + schema=MchatImportSchema, + repository=tea_mchat_repository, + conflict_fields=("mch_id",), ), - "tea.EvaluacionPsicologica": EntitySpec( - schema=EvaluacionPsicologicaImportSchema, - repository=tea_evaluacion_psicologica_repository, - conflict_fields=None, + "tea.Ados2": EntitySpec( + schema=Ados2ImportSchema, + repository=tea_ados2_repository, + conflict_fields=("ado_id",), ), - "tea.PotencialesEvocadosAuditivos": EntitySpec( - schema=PotencialesEvocadosAuditivosImportSchema, - repository=tea_potenciales_evocados_auditivos_repository, - conflict_fields=None, + "tea.EvaluacionNeuropediatrica": EntitySpec( + schema=EvaluacionNeuropediatricaImportSchema, + repository=tea_evaluacion_neuropediatrica_repository, + conflict_fields=("neu_id",), ), - "tea.EegEstudio": EntitySpec( - schema=EegEstudioImportSchema, - repository=tea_eeg_estudio_repository, - # The EDF file and its scanned report describe the same study; both - # the `edf` connector (from the file's own admin code) and a - # `document` source (read from the report text) populate this field, - # so merge_duplicates/on_conflict=upsert can land them on one row. + "tea.Eeg": EntitySpec( + schema=EegImportSchema, + repository=tea_eeg_repository, + # The EDF file and its report describe the same study; the `edf` connector (from the file's own admin + # code) and a `document` source both fill this field, so merge_duplicates/on_conflict=upsert land them on + # one row. conflict_fields=("eeg_id_registro_laboratorio",), ), - "tea.EegSegmento": EntitySpec( - schema=EegSegmentoImportSchema, - repository=tea_eeg_segmento_repository, - conflict_fields=None, + "tea.EegMetrica": EntitySpec( + schema=EegMetricaImportSchema, + repository=tea_eeg_metrica_repository, + conflict_fields=("met_id",), ), - "tea.InstrumentoAplicado": EntitySpec( - schema=InstrumentoAplicadoImportSchema, - repository=tea_instrumento_aplicado_repository, - conflict_fields=None, - ), - "tea.AntecedentesMaternosGestacion": EntitySpec( - schema=AntecedentesMaternosGestacionImportSchema, - repository=tea_antecedentes_maternos_gestacion_repository, - conflict_fields=None, - ), - "tea.PartoNeonatal": EntitySpec( - schema=PartoNeonatalImportSchema, - repository=tea_parto_neonatal_repository, - conflict_fields=None, + "tea.EegMetricaElectrodo": EntitySpec( + schema=EegMetricaElectrodoImportSchema, + repository=tea_eeg_metrica_electrodo_repository, + conflict_fields=("mel_id",), ), } diff --git a/webapi/imports/schemas/tea/ados2.py b/webapi/imports/schemas/tea/ados2.py new file mode 100644 index 0000000..973ce22 --- /dev/null +++ b/webapi/imports/schemas/tea/ados2.py @@ -0,0 +1,55 @@ +"""Import schema for `core.tea.models.Ados2`: module, algorithm, CSS, classification and the 28 algorithm items. + +The domain subtotals and the total aren't imported: they're sums of the items' algorithm scores.""" +from typing import Optional + +from core.tea.enums import CLASIFICACION_ADOS2_ALIAS, ClasificacionAdos2, ModuloAdos2 +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, FlexDate, OptionalStr, SourceId + +_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2) +_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS) +_ITEM = Bounded(int, 0, 3) + + +class Ados2ImportSchema(ImportSchema): + ado_id: SourceId = None + ado_pac_id: Optional[int] = None + ado_ord_id: OptionalStr = None + ado_fecha: FlexDate = None + ado_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None + ado_algoritmo: OptionalStr = None + ado_css: Bounded(int, 1, 10) = None + ado_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None + + # Social affect (SA) + ado_sa_a2: _ITEM = None + ado_sa_a6: _ITEM = None + ado_sa_a7: _ITEM = None + ado_sa_a8: _ITEM = None + ado_sa_b1: _ITEM = None + ado_sa_b2: _ITEM = None + ado_sa_b3: _ITEM = None + ado_sa_b4: _ITEM = None + ado_sa_b5: _ITEM = None + ado_sa_b6: _ITEM = None + ado_sa_b7: _ITEM = None + ado_sa_b8: _ITEM = None + ado_sa_b9: _ITEM = None + ado_sa_b10: _ITEM = None + ado_sa_b11: _ITEM = None + ado_sa_b12: _ITEM = None + ado_sa_b13: _ITEM = None + ado_sa_b14: _ITEM = None + ado_sa_b15: _ITEM = None + ado_sa_b16b: _ITEM = None + ado_sa_b18: _ITEM = None + + # Restricted and repetitive behaviour (RRB) + ado_rrb_a3: _ITEM = None + ado_rrb_a4: _ITEM = None + ado_rrb_a5: _ITEM = None + ado_rrb_d1: _ITEM = None + ado_rrb_d2: _ITEM = None + ado_rrb_d4: _ITEM = None + ado_rrb_d5: _ITEM = None diff --git a/webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py b/webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py deleted file mode 100644 index 7e34450..0000000 --- a/webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Import schema for `core.tea.models.AntecedentesMaternosGestacion`. All fields -optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - CategoriaPesoMaterno, - FuenteAntecedenteMaterno, - TipoEmbarazo, - TrastornoHipertensivoGestacion, - VolumenLiquidoAmniotico, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr - -_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno) -_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno) -_TIPO_EMBARAZO_CATALOG = Catalog(TipoEmbarazo) -_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG = Catalog(TrastornoHipertensivoGestacion) -_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico) - - -class AntecedentesMaternosGestacionImportSchema(ImportSchema): - amg_pac_id: Optional[int] = None - amg_id_madre_seudonimo: OptionalStr = None - amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None - amg_flag_vinculo_verificado: Optional[int] = None - amg_imc_pregestacional: Optional[float] = None - amg_categoria_peso_materno: CatalogValue(_CATEGORIA_PESO_MATERNO_CATALOG) = None - amg_tabaquismo_gestacion: Optional[int] = None - amg_acido_folico_preconcepcional: Optional[int] = None - amg_intervalo_intergenesico_meses: Optional[int] = None - amg_antecedente_aborto: Optional[int] = None - amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None - amg_infeccion_gestacion: Optional[int] = None - amg_infeccion_tipo: OptionalStr = None - amg_infeccion_hospitalizacion: Optional[int] = None - amg_diabetes_gestacional: Optional[int] = None - amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None - amg_hipotiroidismo: Optional[int] = None - amg_hipertiroidismo: Optional[int] = None - amg_incompatibilidad_rh: Optional[int] = None - amg_crisis_convulsivas: Optional[int] = None - amg_proceso_proinflamatorio: Optional[int] = None - amg_enfermedad_autoinmune: Optional[int] = None - amg_migrana: Optional[int] = None - amg_asma: Optional[int] = None - amg_hipoxia_materna: Optional[int] = None - amg_estres_agudo: Optional[int] = None - amg_trastorno_neurologico: Optional[int] = None - amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None - amg_medicamentos_gestacion: OptionalStr = None - amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None - amg_observaciones: OptionalStr = None - amg_ocr_confianza: Optional[float] = None - amg_nlp_version: OptionalStr = None diff --git a/webapi/imports/schemas/tea/eeg.py b/webapi/imports/schemas/tea/eeg.py new file mode 100644 index 0000000..ddcaf12 --- /dev/null +++ b/webapi/imports/schemas/tea/eeg.py @@ -0,0 +1,26 @@ +"""Import schema for `core.tea.models.Eeg`: the study, its EDF and what the EEG analysis writes back (sleep, +channels, duration and the five quality criteria).""" +from typing import Optional + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Bounded, EdfFile, FlexDate, OptionalStr, SourceId + +_CHANNELS = Bounded(int, 0, None) + + +class EegImportSchema(ImportSchema): + # The source's own id, kept so the metrics that reference it still point at this record. + eeg_id: SourceId = None + eeg_pac_id: Optional[int] = None + eeg_ord_id: OptionalStr = None + eeg_id_registro_laboratorio: OptionalStr = None + eeg_fecha_estudio: FlexDate = None + eeg_con_sueno: Bounded(int, 0, 1) = None + eeg_canales: Bounded(int, 1, 256) = None + eeg_duracion_min: Bounded(float, 0, None) = None + eeg_canales_amplitud: _CHANNELS = None + eeg_canales_alta_frecuencia: _CHANNELS = None + eeg_canales_correlacion: _CHANNELS = None + eeg_canales_sin_senal: _CHANNELS = None + eeg_ruido_linea_db: Bounded(float, 0, None) = None + eeg_estudio: EdfFile = None diff --git a/webapi/imports/schemas/tea/eeg_estudio.py b/webapi/imports/schemas/tea/eeg_estudio.py deleted file mode 100644 index 26e621e..0000000 --- a/webapi/imports/schemas/tea/eeg_estudio.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Import schema for `core.tea.models.EegEstudio`. All fields optional, like TEA's -Core; system-managed `eeg_created_at`/`eeg_updated_at` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - CalidadTecnicaEeg, - ConclusionEeg, - DistribucionAnormalidad, - EstadoRegistroEeg, - FuenteInterpretacionEeg, - Lentificacion, - RespuestaFotoestimulacion, - Simetria, - TipoGrafoelemento, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId - -_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg) -_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg) -_CALIDAD_TECNICA_EEG_CATALOG = Catalog(CalidadTecnicaEeg) -_SIMETRIA_CATALOG = Catalog(Simetria) -_TIPO_GRAFOELEMENTO_CATALOG = Catalog(TipoGrafoelemento) -_DISTRIBUCION_ANORMALIDAD_CATALOG = Catalog(DistribucionAnormalidad) -_LENTIFICACION_CATALOG = Catalog(Lentificacion) -_RESPUESTA_FOTOESTIMULACION_CATALOG = Catalog(RespuestaFotoestimulacion) -_CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg) - - -class EegEstudioImportSchema(ImportSchema): - # The source's own id, kept so rows that reference it by id still point at this record. - eeg_id: SourceId = None - eeg_ord_id: OptionalStr = None - eeg_pac_id: Optional[int] = None - eeg_reporte_disponible: Optional[int] = None - eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None - eeg_fecha_nacimiento_archivo: FlexDate = None - eeg_edad_meses: Optional[float] = None - eeg_fecha_estudio: FlexDate = None - eeg_fecha_reporte: FlexDate = None - eeg_dias_respuesta: Optional[int] = None - eeg_medico_interpreta: OptionalStr = None - eeg_estado_registro: CatalogValue(_ESTADO_REGISTRO_EEG_CATALOG) = None - eeg_privacion_sueno: Optional[int] = None - eeg_sedacion: Optional[int] = None - eeg_sedacion_farmaco: OptionalStr = None - eeg_duracion_min: Optional[float] = None - eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None - eeg_descripcion_senal: OptionalStr = None - eeg_ritmo_base_frecuencia: Optional[float] = None - eeg_ritmo_base_amplitud: Optional[int] = None - eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None - eeg_anormalidad_presente: Optional[int] = None - eeg_actividad_epileptiforme: Optional[int] = None - eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None - eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None - eeg_localizacion: OptionalStr = None - eeg_activacion_sueno: Optional[int] = None - eeg_lentificacion: CatalogValue(_LENTIFICACION_CATALOG) = None - eeg_crisis_registradas: Optional[int] = None - eeg_respuesta_fotoestimulacion: CatalogValue(_RESPUESTA_FOTOESTIMULACION_CATALOG) = None - eeg_conclusion_texto: OptionalStr = None - eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None - eeg_id_registro_laboratorio: OptionalStr = None - eeg_pdf_ruta: OptionalStr = None - eeg_ocr_confianza: Optional[float] = None - eeg_nlp_version: OptionalStr = None - eeg_utilizable: Optional[int] = None - eeg_estudio: EdfFile = None diff --git a/webapi/imports/schemas/tea/eeg_metrica.py b/webapi/imports/schemas/tea/eeg_metrica.py new file mode 100644 index 0000000..95b798c --- /dev/null +++ b/webapi/imports/schemas/tea/eeg_metrica.py @@ -0,0 +1,16 @@ +"""Import schema for `core.tea.models.EegMetrica`: a metric the EEG analysis measured. A blank value is a metric +that can't be evaluated.""" +from typing import Optional + +from core.tea.enums import MetricaEeg +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr, SourceId + +_METRICA_CATALOG = Catalog(MetricaEeg) + + +class EegMetricaImportSchema(ImportSchema): + met_id: SourceId = None + met_eeg_id: OptionalStr = None + met_codigo: CatalogValue(_METRICA_CATALOG) = None + met_valor: Optional[float] = None diff --git a/webapi/imports/schemas/tea/eeg_metrica_electrodo.py b/webapi/imports/schemas/tea/eeg_metrica_electrodo.py new file mode 100644 index 0000000..9a91ee9 --- /dev/null +++ b/webapi/imports/schemas/tea/eeg_metrica_electrodo.py @@ -0,0 +1,12 @@ +"""Import schema for `core.tea.models.EegMetricaElectrodo`: a metric's z-score at one 10-20 electrode.""" +from typing import Optional + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import OptionalStr, SourceId + + +class EegMetricaElectrodoImportSchema(ImportSchema): + mel_id: SourceId = None + mel_met_id: OptionalStr = None + mel_electrodo: OptionalStr = None + mel_valor: Optional[float] = None diff --git a/webapi/imports/schemas/tea/eeg_segmento.py b/webapi/imports/schemas/tea/eeg_segmento.py deleted file mode 100644 index ee93850..0000000 --- a/webapi/imports/schemas/tea/eeg_segmento.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Import schema for `core.tea.models.EegSegmento`. All fields optional, like -TEA's Core.""" -from typing import Optional - -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import OptionalStr - - -class EegSegmentoImportSchema(ImportSchema): - seg_eeg_id: OptionalStr = None - seg_estado: OptionalStr = None - seg_inicio_s: Optional[float] = None - seg_fin_s: Optional[float] = None - seg_duracion_s: Optional[float] = None - seg_fuente: OptionalStr = None - seg_frecuencia_flash_hz: Optional[float] = None - seg_n_destellos: Optional[int] = None - seg_cobertura: Optional[float] = None - seg_rms_uv: Optional[float] = None - seg_emg: Optional[float] = None - seg_p2p_max_uv: Optional[float] = None diff --git a/webapi/imports/schemas/tea/evaluacion_neuropediatrica.py b/webapi/imports/schemas/tea/evaluacion_neuropediatrica.py new file mode 100644 index 0000000..ed5cf49 --- /dev/null +++ b/webapi/imports/schemas/tea/evaluacion_neuropediatrica.py @@ -0,0 +1,27 @@ +"""Import schema for `core.tea.models.EvaluacionNeuropediatrica`: the note and its ICD-10 diagnosis.""" +from typing import Annotated, Optional + +from pydantic import BeforeValidator, StringConstraints + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import FlexDate, OptionalStr, SourceId, optional_str + + +def _upper(v): + v = optional_str(v) + return v.strip().upper() if isinstance(v, str) else v + + +# A letter, two digits and optionally a dot with one or two more (F84.0); the dot may be missing (F840). +_CIE10 = Annotated[ + Optional[Annotated[str, StringConstraints(pattern=r"^[A-Z][0-9]{2}(\.?[0-9]{1,2})?$")]], + BeforeValidator(_upper), +] + + +class EvaluacionNeuropediatricaImportSchema(ImportSchema): + neu_id: SourceId = None + neu_pac_id: Optional[int] = None + neu_ord_id: OptionalStr = None + neu_fecha: FlexDate = None + neu_cie_codigo: _CIE10 = None diff --git a/webapi/imports/schemas/tea/evaluacion_psicologica.py b/webapi/imports/schemas/tea/evaluacion_psicologica.py deleted file mode 100644 index 0cfeb9b..0000000 --- a/webapi/imports/schemas/tea/evaluacion_psicologica.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Import schema for `core.tea.models.EvaluacionPsicologica`, including the 28 -ADOS-2 item columns. All fields optional, like TEA's Core; system-managed `psi_created_at`/`psi_updated_at` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - ClasificacionAdos2, - InstrumentoTamizaje, - ModuloAdos2, - NivelRiesgoTamizaje, - VentanaMadurativa, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId - -_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa) -_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje) -_NIVEL_RIESGO_TAMIZAJE_CATALOG = Catalog(NivelRiesgoTamizaje) -_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2) -_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2) - - -class EvaluacionPsicologicaImportSchema(ImportSchema): - # The source's own id, kept so rows that reference it by id still point at this record. - psi_id: SourceId = None - psi_ord_id: OptionalStr = None - psi_pac_id: Optional[int] = None - psi_fecha_entrevista_inicial: FlexDate = None - psi_fecha_ados2: FlexDate = None - psi_fecha_evaluacion: FlexDate = None - psi_psicologo: OptionalStr = None - psi_edad_meses: Optional[float] = None - psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None - psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None - psi_tamizaje_puntaje: Optional[int] = None - psi_tamizaje_riesgo: CatalogValue(_NIVEL_RIESGO_TAMIZAJE_CATALOG) = None - psi_ados2_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None - - # Items ADOS-2, dominio SA (Interaccion Social Reciproca) - psi_ados2_sa_a2: Optional[int] = None - psi_ados2_sa_a6: Optional[int] = None - psi_ados2_sa_a7: Optional[int] = None - psi_ados2_sa_a8: Optional[int] = None - psi_ados2_sa_b1: Optional[int] = None - psi_ados2_sa_b2: Optional[int] = None - psi_ados2_sa_b3: Optional[int] = None - psi_ados2_sa_b4: Optional[int] = None - psi_ados2_sa_b5: Optional[int] = None - psi_ados2_sa_b6: Optional[int] = None - psi_ados2_sa_b7: Optional[int] = None - psi_ados2_sa_b8: Optional[int] = None - psi_ados2_sa_b9: Optional[int] = None - psi_ados2_sa_b10: Optional[int] = None - psi_ados2_sa_b11: Optional[int] = None - psi_ados2_sa_b12: Optional[int] = None - psi_ados2_sa_b13: Optional[int] = None - psi_ados2_sa_b14: Optional[int] = None - psi_ados2_sa_b15: Optional[int] = None - psi_ados2_sa_b16b: Optional[int] = None - psi_ados2_sa_b18: Optional[int] = None - - # Items ADOS-2, dominio RRB (Conductas Restringidas y Repetitivas) - psi_ados2_rrb_a3: Optional[int] = None - psi_ados2_rrb_a4: Optional[int] = None - psi_ados2_rrb_a5: Optional[int] = None - psi_ados2_rrb_d1: Optional[int] = None - psi_ados2_rrb_d2: Optional[int] = None - psi_ados2_rrb_d4: Optional[int] = None - psi_ados2_rrb_d5: Optional[int] = None - - psi_ados2_sa: Optional[int] = None - psi_ados2_rrb: Optional[int] = None - psi_ados2_total: Optional[int] = None - psi_ados2_css: Optional[int] = None - psi_ados2_css_sa: Optional[int] = None - psi_ados2_css_rrb: Optional[int] = None - psi_ados2_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None - psi_rgd: Optional[int] = None - psi_cociente_desarrollo: Optional[float] = None - psi_css_umbral_aplicado: Optional[int] = None - psi_caso_confirmado: Optional[int] = None - psi_cars_total: Optional[float] = None - psi_otros_instrumentos: OptionalStr = None - psi_regresion_desarrollo: Optional[int] = None - psi_diagnostico_texto: OptionalStr = None - psi_ocr_confianza: Optional[float] = None - psi_nlp_version: OptionalStr = None diff --git a/webapi/imports/schemas/tea/instrumento_aplicado.py b/webapi/imports/schemas/tea/instrumento_aplicado.py deleted file mode 100644 index 1025946..0000000 --- a/webapi/imports/schemas/tea/instrumento_aplicado.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields -optional, like TEA's Core.""" - -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import OptionalStr - - -class InstrumentoAplicadoImportSchema(ImportSchema): - ins_psi_id: OptionalStr = None - ins_instrumento: OptionalStr = None - ins_informante: OptionalStr = None - ins_area: OptionalStr = None - ins_interpretacion: OptionalStr = None diff --git a/webapi/imports/schemas/tea/mchat.py b/webapi/imports/schemas/tea/mchat.py new file mode 100644 index 0000000..444fd0c --- /dev/null +++ b/webapi/imports/schemas/tea/mchat.py @@ -0,0 +1,13 @@ +"""Import schema for `core.tea.models.Mchat`: one M-CHAT-R/F and its total score.""" +from typing import Optional + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Bounded, FlexDate, OptionalStr, SourceId + + +class MchatImportSchema(ImportSchema): + mch_id: SourceId = None + mch_pac_id: Optional[int] = None + mch_ord_id: OptionalStr = None + mch_fecha: FlexDate = None + mch_puntaje: Bounded(int, 0, 20) = None diff --git a/webapi/imports/schemas/tea/nota_medica.py b/webapi/imports/schemas/tea/nota_medica.py deleted file mode 100644 index 5e06694..0000000 --- a/webapi/imports/schemas/tea/nota_medica.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's -Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded.""" -from typing import Optional - -from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr - -_TIPO_NOTA_CATALOG = Catalog(TipoNota) -_ESPECIALIDAD_CATALOG = Catalog(Especialidad) -_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa) -_PRONOSTICO_CATALOG = Catalog(Pronostico) - - -class NotaMedicaImportSchema(ImportSchema): - nm_pac_id: Optional[int] = None - nm_id_hospital: OptionalStr = None - nm_nota_previa_id: OptionalStr = None - nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None - nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None - nm_fecha: FlexDate = None - nm_edad_meses: Optional[float] = None - nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None - nm_medico_tratante: OptionalStr = None - nm_motivo_consulta: OptionalStr = None - nm_interrogatorio: OptionalStr = None - nm_regresion_referida: Optional[int] = None - nm_antecedente_familiar_tea: Optional[int] = None - nm_perimetro_cefalico: Optional[float] = None - nm_diagnostico_texto: OptionalStr = None - nm_cie_codigo: OptionalStr = None - nm_cie_descripcion: OptionalStr = None - nm_tratamiento_texto: OptionalStr = None - nm_receta: OptionalStr = None - nm_plan_estudios: OptionalStr = None - nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None - nm_observaciones: OptionalStr = None - nm_masa_corporal: Optional[float] = None - nm_talla: Optional[float] = None - nm_imc_visita: Optional[float] = None - nm_frecuencia_cardiaca: Optional[int] = None - nm_frecuencia_respiratoria: Optional[int] = None - nm_presion_arterial_sistolica: Optional[int] = None - nm_presion_arterial_diastolica: Optional[int] = None - nm_temperatura: Optional[float] = None - nm_pdf_ruta: OptionalStr = None diff --git a/webapi/imports/schemas/tea/ordenes_estudio.py b/webapi/imports/schemas/tea/ordenes_estudio.py index cbe6714..72c18ae 100644 --- a/webapi/imports/schemas/tea/ordenes_estudio.py +++ b/webapi/imports/schemas/tea/ordenes_estudio.py @@ -1,37 +1,17 @@ -"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like -TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded.""" +"""Import schema for `core.tea.models.OrdenesEstudio`: the order of an ADOS-2, a neuropediatrics note or an EEG.""" from typing import Optional -from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa +from core.tea.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio from webapi.imports.schemas.base import ImportSchema from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId -_ESPECIALIDAD_CATALOG = Catalog(Especialidad) _TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS) -_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio) -_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa) class OrdenesEstudioImportSchema(ImportSchema): # The source's own id, kept so rows that reference it by id still point at this record. ord_id: SourceId = None ord_pac_id: Optional[int] = None - ord_nota_medica_id: OptionalStr = None ord_id_hospital: OptionalStr = None - ord_fecha: FlexDate = None - ord_medico_solicitante: OptionalStr = None - ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None - ord_diagnostico_asignado: OptionalStr = None - ord_cie_asignado: OptionalStr = None - ord_dias_vigencia: Optional[int] = None - ord_fecha_vencimiento: FlexDate = None ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None - ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None - ord_fecha_realizacion: FlexDate = None - ord_fecha_resultado: FlexDate = None - ord_dias_espera: Optional[int] = None - ord_proveedor: OptionalStr = None - ord_edad_meses: Optional[float] = None - ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None - ord_pdf_ruta: OptionalStr = None - ord_observaciones: OptionalStr = None + ord_fecha: FlexDate = None diff --git a/webapi/imports/schemas/tea/pacientes.py b/webapi/imports/schemas/tea/pacientes.py index 5b899d0..c4c110c 100644 --- a/webapi/imports/schemas/tea/pacientes.py +++ b/webapi/imports/schemas/tea/pacientes.py @@ -1,24 +1,14 @@ -"""Import schema for `core.tea.models.Pacientes`. All fields optional, like TEA's -Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are excluded. +"""Import schema for `core.tea.models.Pacientes`. -`pac_id` is importable: every other TEA table references the patient by the -source system's integer id, so it has to be kept, not renumbered.""" +`pac_id` is importable: every other TEA table references the patient by the source system's integer id, so it is +kept, not renumbered.""" from typing import Optional -from core.tea.enums import Parentesco, SexoBiologico from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr - -_SEXO_CATALOG = Catalog(SexoBiologico) -_PARENTESCO_CATALOG = Catalog(Parentesco) +from webapi.imports.schemas.coercion import FlexDate, OptionalStr class PacientesImportSchema(ImportSchema): pac_id: Optional[int] = None pac_id_hospital: OptionalStr = None - pac_id_titular: OptionalStr = None - pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None pac_fecha_nacimiento: FlexDate = None - pac_sexo: CatalogValue(_SEXO_CATALOG) = None - pac_codigo_postal_vigente: OptionalStr = None - pac_dependencia: OptionalStr = None diff --git a/webapi/imports/schemas/tea/parto_neonatal.py b/webapi/imports/schemas/tea/parto_neonatal.py deleted file mode 100644 index 29274ec..0000000 --- a/webapi/imports/schemas/tea/parto_neonatal.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Import schema for `core.tea.models.PartoNeonatal`. All fields optional, like -TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - ClasificacionEdadGestacional, - ComplicacionIntraparto, - FuenteAntecedenteNeonatal, - TamanoParaEdadGestacional, - TipoParto, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr - -_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal) -_TIPO_PARTO_CATALOG = Catalog(TipoParto) -_COMPLICACION_INTRAPARTO_CATALOG = Catalog(ComplicacionIntraparto) -_CLASIFICACION_EDAD_GESTACIONAL_CATALOG = Catalog(ClasificacionEdadGestacional) -_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG = Catalog(TamanoParaEdadGestacional) - - -class PartoNeonatalImportSchema(ImportSchema): - pnn_pac_id: Optional[int] = None - pnn_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_NEONATAL_CATALOG) = None - pnn_tipo_parto: CatalogValue(_TIPO_PARTO_CATALOG) = None - pnn_complicaciones_intraparto: Optional[int] = None - pnn_complicacion_tipo: CatalogValue(_COMPLICACION_INTRAPARTO_CATALOG) = None - pnn_peso_nacer_g: Optional[int] = None - pnn_talla_nacer_cm: Optional[float] = None - pnn_perimetro_cefalico_nacer_cm: Optional[float] = None - pnn_edad_gestacional_sem: Optional[float] = None - pnn_clasificacion_eg: CatalogValue(_CLASIFICACION_EDAD_GESTACIONAL_CATALOG) = None - pnn_tamano_para_eg: CatalogValue(_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG) = None - pnn_peso_nacer_zscore: Optional[float] = None - pnn_apgar_1min: Optional[int] = None - pnn_apgar_5min: Optional[int] = None - pnn_ingreso_ucin: Optional[int] = None - pnn_dias_ucin: Optional[int] = None - pnn_encefalopatia_hipoxico_isquemica: Optional[int] = None - pnn_hipotermia_nacer: Optional[int] = None - pnn_hiperbilirrubinemia: Optional[int] = None - pnn_fototerapia: Optional[int] = None - pnn_hipoglucemia_neonatal: Optional[int] = None - pnn_anoxia: Optional[int] = None - pnn_sindrome_congenito: Optional[int] = None - pnn_sindrome_congenito_desc: OptionalStr = None - pnn_flag_riesgo_neonatal: Optional[int] = None - pnn_observaciones: OptionalStr = None - pnn_ocr_confianza: Optional[float] = None - pnn_nlp_version: OptionalStr = None diff --git a/webapi/imports/schemas/tea/potenciales_evocados_auditivos.py b/webapi/imports/schemas/tea/potenciales_evocados_auditivos.py deleted file mode 100644 index e71e09e..0000000 --- a/webapi/imports/schemas/tea/potenciales_evocados_auditivos.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields -optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded.""" -from typing import Optional - -from core.tea.enums import GradoHipoacusia -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr - -_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia) - - -class PotencialesEvocadosAuditivosImportSchema(ImportSchema): - pea_ord_id: OptionalStr = None - pea_pac_id: Optional[int] = None - pea_fecha_estudio: FlexDate = None - pea_medico_interpreta: OptionalStr = None - pea_umbral_od: Optional[int] = None - pea_umbral_oi: Optional[int] = None - pea_latencia_v_od: Optional[float] = None - pea_latencia_v_oi: Optional[float] = None - pea_interpico_i_v_od: Optional[float] = None - pea_interpico_i_v_oi: Optional[float] = None - pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None - pea_conclusion_texto: OptionalStr = None - pea_flag_diferencial_auditivo: Optional[int] = None - pea_ocr_confianza: Optional[float] = None diff --git a/webapi/metrics.py b/webapi/metrics.py index 23b3574..7baf63c 100644 --- a/webapi/metrics.py +++ b/webapi/metrics.py @@ -30,6 +30,7 @@ from sqlalchemy import ( case, cast, column, + desc, distinct, func, literal, @@ -37,6 +38,7 @@ from sqlalchemy import ( select, table, text, + true, ) AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read @@ -45,6 +47,8 @@ NO_DATA = "sin_dato" AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo" TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" OF_THE_CHOSEN = "del_elegido" +COLUMN = "columna" +STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo" class UndecidedRule(ValueError): @@ -56,7 +60,8 @@ class Population: """A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates. `dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the - dates the knowledge cut-off applies to. + dates the knowledge cut-off applies to. `at_end`, with a status at the period's end: dates that must have (or must + not have) been reached by the period's end, each with when it became known. """ metric: str @@ -65,6 +70,53 @@ class Population: codes: tuple[str, ...] dated_at: tuple[str, ...] known_at: tuple[str, ...] + at_end: tuple["ReachedByEnd", ...] = () + + +@dataclasses.dataclass(frozen=True) +class ReachedByEnd: + """A date reached by the period's end (`reached`) or not: dated before the period's end and the event cut-off, + and known by the knowledge cut-off.""" + + date: str + known_at: str | None + reached: bool + + +@dataclasses.dataclass(frozen=True) +class StatusAtEnd: + """Who a period counts and with which row: every unit that entered (`entry`) on or before the period's end and + hadn't left (`exit`, known at `exit_known`) before its start, whether or not it has a fact in the period. Each + unit is counted with its row of highest `order` dated on or before the period's end (its status then) and known + by the cut-offs (`known_at`). With no `order`, the model has one row per unit.""" + + entry: str + exit: str + exit_known: str | None + order: str | None + known_at: tuple[str, ...] + + @classmethod + def of(cls, spec: dict | None) -> "StatusAtEnd | None": + if spec is None: + return None + if spec["tipo"] != STATUS_AT_PERIOD_END: + raise NotImplementedError(f"populations of kind {spec['tipo']!r} aren't answered") + return cls(spec["ingreso"], spec["salida"], spec.get("salida_conocida_en"), spec.get("orden"), + tuple(spec.get("conocida_en", ()))) + + def columns(self) -> set[str]: + return {self.entry, self.exit, *((self.exit_known,) if self.exit_known else ()), + *((self.order,) if self.order else ()), *self.known_at} + + +@dataclasses.dataclass(frozen=True) +class Group: + """One of several groups of a measure: its numerator is the measure's own with this filter instead.""" + + name: str + label: str + filter_sql: str @dataclasses.dataclass(frozen=True) @@ -76,7 +128,8 @@ class Stratum: `fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a timeline `tipo` to whether there was one; - - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category. + - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category; + - `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null. """ name: str @@ -89,7 +142,7 @@ class Stratum: @classmethod def of(cls, name: str, spec: dict) -> "Stratum": - if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN): + if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN, COLUMN): raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered") return cls(name, spec["tipo"], spec) @@ -112,11 +165,26 @@ class MeasureDefinition: rules: dict[str, str] strata: tuple[Stratum, ...] improvement_notation: str | None = None + population: StatusAtEnd | None = None + groups: tuple[Group, ...] = () + exclusion: Population | None = None + meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) @property def measure_id(self) -> str: return self.url.rsplit("/", 1)[-1] + def for_group(self, group: Group) -> "MeasureDefinition": + """The definition as one of its groups: the denominator's units, filtered by the group.""" + numerator = dataclasses.replace(self.denominator, metric=f"{self.numerator.metric}:{group.name}", + codes=self.numerator.codes, filter_sql=_both(self.denominator.filter_sql, + group.filter_sql)) + return dataclasses.replace(self, numerator=numerator, group=group.name, groups=(), strata=(), exclusion=None) + + +def _both(first: str | None, second: str | None) -> str | None: + return " and ".join(f"({c})" for c in (first, second) if c) or None + def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]: """The ratio metrics of the manifest that declare a `measure_url`, by that url.""" @@ -143,10 +211,20 @@ def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]: group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), improvement_notation=meta.get("improvement_notation"), + population=StatusAtEnd.of(meta.get("poblacion")), + groups=tuple(Group(g["grupo"], g.get("etiqueta", g["grupo"]), _unraw(g["filtro"])) + for g in meta.get("grupos", ())), + exclusion=_population(metrics[meta["exclusion"]], model) if "exclusion" in meta else None, + meta=meta, ) return definitions +def _unraw(template: str) -> str: + """A `meta` template as written, without the `{% raw %}` that keeps dbt from rendering it.""" + return template.replace("{% raw %}", "").replace("{% endraw %}", "") + + def _semantic_model_of(metric: dict, semantic: dict) -> dict: measure = metric["type_params"]["measure"]["name"] for model in semantic.values(): @@ -167,6 +245,8 @@ def _population(metric: dict, model: dict) -> Population: filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None, codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())), known_at=tuple(meta.get("conocida_en", ())), + at_end=tuple(ReachedByEnd(a["fecha"], a.get("conocida_en"), bool(a.get("alcanzada", True))) + for a in meta.get("al_fin", ())), ) @@ -195,12 +275,20 @@ class MeasureQueries: names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr} # When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in. known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at} + known |= {definition.dimensions[a.known_at] for p in (definition.numerator, definition.denominator) + for a in p.at_end if a.known_at} for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)): known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())} + self.status = getattr(definition, "population", None) + if self.status is not None: + names |= {definition.dimensions[n] for n in self.status.columns()} + known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n} self.events = table(definition.relation, *( column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) if name.isidentifier())) self.periods = period_table + if self.status is not None: + self.events = self._status_rows() self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio") self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD)) @@ -223,9 +311,56 @@ class MeasureQueries: if self.q.knowledge_cutoff is not None: conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at] conditions += [self._column(name).is_not(None) for name in population.known_at] + for date in population.at_end: + reached = self._reached_by_end(date.date, date.known_at) + conditions.append(reached if date.reached else case((reached, 0), else_=1) == 1) return and_(*conditions) if conditions else None + def _reached_by_end(self, date: str, known_at: str | None): + """The date is reached by the period's end: dated before it and by the event cut-off, known by the + knowledge cut-off. Only with a status at the period's end, whose rows carry the period's bounds.""" + if self.status is None: + raise ValueError(f"{self.d.url}: `al_fin` needs a population at the period's end") + value = self._column(date) + conditions = [value.is_not(None), value < self.events.c.periodo_fin] + if self.q.event_cutoff is not None: + conditions.append(value <= self.q.event_cutoff.isoformat()) + if known_at is not None and self.q.knowledge_cutoff is not None: + conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff] + return and_(*conditions) + + def _status_rows(self): + """Each unit the period counts, with its row of highest order: a subquery with the model's name, so the + rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds. + + A unit is in when it entered by the period's end and hadn't left before its start; a later exit, or one not + yet dated or known by the cut-offs, doesn't count. Its rows are those dated before the period's end and by + the event cut-off, and known by the knowledge cut-off. + """ + rule, base, p = self.status, self.events, self.periods.c + col = lambda name: base.c[self.d.dimensions[name]] # noqa: E731 + when, unit = base.c[self.d.time_dimension], base.c[self.d.numerator.measure_expr] + conditions = [p.periodo_id == self.q.period_id, when.is_not(None), when < p.fin, col(rule.entry) < p.fin] + left = [col(rule.exit).is_not(None), col(rule.exit) < p.inicio] + if self.q.event_cutoff is not None: + conditions.append(when <= self.q.event_cutoff.isoformat()) + left.append(col(rule.exit) <= self.q.event_cutoff.isoformat()) + if self.q.knowledge_cutoff is not None: + conditions += [col(n) <= self.q.knowledge_cutoff for n in rule.known_at] + if rule.exit_known: + left += [col(rule.exit_known).is_not(None), col(rule.exit_known) <= self.q.knowledge_cutoff] + conditions.append(case((and_(*left), 1), else_=0) == 0) + order = [desc(col(rule.order))] if rule.order else [desc(when)] + ranked = (select(*base.c, p.periodo_id.label("periodo_id"), p.inicio.label("periodo_inicio"), + p.fin.label("periodo_fin"), + func.row_number().over(partition_by=unit, order_by=order).label("lugar_al_fin")) + .select_from(base.join(self.periods, true())).where(*conditions).subquery("al_fin_del_periodo")) + return (select(*(c for c in ranked.c if c.name != "lugar_al_fin")).where(ranked.c.lugar_al_fin == 1) + .subquery(self.d.relation)) + def _in_question(self): + if self.status is not None: + return self.events.c.periodo_id == self.q.period_id when, p = self.events.c[self.d.time_dimension], self.periods.c conditions = [p.periodo_id == self.q.period_id] if self.q.event_cutoff is not None: @@ -233,12 +368,16 @@ class MeasureQueries: return and_(*conditions) def _from(self, *, with_strata: bool): + if self.status is not None: + if with_strata and any(s.kind not in (COLUMN, OF_THE_CHOSEN) for s in self.d.strata): + raise NotImplementedError(f"{self.d.url}: a status at the period's end takes column strata only") + return self.events when, p = self.events.c[self.d.time_dimension], self.periods.c joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin)) if not with_strata: return joined for stratum in self.d.strata: - if stratum.kind == OF_THE_CHOSEN: + if stratum.kind in (OF_THE_CHOSEN, COLUMN): continue if stratum.kind == AGE_AT_PERIOD_START: joined = (joined @@ -283,6 +422,8 @@ class MeasureQueries: return func.coalesce(self.age_groups.c.etiqueta, NO_DATA) if stratum.kind == OF_THE_CHOSEN: return self._column(stratum.spec["valor"]) + if stratum.kind == COLUMN: + return func.coalesce(self._column(stratum.spec["columna"]), NO_DATA) had = self._timeline(stratum).c def holds(alternative: dict): @@ -306,9 +447,15 @@ class MeasureQueries: return (select(value, *self._cells()).select_from(self._from(with_strata=True)) .where(self._in_question()).group_by(value)) + def excluded(self) -> Select: + """The units of the measure's exclusion (`meta.exclusion`): in the period, but out of its denominator.""" + unit, condition = self.events.c[self.d.exclusion.measure_expr], self._filter(self.d.exclusion) + counted = unit if condition is None else case((condition, unit)) + return select(func.count(distinct(counted))).select_from(self._from(with_strata=False)).where(self._in_question()) + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: """What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum.""" - for population in (self.d.denominator, self.d.numerator): + for population in (self.d.denominator, self.d.numerator, *((self.d.exclusion,) if self.d.exclusion else ())): unit = self.events.c[population.measure_expr] condition = self._filter(population) where = self._in_question() if condition is None else and_(self._in_question(), condition) @@ -372,6 +519,8 @@ class Answer: total: Counts strata: dict[str, dict[str, Counts]] stored_before: bool + groups: dict[str, Counts] = dataclasses.field(default_factory=dict) # by group, for a measure with several + excluded: int | None = None # the units of its exclusion, when it has one @property def numerator(self) -> int: @@ -397,7 +546,8 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p key, key_sha = key_of(definition, question, values) stored = history.find(definition.url, key_sha) if stored is not None: - return _from_counts(definition, stored, history.counts(stored)) + return _from_counts(definition, stored, history.counts(stored), + history.group_counts(stored) if definition.groups else {}) period = periods.get(question.period_id) if period is None: @@ -408,6 +558,13 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p for stratum in definition.strata: _, cells = queries.rows(sql.counts_by_stratum(stratum)) strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells} + excluded = queries.rows(sql.excluded())[1][0][0] if definition.exclusion else None + group_sql, groups = [], {} + for group in definition.groups: + g = MeasureQueries(definition.for_group(group), question, values, periods.model.__table__) + _, ((n, d),) = queries.rows(g.counts()) + groups[group.name] = Counts(n, d) + group_sql.append(g) models = import_module(f"core.{project}.indicadores.models") (any_rule,) = parameters.list(limit=1) report = models.MeasureReport( @@ -418,15 +575,21 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), agregacion_version=AGGREGATION_VERSION, huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted( - (s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode() + (s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items()), + excluded, sorted((g, c.numerator, c.denominator) for g, c in groups.items())]).encode() ).hexdigest(), ) - report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, - models.MeasureReportUnidadEstrato)) - return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False) + + def rows(rid): + for queries_of in (sql, *group_sql): + yield from queries_of.rows(rid, models.MeasureReportUnidad, models.MeasureReportUnidadEstrato) + + report_id = history.record(report, rows) + return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False, groups=groups, + excluded=excluded) -def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer: +def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by_group: dict | None = None) -> Answer: numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0], definition.denominator.codes[0])) cells: dict[tuple[str, str], list[int]] = {} @@ -440,7 +603,19 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> for (stratum, value), (n, d) in cells.items(): if stratum != TOTAL: strata.setdefault(stratum, {})[value] = Counts(n, d) - return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True) + excluded = None + if definition.exclusion is not None: + code = f"{definition.measure_id}.{definition.exclusion.codes[0]}" + excluded = sum(n for (stratum, _, resultado, _), n in counts.items() if stratum == TOTAL and resultado == code) + groups = {} + if definition.groups: + by_group = by_group or {} + groups = {g.name: Counts(by_group.get((g.name, numerator), 0), by_group.get((g.name, denominator), 0)) + for g in definition.groups} + totals = Counts(by_group.get((definition.group, numerator), 0), by_group.get((definition.group, denominator), 0)) + else: + totals = Counts(*cells.get((TOTAL, TOTAL), (0, 0))) + return Answer(report_id, totals, strata, stored_before=True, groups=groups, excluded=excluded) # --- the contract -------------------------------------------------------------------------------------------------- diff --git a/webapi/orchestration/__main__.py b/webapi/orchestration/__main__.py index b6dca89..f45d65e 100644 --- a/webapi/orchestration/__main__.py +++ b/webapi/orchestration/__main__.py @@ -15,7 +15,7 @@ from pathlib import Path from webapi.orchestration.context import Context from webapi.orchestration.runner import run -PROJECTS = ("cacu", "cama") +PROJECTS = ("cacu", "cama", "tea") def main(argv: list[str] | None = None) -> None: diff --git a/webapi/orchestration/reference/parametros.toml b/webapi/orchestration/reference/parametros.toml index 776275d..f55b478 100644 --- a/webapi/orchestration/reference/parametros.toml +++ b/webapi/orchestration/reference/parametros.toml @@ -51,12 +51,6 @@ valor = 1 estado = "provisional" fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)" -[tea.riesgos.horizonte_banda] -# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses). -valor = 4 -estado = "provisional" -fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)" - [comun.catalogos.banda_riesgo] # Las bandas del resumen de riesgos, de menor a mayor. valor = [ @@ -90,10 +84,10 @@ estado = "provisional" fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar" # =========================================================================== -# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8) +# TEA · the screening's indicators (M21 to M30) # -# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la -# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses". +# The key is the dotted path: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses". +# The measures read their rules from dbt's var `tea` (Transformation/dbt_project.yml), which holds the same values. # Las listas y tablas se guardan en def_parametro como JSON. # El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga. # Documentos citados (repositorio analisis-tea, carpeta docs/): @@ -102,9 +96,10 @@ fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-1 # =========================================================================== [tea.cohorte.edad_min_meses] +# The cohort: children whose first M-CHAT was at 16 to 36 completed months. valor = 16 estado = "confirmado" -fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)" +fuente = "Responsable del proyecto, 2026-11-11: edad cumplida al primer M-CHAT, de 16 a 36 meses" [tea.cohorte.edad_max_meses] valor = 36 @@ -117,97 +112,23 @@ valor = 30.4375 estado = "confirmado" fuente = "analisis-tea/tea/comun.py, edad_meses" -[tea.cohorte.plazo_ados2_eeg_dias] -# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo. -valor = 30 -estado = "confirmado" -fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)" - [tea.cohorte.ventanas] -# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos. +# Age groups, by completed months at the first M-CHAT, without gaps: the windows of the TEA page. valor = [ - { clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" }, - { clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" }, - { clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" }, + { clave = "16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" }, + { clave = "24_29", desde = 24, hasta = 29, etiqueta = "24 a 29 meses", color = "#5E93CC" }, + { clave = "30_36", desde = 30, hasta = 36, etiqueta = "30 a 36 meses", color = "#1B4A80" }, ] estado = "confirmado" -fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)" - -[tea.instrumentos.informantes_ramos] -# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre. -valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"] -estado = "confirmado" -fuente = "contexto §1 (equipo); psicología no registra al cuidador principal" - -[tea.instrumentos.informantes_otros] -valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"] -estado = "confirmado" -fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21" - -[tea.ramos.areas] -# «TOTAL» no cuenta como área. -valor = [ - { clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" }, - { clave = "LINGUISTICO", etiqueta = "Lingüístico" }, - { clave = "FISICO", etiqueta = "Físico" }, - { clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" }, - { clave = "ADAPTATIVO", etiqueta = "Adaptativo" }, -] -estado = "confirmado" -fuente = "spec v2, catálogo de ins_area; contexto §1" - -[tea.poblacion.css_min_tea] -# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor. -valor = 3 -estado = "confirmado" -fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo" +fuente = "Responsable del proyecto, 2026-11-10: las ventanas de la página de TEA. Colores: paleta de ejemplo (provisional)" [tea.diagnostico.cie_tea] -# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840). +# M21 to M25: ICD-10 codes of the neuropediatrics note that confirm the diagnosis, without the dot (F84.0 -> F840). +# F84 without its subcode doesn't count. valor = ["F840"] estado = "confirmado" fuente = "usuario (2026-10-15): solo F84.0 (autismo)" -[tea.diagnostico.instrumentos_mchat] -# M25: valores de psi_instrumento_tamizaje que son un M-CHAT. -valor = ["M_CHAT_R", "M_CHAT_RF"] -estado = "confirmado" -fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)" - -[tea.atencion.plazo_referencia_evaluacion_dias] -# K1: inicio de la evaluación a más tardar este número de días después de la referencia. -valor = 90 -estado = "confirmado" -fuente = "estandares: NICE QS51, enunciado 1 (3 meses)" - -[tea.parto.apgar_corte] -# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10). -valor = 7 -estado = "confirmado" -fuente = "lista, M17: menor de 7, 7, y 8 a 10" - -# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar: -# un cambio pide volver a cargar. -[tea.antecedentes_maternos.no_registrado] -valor = "NO_REGISTRADO" -estado = "confirmado" -fuente = "spec v2: NO_REGISTRADO = sin dato" - -[tea.antecedentes_maternos.hipertension_ninguno] -valor = "NINGUNO" -estado = "confirmado" -fuente = "spec v2, catálogo de amg_hipertension_preeclampsia" - -[tea.antecedentes_maternos.embarazo_no_unico] -valor = ["GEMELAR", "TRIPLE_O_MAS"] -estado = "confirmado" -fuente = "spec v2, catálogo de amg_embarazo_multiple" - -[tea.antecedentes_maternos.liquido_anormal] -valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"] -estado = "confirmado" -fuente = "spec v2, catálogo de amg_liquido_amniotico" - [tea.supresion.activa] # Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se # suprime nada, aunque comun.umbral_supresion tenga valor. @@ -232,54 +153,6 @@ valor = { etiqueta = "Sin dato", color = "#C9CDD2" } estado = "confirmado" fuente = "lista: «sin dato» siempre se muestra como categoría propia" -[tea.catalogos.sexo] -valor = [ - { clave = "F", etiqueta = "Femenino", color = "#E0A030" }, - { clave = "M", etiqueta = "Masculino", color = "#2F6DB3" }, - { clave = "I", etiqueta = "Indeterminado", color = "#8A9199" }, -] -estado = "provisional" -fuente = "spec v2, pac_sexo; colores provisionales" - -[tea.catalogos.resultado_mchat] -valor = [ - { clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" }, - { clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" }, - { clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" }, -] -estado = "provisional" -fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales" - -[tea.catalogos.interpretacion_ramos] -valor = [ - { clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" }, - { clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" }, - { clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" }, -] -estado = "provisional" -fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales" - -[tea.catalogos.grado_hipoacusia] -valor = [ - { clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" }, - { clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" }, - { clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" }, - { clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" }, - { clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" }, - { clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" }, -] -estado = "provisional" -fuente = "spec v2, pea_grado_hipoacusia; colores provisionales" - -[tea.catalogos.apgar_5min] -valor = [ - { clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" }, - { clave = "SIETE", etiqueta = "7", color = "#E8C28E" }, - { clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" }, -] -estado = "provisional" -fuente = "lista, M17; colores provisionales" - # =========================================================================== # CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml) # =========================================================================== diff --git a/webapi/orchestration/semantic_layer.py b/webapi/orchestration/semantic_layer.py index 9642c57..3ba3604 100644 --- a/webapi/orchestration/semantic_layer.py +++ b/webapi/orchestration/semantic_layer.py @@ -25,8 +25,9 @@ def event_views(manifest: Path, project: str) -> list: """`drop view if exists` and `create view … as ` for every model the project's measures read, parents first. - Those are the project's models semantic models count over (`models//…`) and the timelines its strata - read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined + Those are the project's models semantic models count over (`models//…`), the timelines its strata + read (`meta.estratos.*.linea`) and the views the WebApi reads (`meta.lee_la_webapi`), with the non-ephemeral + models they're built on; an ephemeral one is already inlined in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here. """ m = json.loads(manifest.read_text(encoding="utf-8")) @@ -37,6 +38,9 @@ def event_views(manifest: Path, project: str) -> list: roots |= {by_name[spec["linea"]] for metric in m["metrics"].values() if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/") for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec} + # The views the WebApi reads directly (a follow-up list, a patient summary). + roots |= {uid for uid, n in nodes.items() if n["resource_type"] == "model" and n["fqn"][1] == project + and n["config"].get("meta", {}).get("lee_la_webapi")} ordered: list[str] = [] def visit(uid: str) -> None: @@ -69,10 +73,14 @@ def catalog_layers(project: str, manifest: Path) -> list[list]: contract = CONTRACTS[scoring_of(d)] measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric], contrato=contract, unidad=d.basis)) - codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()))) + exclusion = getattr(d, "exclusion", None) + codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()), + *(exclusion.codes if exclusion else ()))) children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c, etiqueta=c) for c in codes] children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0)) + children += [t.CatMeasureGrupo(measure_id=d.measure_id, grupo=g.name, etiqueta=g.label, orden=i) + for i, g in enumerate(getattr(d, "groups", ()), 1)] children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata] stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata] return [stratum_rows + measures, children] diff --git a/webapi/orchestration/silver/procedures.py b/webapi/orchestration/silver/procedures.py index 9946a2d..1412ad8 100644 --- a/webapi/orchestration/silver/procedures.py +++ b/webapi/orchestration/silver/procedures.py @@ -14,6 +14,7 @@ llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`, from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field +from types import SimpleNamespace from typing import NamedTuple from webapi.orchestration.reference.catalogs import Catalogo @@ -59,6 +60,16 @@ class Hija: resultados: Mapping[str, str] = field(default_factory=dict) +@dataclass(frozen=True) +class Junta: + """Another staging row whose columns the row's content takes: the row of `staging` whose `llave` equals the + row's column `columna` (an electrode value takes its metric's code and EEG). Without a match, they're null.""" + + staging: type + llave: str + columna: str + + @dataclass(frozen=True) class DeStaging: """Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c). @@ -72,6 +83,10 @@ class DeStaging: no es un reporte); no es un descarte. - `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en `descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging. + - `juntas`: rows of other staging tables whose columns join the content before the derived ones. + - `observa_en`: the row gives no procedure of its own; its observations go on the procedure this parent key + names (a metric of an EEG is a result of the EEG's recording). `clase` is unused then. + A result's template can name the content's columns (`eeg.{metrica}`) besides `{estudio}`. Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada. Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17). @@ -92,6 +107,8 @@ class DeStaging: paciente: str | None = "pac_id" solo_si: Callable | None = None descartar: Callable | None = None + juntas: tuple[Junta, ...] = () + observa_en: Padre | None = None class LotePlata(NamedTuple): @@ -124,6 +141,7 @@ def plata_desde_staging( pacientes = set(pacientes) tipos, vigentes = _tipos_y_vigentes(catalogo) procedimientos, observaciones, descartes = [], [], {} + indices: dict[tuple[str, str], dict] = {} for c in correspondencias: tabla = c.staging.__tablename__ for fila in filas.get(tabla, ()): @@ -133,7 +151,13 @@ def plata_desde_staging( continue if c.solo_si is not None and not c.solo_si(fila): continue - contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}} + contenido = fila.model_dump() + if c.juntas: + for junta in c.juntas: + unida = _junta(junta, filas, indices).get(contenido.get(junta.columna)) + contenido = {**(unida or dict.fromkeys(junta.staging.model_fields)), **contenido} + fila = SimpleNamespace(**contenido) + contenido = {**contenido, **{nombre: f(fila) for nombre, f in c.derivadas.items()}} contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente) contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()}) _repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital, @@ -168,6 +192,14 @@ def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]: return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3]))) +def _junta(junta: Junta, filas: Mapping[str, Iterable], indices: dict) -> dict: + """The rows of the joined table by their key, as dictionaries; built once per batch.""" + clave = (junta.staging.__tablename__, junta.llave) + if clave not in indices: + indices[clave] = {getattr(f, junta.llave): f.model_dump() for f in filas.get(clave[0], ())} + return indices[clave] + + def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]: tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados} vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"} @@ -183,6 +215,11 @@ def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, col motivo = f"{nombre}: {c.estudio_de} fuera de catálogo" descartes[motivo] = descartes.get(motivo, 0) + 1 return + if c.observa_en is not None: + dueno = _parent(c.observa_en, contenido) + if dueno is not None: + observaciones += _observaciones(dueno, contenido, c.resultados, c.fuentes, tipos, vigentes) + return llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase) procedimientos.append({ "llave": llave, @@ -225,7 +262,9 @@ def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str], tipos: dict, vigentes: set) -> list[dict]: filas = [] for columna, plantilla in resultados.items(): - resultado_id = plantilla.format(estudio=llave[2]) + resultado_id = plantilla.format_map({**contenido, "estudio": llave[2]}) + if resultado_id not in tipos and "{" in plantilla.replace("{estudio}", ""): + continue # a value of the row names a result the catalog doesn't have (an unknown metric) filas.append({ "procedimiento": llave, "pac_id": contenido.get("pac_id"), diff --git a/webapi/orchestration/silver/tea.py b/webapi/orchestration/silver/tea.py new file mode 100644 index 0000000..10b58fb --- /dev/null +++ b/webapi/orchestration/silver/tea.py @@ -0,0 +1,120 @@ +"""TEA in the two-table silver: what each staging row gives, as `DESDE_STAGING` (read by `carga_desde_staging`). + +- an order is an `orden` of the study it asks for (`ord_tipo_estudio`, in Core's code or one of its aliases); +- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each + hangs from its order when it has one; +- an EEG metric is a result of its EEG's recording, not a procedure; a metric's electrode value is a `parte` of the + EEG (`codigo_fuente` the electrode) with the metric's result. Both find their EEG through the metric's row. +""" + +from core.tea.enums import ( + CLASIFICACION_ADOS2_ALIAS, + TIPO_ESTUDIO_ALIAS, + ClasificacionAdos2, + ModuloAdos2, + TipoEstudio, +) +from core.tea.models import ( + ADOS2_ITEMS, + Ados2, + Eeg, + EegMetrica, + EegMetricaElectrodo, + EvaluacionNeuropediatrica, + Mchat, + OrdenesEstudio, + Pacientes, +) + +from webapi.orchestration.silver.procedures import DeStaging, Junta, Padre +from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio + +PACIENTES = Pacientes # where persons come from +ORDENES = OrdenesEstudio.__tablename__ +EEG = Eeg.__tablename__ + + +def _codigo(columna: str, enum, alias: dict | None = None): + codigos = {e.value for e in enum} + return lambda f: codigo_de_especialidad(getattr(f, columna), alias or {}, codigos) + + +def _su_orden(estudio_id: str, columna: str) -> Padre: + """The order a study row names by its `*_ord_id`.""" + return Padre(estudio_id=estudio_id, clase="orden", fuente_id=columna, tabla=ORDENES) + + +def _metrica(f) -> str | None: + """A metric's result in the catalog: its code in lower case (`RITMO_POSTERIOR` -> `ritmo_posterior`).""" + codigo = texto_limpio(f.met_codigo) + return None if codigo is None else codigo.lower() + + +SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG) + + +DESDE_STAGING = ( + DeStaging( + OrdenesEstudio, "ord_id", "orden", estudio_de="tipo_estudio", fecha="ord_fecha", paciente="ord_pac_id", + derivadas={ + "tipo_estudio": _codigo("ord_tipo_estudio", TipoEstudio, TIPO_ESTUDIO_ALIAS), + "intencion": lambda f: INTENCION, + }, + columnas={"id_hospital": "ord_id_hospital", "codigo_fuente": "ord_tipo_estudio"}, + resultados={"intencion": "orden.intencion"}, + ), + DeStaging( + Mchat, "mch_id", "toma", estudio_id="mchat", fecha="mch_fecha", paciente="mch_pac_id", + padres=(_su_orden("mchat", "mch_ord_id"),), + resultados={"mch_puntaje": "mchat.puntaje"}, + ), + DeStaging( + Ados2, "ado_id", "encuentro", estudio_id="ados2", fecha="ado_fecha", paciente="ado_pac_id", + padres=(_su_orden("ados2", "ado_ord_id"),), + derivadas={ + "modulo": _codigo("ado_modulo", ModuloAdos2), + "clasificacion": _codigo("ado_clasificacion", ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS), + "algoritmo": lambda f: texto_limpio(f.ado_algoritmo), + }, + resultados={ + "modulo": "ados2.modulo", + "algoritmo": "ados2.algoritmo", + "clasificacion": "ados2.clasificacion", + "ado_css": "ados2.css", + **{f"ado_{item}": f"ados2.{item}" for item in ADOS2_ITEMS}, + }, + fuentes={"modulo": "ado_modulo", "clasificacion": "ado_clasificacion"}, + ), + DeStaging( + EvaluacionNeuropediatrica, "neu_id", "encuentro", estudio_id="evaluacion_neuropediatrica", + fecha="neu_fecha", paciente="neu_pac_id", padres=(_su_orden("evaluacion_neuropediatrica", "neu_ord_id"),), + derivadas={"cie_codigo": lambda f: cie(f.neu_cie_codigo)}, + resultados={"cie_codigo": "evaluacion_neuropediatrica.diagnostico"}, + ), + DeStaging( + Eeg, "eeg_id", "toma", estudio_id="eeg", fecha="eeg_fecha_estudio", paciente="eeg_pac_id", + padres=(_su_orden("eeg", "eeg_ord_id"),), columnas={"id_hospital": "eeg_id_registro_laboratorio"}, + resultados={ + "eeg_con_sueno": "eeg.con_sueno", + "eeg_canales": "eeg.canales", + "eeg_duracion_min": "eeg.duracion_min", + "eeg_canales_amplitud": "eeg.calidad_amplitud", + "eeg_canales_alta_frecuencia": "eeg.calidad_alta_frecuencia", + "eeg_canales_correlacion": "eeg.calidad_correlacion", + "eeg_canales_sin_senal": "eeg.calidad_sin_senal", + "eeg_ruido_linea_db": "eeg.calidad_linea", + }, + ), + DeStaging( + EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG, + derivadas={"metrica": _metrica}, + resultados={"met_valor": "eeg.{metrica}"}, + ), + DeStaging( + EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None, + juntas=(Junta(EegMetrica, "met_id", "mel_met_id"),), padres=(SU_EEG,), + derivadas={"metrica": _metrica}, + columnas={"codigo_fuente": "mel_electrodo"}, + resultados={"mel_valor": "eeg.{metrica}"}, + ), +) diff --git a/webapi/orchestration/tables/__init__.py b/webapi/orchestration/tables/__init__.py index fd15b32..0a14336 100644 --- a/webapi/orchestration/tables/__init__.py +++ b/webapi/orchestration/tables/__init__.py @@ -14,7 +14,7 @@ from importlib import import_module from sqlmodel import SQLModel -PROJECTS = ("cacu", "cama") +PROJECTS = ("cacu", "cama", "tea") @dataclass(frozen=True) diff --git a/webapi/orchestration/tables/tea.py b/webapi/orchestration/tables/tea.py new file mode 100644 index 0000000..3bd5e07 --- /dev/null +++ b/webapi/orchestration/tables/tea.py @@ -0,0 +1,75 @@ +"""TEA's tables: in `Core`, in the domain's registry. + +`TABLAS` is what the shared code receives to work with this project; TEA's person adds nothing (its `sexo` stays null). +""" + +from core.tea.indicadores.models import ( + CatMeasure, + CatMeasureResultado, + CatMeasureValor, + CatMeasureGrupo, + CatEstrato, + CatEstratoValor, + CatMeasureEstrato, + MeasureReportUnidad, + MeasureReportUnidadEstrato, + CatEstudio, + CatResultado, + CatValor, + Observacion, + Procedimiento, + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, + Carga, + DefParametro, + DimFecha, + DimGrupoEdad, + DimPeriodo, + MeasureReport, + PeriodoObservacion, + Persona, +) + +from core.indicadores.cohortes import TablasCohorte +from webapi.orchestration.tables import TablasKit + +__all__ = ["TABLAS", "COHORTES"] + +TABLAS = TablasKit( + Persona=Persona, + PeriodoObservacion=PeriodoObservacion, + Carga=Carga, + DefParametro=DefParametro, + DimPeriodo=DimPeriodo, + DimFecha=DimFecha, + DimGrupoEdad=DimGrupoEdad, + MeasureReport=MeasureReport, + CatEstudio=CatEstudio, + CatResultado=CatResultado, + CatValor=CatValor, + Procedimiento=Procedimiento, + Observacion=Observacion, + CatMeasure=CatMeasure, + CatMeasureResultado=CatMeasureResultado, + CatMeasureValor=CatMeasureValor, + CatMeasureGrupo=CatMeasureGrupo, + CatEstrato=CatEstrato, + CatEstratoValor=CatEstratoValor, + CatMeasureEstrato=CatMeasureEstrato, + MeasureReportUnidad=MeasureReportUnidad, + MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, +) + +# Cohorts for models and their risk estimates: TEA builds none yet, the tables are the domain's. +COHORTES = TablasCohorte( + CohorteArmado=CohorteArmado, + CohorteMiembro=CohorteMiembro, + CohorteExclusion=CohorteExclusion, + CohorteVariable=CohorteVariable, + EvaluacionRiesgoLote=EvaluacionRiesgoLote, + EvaluacionRiesgo=EvaluacionRiesgo, +) diff --git a/webapi/recomputation.py b/webapi/recomputation.py index 77f4b40..39fda58 100644 --- a/webapi/recomputation.py +++ b/webapi/recomputation.py @@ -26,7 +26,7 @@ from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message -DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes +DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) -- 2.53.0 From 0f9433949fb0e109c4445bcdbdd9c816092e266e Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 12 Nov 2026 19:47:19 -0600 Subject: [PATCH 06/24] TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too --- tests/staging/tea.py | 2 +- tests/test_fhir_tea.py | 10 +++++++ tests/test_tea_measures.py | 56 ++++++++++++++++++++++++++++---------- webapi/fhir/__init__.py | 8 +----- webapi/kpis.py | 23 +++++++++++++--- webapi/metrics.py | 20 ++++++++++++++ 6 files changed, 93 insertions(+), 26 deletions(-) diff --git a/tests/staging/tea.py b/tests/staging/tea.py index 8bb82ce..531b13e 100644 --- a/tests/staging/tea.py +++ b/tests/staging/tea.py @@ -12,7 +12,7 @@ with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first stays at psychology. - 4, H-T04, 39 months: out of the cohort, never counted. - 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in - order, so it stays at M-CHAT. + order, so it stays at M-CHAT and in process. - 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG step is dated by the note, so it reaches EEG on 2 Jun and leaves after June. - 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else. diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py index 03b8789..61533db 100644 --- a/tests/test_fhir_tea.py +++ b/tests/test_fhir_tea.py @@ -82,6 +82,16 @@ def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monke assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} +def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch): + """Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both + with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation.""" + assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()} + assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404 + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()} + assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200 + + def test_a_measure_carries_what_the_page_needs(client): """Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category labels. Fails if the page's catalog fields stop reaching the Measure.""" diff --git a/tests/test_tea_measures.py b/tests/test_tea_measures.py index 6139462..3f1f890 100644 --- a/tests/test_tea_measures.py +++ b/tests/test_tea_measures.py @@ -19,7 +19,7 @@ from sqlmodel import select import staging.tea as fixture from conftest import base_de -from core.tea.models import Eeg, EegMetrica +from core.tea.models import Ados2, Eeg, EegMetrica, Mchat from webapi.compositions import answer_composition, composition_definitions from webapi.durations import answer_duration, duration_definitions from webapi.metrics import Question, answer, measure_definitions @@ -106,9 +106,9 @@ RESULTS = { "2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2}, "2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2}, "2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3}, - "2025-07": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-07": {"EN_PROCESO": 3}, "2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3}, - "2025-S2": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-S2": {"EN_PROCESO": 3}, } @@ -116,18 +116,19 @@ RESULTS = { def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period): """Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note - confirms it in July even without the ADOS-2. Fails if F84 counts as a confirmation or a note without F84.0 counts - as in process.""" + of July doesn't confirm it without the ADOS-2: it stays in process. Fails if F84 counts as a confirmation, if a + note without F84.0 counts as in process, or if a note counts before the psychology step.""" assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period] @pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [ - ("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 1, 3, 1), ("2025-S1", 2, 5, 1), + ("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 0, 3, 1), ("2025-S1", 2, 5, 1), ]) def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator, excluded): """Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion - from April. Fails if the denominator takes the children without TEA or the exclusion stops being counted.""" + from April. In July child 5's F84.0 note, without the ADOS-2, leaves it in process. Fails if the denominator takes + the children without TEA, the exclusion stops being counted, or a note confirms without the psychology step.""" result = proportion(base, manifest, "M24_confirmacion_diagnostico", period) assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded) @@ -142,15 +143,15 @@ def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest): @pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [ - ("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 1, 1), - ("2025-S1", 2, 0, 2), ("2025-S2", 0, 1, 1), + ("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 0, 0), + ("2025-S1", 2, 0, 2), ("2025-S2", 0, 0, 0), ]) def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg, without_eeg, confirmed): """Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG - by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5, confirmed in July, - has a good EEG but no ADOS-2, so its chain never reaches it. Fails if the EEG is read beyond the period's end or - outside the chain.""" + by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5 has a F84.0 note and + a good EEG in July but no ADOS-2, so it isn't confirmed and July has nobody. Fails if the EEG is read beyond the + period's end, or the note or the EEG count outside the chain.""" m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period) m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period) assert (m21.numerator, m21.denominator) == (with_eeg, confirmed) @@ -164,14 +165,14 @@ def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, ("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5), ("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0), ("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5), - ("M25_dias_mchat_diagnostico", "2025-S2", 4, 1, 16.0), + ("M25_dias_mchat_diagnostico", "2025-S2", 4, 0, None), ]) def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period, initial, n, median): """Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval ended by the period's end have days (repeated in each period that counts them), the rest count as without event. In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of - 1 July gives 16 days in the second semester only. Fails if the value is read beyond the period's end or the + 1 July gives no days without the ADOS-2. Fails if the value is read beyond the period's end or the population goes back to the facts in the period.""" result = duration(base, manifest, measure_id, period) assert (result.initial, result.n, result.median) == (initial, n, median) @@ -243,3 +244,30 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest): assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1 finally: base.motor.dispose() + + +def test_a_knowledge_cut_off_keeps_what_was_known_when_an_earlier_fact_arrives_later(tmp_path, manifest): + """Pins down: an answer as of a load doesn't change when a later load brings an earlier-dated fact. A second load + adds an ADOS-2 of 20 Feb for child 3 (its known one is of 28 Feb) and an M-CHAT of 1 Apr for child 7 (its known + one is of 1 May). Asked as of the first load, March still counts child 3 at psychology and May still counts + child 7; asked as of now, child 7 is in the screening from April. Fails if a child's first fact is chosen among + every load's facts and then dropped for being known after the cut-off.""" + base = base_de("tea", tmp_path) + try: + base.run(*UNTIL_MODELS, allow_undecided=True) + with base.motor.begin() as connection: + (first_load,) = connection.execute(text("select max(fin) from carga")).one() + known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc) + with base.staging() as session: + session.add(Ados2(ado_id="ado-3-earlier", ado_pac_id=3, ado_fecha=date(2025, 2, 20), ado_modulo="MODULO_2", + ado_css=2)) + session.add(Mchat(mch_id="mch-7-earlier", mch_pac_id=7, mch_fecha=date(2025, 4, 1), mch_puntaje=7)) + session.commit() + base.run("load", allow_undecided=True) + later = replace(base, ctx=replace(base.ctx, allow_undecided=True)) + for period in ("2025-03", "2025-05"): + assert composition(later, manifest, "M28_casos_por_estado", period, knowledge_cutoff=known) == STAGES[period] + assert composition(later, manifest, "M28_casos_por_estado", "2025-04") == { + "SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2} + finally: + base.motor.dispose() diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index c039626..eaeb72f 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -39,13 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: def definitions() -> dict: """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" - every = {fhir_id(d): d for d in definitions_of(project, manifest).values()} - if project == "tea": - from webapi.fhir.tea import alterations_validated - - if not alterations_validated(): - every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")} - return every + return {fhir_id(d): d for d in definitions_of(project, manifest).values()} def definition_of(measure_id: str): return definitions().get(measure_id.replace("_", "-")) diff --git a/webapi/kpis.py b/webapi/kpis.py index abf497e..61941e8 100644 --- a/webapi/kpis.py +++ b/webapi/kpis.py @@ -10,6 +10,7 @@ durations (`webapi.durations`; without `corte_evento`, the day of the last load) import json from collections.abc import Callable from datetime import date, datetime, timezone +from functools import lru_cache from pathlib import Path from core.indicadores.tipos import FechaHoraUTC @@ -24,28 +25,42 @@ LOADS = table("carga", column("inicio", FechaHoraUTC)) def definitions_of(project: str, manifest: Path) -> dict: - """Every measure the manifest defines for the domain, by its id (the end of its url).""" + """Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for + a validation (`meta.requiere_validacion`) is left out until it's given.""" + return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)} + + +@lru_cache +def _defined(project: str, manifest: Path) -> dict: every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)} return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")} +def _awaits_validation(definition) -> bool: + """TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them.""" + if not definition.meta.get("requiere_validacion"): + return False + from webapi.fhir.tea import alterations_validated + + return not alterations_validated() + + def kpis_blueprint(project: str, repositories, manifest: Path, *, now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: """The blueprint of a domain, to register with `url_prefix="/"`. `repositories` is the domain's `persistance.` module.""" blueprint = Blueprint(f"{project}_kpis", __name__) - definitions = definitions_of(project, manifest) @blueprint.get("/indicadores") def list_kpis(): """The measures answered on request: id, url, version and scoring.""" return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)} - for i, d in sorted(definitions.items())]) + for i, d in sorted(definitions_of(project, manifest).items())]) @blueprint.get("/indicadores/") def get_kpi(measure_id: str): """A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history.""" - definition = definitions.get(measure_id) + definition = definitions_of(project, manifest).get(measure_id) if definition is None: return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404 try: diff --git a/webapi/metrics.py b/webapi/metrics.py index 7baf63c..efb8c65 100644 --- a/webapi/metrics.py +++ b/webapi/metrics.py @@ -49,6 +49,7 @@ TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" OF_THE_CHOSEN = "del_elegido" COLUMN = "columna" STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo" +KNOWN_VERSION = "version_conocida" class UndecidedRule(ValueError): @@ -283,10 +284,15 @@ class MeasureQueries: if self.status is not None: names |= {definition.dimensions[n] for n in self.status.columns()} known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n} + version = (getattr(definition, "meta", None) or {}).get(KNOWN_VERSION) + if version is not None: + known.add(definition.dimensions[version]) self.events = table(definition.relation, *( column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) if name.isidentifier())) self.periods = period_table + if version is not None: + self.events = self._known_version(definition.dimensions[version]) if self.status is not None: self.events = self._status_rows() self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") @@ -329,6 +335,20 @@ class MeasureQueries: conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff] return and_(*conditions) + def _known_version(self, version: str): + """Each unit's rows as they were known at the knowledge cut-off, for a model with one set of rows per unit + and knowledge version (`meta.version_conocida`, the column that dates each version): the unit's latest + version by the cut-off, or its latest of all without one. A subquery with the model's name, read as the + model is.""" + base = self.events + latest = func.rank().over(partition_by=base.c[self.d.numerator.measure_expr], order_by=desc(base.c[version])) + versions = select(*base.c, latest.label("lugar_de_version")) + if self.q.knowledge_cutoff is not None: + versions = versions.where(base.c[version] <= self.q.knowledge_cutoff) + versions = versions.subquery("versiones") + return (select(*(c for c in versions.c if c.name != "lugar_de_version")) + .where(versions.c.lugar_de_version == 1).subquery(self.d.relation)) + def _status_rows(self): """Each unit the period counts, with its row of highest order: a subquery with the model's name, so the rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds. -- 2.53.0 From e19121bc4280acdde10153ec5f93aeaa590b2bb4 Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 13 Nov 2026 15:03:02 -0600 Subject: [PATCH 07/24] TEA: an order carries its study's report as a PDF through the import --- tests/test_new_sources.py | 38 +++++++++++++++++++ webapi/imports/schemas/tea/ordenes_estudio.py | 1 + 2 files changed, 39 insertions(+) diff --git a/tests/test_new_sources.py b/tests/test_new_sources.py index f647c74..d13c862 100644 --- a/tests/test_new_sources.py +++ b/tests/test_new_sources.py @@ -348,3 +348,41 @@ def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client): [row] = mastografia_repository.list(pac_id_hospital="IMG-0001") assert "nódulo circunscrito" in row.mast_interpretacion assert row.mast_dicom_blob.startswith(b"\x89PNG") + + +def test_a_tea_order_keeps_the_pdf_its_sql_source_carries(client, tmp_path): + """Pins down: `ord_pdf_blob` travels with the order from a SQL source into `ordenes_estudio`, byte for + byte, and an order without a file stays without one. The source is a SQLite file in `tmp_path` holding a + two-row `ordenes_estudio`. Fails if the import schema drops the field or the commit rewrites the bytes.""" + report = text_pdf([["EVALUACION PSICOLOGICA", "ADOS-2 Modulo 2"]]) + url = f"sqlite:///{tmp_path / 'hospital.db'}" + table = sa.Table( + "ordenes_estudio", sa.MetaData(), + sa.Column("ord_id", sa.String(36), primary_key=True), + sa.Column("ord_id_hospital", sa.String(64)), + sa.Column("ord_tipo_estudio", sa.Text), + sa.Column("ord_pdf_blob", sa.LargeBinary), + ) + engine = sa.create_engine(url) + table.create(engine) + with engine.begin() as connection: + connection.execute(sa.insert(table), [ + {"ord_id": "ord-pdf-1", "ord_id_hospital": "ORD-PDF-1", "ord_tipo_estudio": "ADOS2", "ord_pdf_blob": report}, + {"ord_id": "ord-pdf-2", "ord_id_hospital": "ORD-PDF-2", "ord_tipo_estudio": "EEG", "ord_pdf_blob": None}, + ]) + engine.dispose() + source = { + "source_type": "sql", + "target": "tea.OrdenesEstudio", + "column_mapping": {column.name: column.name for column in table.columns}, + "payload": {"connection_string": url, "table": "ordenes_estudio"}, + } + + result = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}).get_json()["results"][0] + + assert (result["created"], result["rejected"]) == (2, 0), result + + from persistance.tea import ordenes_estudio_repository + + assert ordenes_estudio_repository.get("ord-pdf-1").ord_pdf_blob == report + assert ordenes_estudio_repository.get("ord-pdf-2").ord_pdf_blob is None diff --git a/webapi/imports/schemas/tea/ordenes_estudio.py b/webapi/imports/schemas/tea/ordenes_estudio.py index 72c18ae..bd9d06e 100644 --- a/webapi/imports/schemas/tea/ordenes_estudio.py +++ b/webapi/imports/schemas/tea/ordenes_estudio.py @@ -15,3 +15,4 @@ class OrdenesEstudioImportSchema(ImportSchema): ord_id_hospital: OptionalStr = None ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None ord_fecha: FlexDate = None + ord_pdf_blob: Optional[bytes] = None -- 2.53.0 From ea228da7b450028a76de00d20eb7021fa9f35689 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 08/24] CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is //indicadores --- tests/conftest.py | 43 +- .../casos_confirmacion_citologia.toml | 114 + tests/fixtures/casos_riesgo_banda.toml | 87 + tests/fixtures/kit_cacu_snapshot.json | 1264 +++ tests/fixtures/kit_cacu_timeline.json | 387 + tests/fixtures/kit_oracle_cacu.json | 7735 +++++++++++++++++ tests/fixtures/kit_oracle_cama.json | 6242 +++++++++++++ tests/test_cama_measures.py | 87 + tests/test_imports_endpoints.py | 13 + tests/test_indicadores_cacu.py | 338 - tests/test_indicadores_cama.py | 229 - tests/test_indicadores_tea.py | 169 - tests/test_kpis_route.py | 135 + tests/test_measure_cases.py | 100 + tests/test_metrics_on_request.py | 461 + tests/test_orquestacion_ciclo.py | 64 +- tests/test_orquestacion_oro.py | 111 +- tests/test_orquestacion_pasos.py | 8 +- tests/test_orquestacion_plata.py | 23 +- tests/test_orquestacion_regla_repositorios.py | 2 +- tests/test_orquestacion_riesgos.py | 20 +- tests/test_orquestacion_timeline.py | 102 +- tests/test_reportes.py | 6 +- tests/test_schemas.py | 20 +- tests/test_schemas_registry.py | 2 + webapi/__init__.py | 14 +- webapi/blueprints/cacu.py | 4 - webapi/blueprints/cama.py | 7 - webapi/blueprints/imports.py | 4 +- webapi/blueprints/tea.py | 7 - webapi/compositions.py | 329 + webapi/durations.py | 291 + webapi/indicadores.py | 231 - webapi/indicadores_vivos.py | 2 +- webapi/kpis.py | 111 + webapi/metrics.py | 502 ++ webapi/orquestacion/__main__.py | 2 +- webapi/orquestacion/ciclo.py | 78 +- webapi/orquestacion/contexto.py | 10 + webapi/orquestacion/proyecto.py | 12 +- webapi/orquestacion/repositorios.py | 17 +- webapi/orquestacion/semantic_layer.py | 78 + 42 files changed, 18123 insertions(+), 1338 deletions(-) create mode 100644 tests/fixtures/casos_confirmacion_citologia.toml create mode 100644 tests/fixtures/casos_riesgo_banda.toml create mode 100644 tests/fixtures/kit_cacu_snapshot.json create mode 100644 tests/fixtures/kit_cacu_timeline.json create mode 100644 tests/fixtures/kit_oracle_cacu.json create mode 100644 tests/fixtures/kit_oracle_cama.json create mode 100644 tests/test_cama_measures.py delete mode 100644 tests/test_indicadores_cacu.py delete mode 100644 tests/test_indicadores_cama.py delete mode 100644 tests/test_indicadores_tea.py create mode 100644 tests/test_kpis_route.py create mode 100644 tests/test_measure_cases.py create mode 100644 tests/test_metrics_on_request.py delete mode 100644 webapi/blueprints/cama.py delete mode 100644 webapi/blueprints/tea.py create mode 100644 webapi/compositions.py create mode 100644 webapi/durations.py delete mode 100644 webapi/indicadores.py create mode 100644 webapi/kpis.py create mode 100644 webapi/metrics.py create mode 100644 webapi/orquestacion/semantic_layer.py diff --git a/tests/conftest.py b/tests/conftest.py index bd318aa..fe080dc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -57,19 +57,21 @@ class Base: return Session(self.motor) -def base_de(proyecto: str, carpeta) -> Base: +def base_de(proyecto: str, carpeta, datos=None) -> Base: + """A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts.""" url = f"sqlite:///{carpeta / f'{proyecto}.db'}" apuntar(proyecto, url) - ctx = Contexto(proyecto, ANIO, ANIO, repos=repositorios_de(proyecto)) + manifest = os.environ.get("DBT_MANIFEST") + ctx = Contexto(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositorios_de(proyecto)) correr(ctx, solo=["migrar"]) motor = create_engine(url) with Session(motor) as sesion: - import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) + (datos or import_module(f"indicadores_kit.{proyecto}.fixtures").insertar)(sesion) sesion.commit() return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor) -@pytest.fixture(params=["cacu", "cama", "tea"]) +@pytest.fixture(params=["cacu", "cama"]) def proyecto(request): return request.param @@ -136,25 +138,16 @@ MESES = ["2025-01", "2025-02", "2025-03"] def cliente_de(proyecto: str, tmp_path_factory): - """Yields a client over a temporary SQLite database seeded with the kit's demonstration data.""" - from indicadores_kit.demostracion import base_de_prueba - from persistance import db - from persistance.settings import settings + """Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging.""" + carpeta = tmp_path_factory.mktemp(proyecto) + base = base_de(proyecto, carpeta) + base.correr("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos", permitir_sin_definir=True) + try: + from webapi import create_app - ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db" - obtener_motor = getattr(db, f"get_{proyecto}_engine") - with pytest.MonkeyPatch.context() as mp: - mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}") - obtener_motor.cache_clear() - try: - base_de_prueba(obtener_motor(), proyecto) - - from webapi import create_app - - app = create_app() - app.config.update(TESTING=True) - with app.test_client() as cliente: - yield cliente - finally: - obtener_motor().dispose() - obtener_motor.cache_clear() + app = create_app() + app.config.update(TESTING=True) + with app.test_client() as cliente: + yield cliente + finally: + base.motor.dispose() diff --git a/tests/fixtures/casos_confirmacion_citologia.toml b/tests/fixtures/casos_confirmacion_citologia.toml new file mode 100644 index 0000000..396d329 --- /dev/null +++ b/tests/fixtures/casos_confirmacion_citologia.toml @@ -0,0 +1,114 @@ +# Casos de CACU_CONFIRMACION_CITOLOGIA (confirmación por biopsia según resultado citológico, C2). +# La unidad es la paciente cuya última citología válida del periodo es de alto grado +# (`cacu.citologia_alto_grado`); la última válida es la de EU7 (`cacu.calidad_insatisfactoria`). +# Cada categoría es `cat:` de la biopsia más grave que originó esa citología (ligada por +# `cit_id`); sin biopsia reportada al corte, `cat:SIN_BIOPSIA`; con biopsia sin grado, `cat:SIN_DATO`. +# `estratos` dice el valor de cada paciente en `citologia_alto_grado`: la fila del panel. Sin `corte`, +# es el día de la carga del caso (2026-01-01). + +measure = "cacu/CACU_CONFIRMACION_CITOLOGIA" + +[[caso]] +nombre = "una paciente con ASC-H y biopsia LIEAG cuenta en LIEAG dentro de la fila ASC-H" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-H" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" }, +] +espera."2025-S1" = { "cat:LIEAG" = 1, "cat:NORMAL" = 1 } +unidades."2025-S1" = { "cat:LIEAG" = ["1"], "cat:NORMAL" = ["2"] } # la 2 es un falso positivo de la fila LIEAG +estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H", "2" = "LIEAG" } + +[[caso]] +nombre = "la última citología válida manda y no la peor" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 2, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEBG" }, +] +espera."2025-S1" = { "cat:LIEBG" = 1 } +estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" } + +[[caso]] +nombre = "con varias biopsias de la toma cuenta la más grave y no la más reciente" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01, bx_cin_grado = "LIEBG" }, + { tabla = "biopsiacervical", bx_id = 3, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-05-01, bx_cin_grado = "NORMAL" }, +] +espera."2025-S1" = { "cat:CIS" = 1, "cat:LIEBG" = 0, "cat:NORMAL" = 0 } + +[[caso]] +nombre = "una biopsia con grado gana a una sin grado; solo sin grado es sin dato" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01 }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" }, + { tabla = "biopsiacervical", bx_id = 3, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01 }, +] +espera."2025-S1" = { "cat:NORMAL" = 1, "cat:SIN_DATO" = 1, "cat:SIN_BIOPSIA" = 0 } +unidades."2025-S1" = { "cat:SIN_DATO" = ["2"] } + +[[caso]] +nombre = "una biopsia reportada después del corte todavía no existe: sin biopsia aún" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" }, +] +corte = 2025-07-31 +espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:LIEAG" = 0 } +estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" } + +[[caso]] +nombre = "el día del corte la biopsia ya existe" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" }, +] +corte = 2025-08-01 +espera."2025-S1" = { "cat:SIN_BIOPSIA" = 0, "cat:LIEAG" = 1 } + +[[caso]] +nombre = "una biopsia de otra toma no cuenta" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" }, + { tabla = "biopsiacervical", bx_id = 2, pac_id = 1, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEAG" }, +] +espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:CIS" = 0, "cat:LIEAG" = 0 } +estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" } + +[[caso]] +nombre = "una insatisfactoria posterior no es la última válida" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "INSATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" }, +] +espera."2025-S1" = { "cat:LIEAG" = 1 } +estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" } + +[[caso]] +nombre = "una paciente cuya última citología es NORMAL no entra aunque antes tuviera LIEAG" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" }, + { tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" }, + { tabla = "citologiacervical", cit_id = 3, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-US" }, +] +espera."2025-S1" = { "cat:CIS" = 0, "cat:SIN_BIOPSIA" = 0, "cat:NORMAL" = 0 } +estratos."2025-S1".citologia_alto_grado = {} + +[[caso]] +nombre = "la citología cuenta en el periodo de su toma y no en el del reporte de la biopsia" +filas = [ + { tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-20, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-25, cit_celulas_escamosas = "CIS" }, + { tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "CARCINOMA" }, +] +espera."2025-S1" = { "cat:CARCINOMA" = 1 } +espera."2025-S2" = { "cat:CARCINOMA" = 0 } +estratos."2025-S1".citologia_alto_grado = { "1" = "CIS" } diff --git a/tests/fixtures/casos_riesgo_banda.toml b/tests/fixtures/casos_riesgo_banda.toml new file mode 100644 index 0000000..bd715d3 --- /dev/null +++ b/tests/fixtures/casos_riesgo_banda.toml @@ -0,0 +1,87 @@ +# Casos de CACU_RIESGO_BANDA (pacientes en vigilancia por banda de riesgo, C2). PROPUESTA (MD-Q5). +# Cuenta a las miembros del armado del lote vigente (el mayor con alguna evaluación `final` al +# horizonte) con fecha índice en el periodo, por la banda de la versión más reciente de su +# evaluación. Con los parámetros de `parametros.toml`: BAJO < 0.04 <= INTERMEDIO < 0.25 <= ALTO, +# horizonte 0. `cat:SIN_DATO`: sin evaluación `final` en el lote. + +measure = "cacu/CACU_RIESGO_BANDA" + +[plantillas] +armado = [ + { tabla = "cohorte_armado", armado_id = 1, url = "cacu/cohorte_vigilancia", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 4, 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 = "cohorte_miembro", armado_id = 1, pac_id = 2, fecha_indice = 2025-03-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "2" }, + { tabla = "cohorte_miembro", armado_id = 1, pac_id = 3, fecha_indice = 2025-04-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "3" }, + { tabla = "cohorte_miembro", armado_id = 1, pac_id = 4, fecha_indice = 2025-08-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "4" }, +] +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 }, +] + +[[caso]] +nombre = "cada paciente en la banda de su riesgo; sin evaluación es sin dato" +incluye = ["armado", "lote_final"] +filas = [] +espera."2025-S1" = { "cat:BAJO" = 1, "cat:INTERMEDIO" = 1, "cat:ALTO" = 0, "cat:SIN_DATO" = 1 } +unidades."2025-S1" = { "cat:SIN_DATO" = [3] } + +[[caso]] +nombre = "el periodo es el de la fecha índice" +incluye = ["armado", "lote_final"] +filas = [] +espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 } + +[[caso]] +nombre = "los cortes son parámetros" +incluye = ["armado", "lote_final"] +filas = [] +parametros = { "comun.riesgos.corte_intermedio" = 0.01, "comun.riesgos.corte_alto" = 0.05 } +espera."2025-S1" = { "cat:BAJO" = 0, "cat:INTERMEDIO" = 1, "cat:ALTO" = 1 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 } + +[[caso]] +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 } + +[[caso]] +nombre = "el lote de otra cohorte no cuenta" +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 }, +] +espera."2025-S1" = { "cat:BAJO" = 0 } diff --git a/tests/fixtures/kit_cacu_snapshot.json b/tests/fixtures/kit_cacu_snapshot.json new file mode 100644 index 0000000..10312e7 --- /dev/null +++ b/tests/fixtures/kit_cacu_snapshot.json @@ -0,0 +1,1264 @@ +{ + "cacu/CACU_EU13": { + "2025-01": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null + ] + ] + }, + "2025-02": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-03": { + "grupo_edad": [ + [ + "2", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null + ] + ] + }, + "2025-04": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null + ] + ] + }, + "2025-05": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-06": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-07": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-08": { + "grupo_edad": [ + [ + "5", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null + ] + ] + }, + "2025-09": { + "grupo_edad": [ + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null + ] + ] + }, + "2025-10": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 1 + ], + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-11": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-12": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-S1": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "2", + "45-54" + ], + [ + "3", + "45-54" + ], + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 4 + ], + "total|total": [ + 0, + 4 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-S2": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "4", + "45-54" + ], + [ + "5", + "45-54" + ], + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54": [ + 0, + 4 + ], + "total|total": [ + 0, + 4 + ] + }, + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null + ] + ] + } + }, + "cacu/CACU_EU7": { + "2025-01": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "SIN_DATO" + ] + ] + }, + "2025-02": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|NEGATIVO": 1, + "total|total|NEGATIVO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO" + ] + ] + }, + "2025-03": { + "grupo_edad": [ + [ + "2", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO" + ] + ] + }, + "2025-04": { + "grupo_edad": [ + [ + "3", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEBG": 1, + "total|total|LIEBG": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG" + ] + ] + }, + "2025-05": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|NEGATIVO": 1, + "total|total|NEGATIVO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO" + ] + ] + }, + "2025-06": { + "grupo_edad": [], + "published": {}, + "units": [] + }, + "2025-07": { + "grupo_edad": [ + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEAG": 1, + "total|total|LIEAG": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG" + ] + ] + }, + "2025-08": { + "grupo_edad": [ + [ + "5", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|NEGATIVO": 1, + "total|total|NEGATIVO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO" + ] + ] + }, + "2025-09": { + "grupo_edad": [ + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO" + ] + ] + }, + "2025-10": { + "grupo_edad": [ + [ + "1", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO" + ] + ] + }, + "2025-11": { + "grupo_edad": [], + "published": {}, + "units": [] + }, + "2025-12": { + "grupo_edad": [], + "published": {}, + "units": [] + }, + "2025-S1": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "2", + "45-54" + ], + [ + "3", + "45-54" + ], + [ + "4", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEBG": 1, + "grupo_edad|45-54|NEGATIVO": 2, + "grupo_edad|45-54|SIN_DATO": 1, + "total|total|LIEBG": 1, + "total|total|NEGATIVO": 2, + "total|total|SIN_DATO": 1 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO" + ] + ] + }, + "2025-S2": { + "grupo_edad": [ + [ + "1", + "45-54" + ], + [ + "4", + "45-54" + ], + [ + "5", + "45-54" + ], + [ + "6", + "45-54" + ] + ], + "published": { + "grupo_edad|45-54|LIEAG": 1, + "grupo_edad|45-54|NEGATIVO": 1, + "grupo_edad|45-54|SIN_DATO": 2, + "total|total|LIEAG": 1, + "total|total|NEGATIVO": 1, + "total|total|SIN_DATO": 2 + }, + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO" + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO" + ] + ] + } + }, + "cacu/IND1": { + "2025-01": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null + ] + ] + }, + "2025-02": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-03": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "2", + 2, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null + ] + ] + }, + "2025-04": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null + ] + ] + }, + "2025-05": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ] + ] + }, + "2025-06": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-07": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null + ] + ] + }, + "2025-08": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "5", + 5, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null + ] + ] + }, + "2025-09": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "6", + 6, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null + ] + ] + }, + "2025-10": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 1 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ] + ] + }, + "2025-11": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-12": { + "grupo_edad": [], + "published": { + "total|total": [ + 0, + 0 + ] + }, + "units": [] + }, + "2025-S1": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 4 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.denominator", + "2", + 2, + null + ], + [ + "principal", + "IND1.denominator", + "3", + 3, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null + ] + ] + }, + "2025-S2": { + "grupo_edad": [], + "published": { + "total|total": [ + 1, + 4 + ] + }, + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null + ], + [ + "principal", + "IND1.denominator", + "5", + 5, + null + ], + [ + "principal", + "IND1.denominator", + "6", + 6, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null + ] + ] + } + } +} \ No newline at end of file diff --git a/tests/fixtures/kit_cacu_timeline.json b/tests/fixtures/kit_cacu_timeline.json new file mode 100644 index 0000000..47a8246 --- /dev/null +++ b/tests/fixtures/kit_cacu_timeline.json @@ -0,0 +1,387 @@ +[ + { + "pac_id": "1", + "fecha": "2025-02-03", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "1" + }, + { + "pac_id": "1", + "fecha": "2025-02-10", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "1" + }, + { + "pac_id": "1", + "fecha": "2025-02-20", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "1" + }, + { + "pac_id": "1", + "fecha": "2025-03-01", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "N871", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "3" + }, + { + "pac_id": "1", + "fecha": "2025-10-02", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "9" + }, + { + "pac_id": "2", + "fecha": "2025-03-05", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "INSATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "2" + }, + { + "pac_id": "2", + "fecha": "2025-09-15", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "C53", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2024-12-01", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "C539", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "2" + }, + { + "pac_id": "3", + "fecha": "2025-01-20", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "INSATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-02-01", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "ASC-US", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-02-01", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "POSITIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-02-01", + "clase": "medicion", + "tipo": "vph_genotipo_16_18", + "codigo": "vph_genotipo_16_18", + "valor_codigo": null, + "valor_numerico": "1.0", + "fuente_tabla": "citologiacervical", + "fuente_id": "3" + }, + { + "pac_id": "3", + "fecha": "2025-04-10", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "2" + }, + { + "pac_id": "3", + "fecha": "2025-04-15", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-04-25", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "LIEBG", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-04-25", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "POSITIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-04-25", + "clase": "medicion", + "tipo": "vph_genotipo_16_18", + "codigo": "vph_genotipo_16_18", + "valor_codigo": null, + "valor_numerico": "0.0", + "fuente_tabla": "citologiacervical", + "fuente_id": "4" + }, + { + "pac_id": "3", + "fecha": "2025-05-01", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": null, + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "1" + }, + { + "pac_id": "3", + "fecha": "2025-05-20", + "clase": "medicion", + "tipo": "biopsia", + "codigo": "cin", + "valor_codigo": "CIN1", + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "1" + }, + { + "pac_id": "4", + "fecha": "2025-05-30", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "5" + }, + { + "pac_id": "4", + "fecha": "2025-06-09", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "5" + }, + { + "pac_id": "4", + "fecha": "2025-06-25", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "3" + }, + { + "pac_id": "4", + "fecha": "2025-07-01", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-11", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "LIEAG", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-11", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "POSITIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-11", + "clase": "medicion", + "tipo": "vph_genotipo_16_18", + "codigo": "vph_genotipo_16_18", + "valor_codigo": null, + "valor_numerico": "1.0", + "fuente_tabla": "citologiacervical", + "fuente_id": "6" + }, + { + "pac_id": "4", + "fecha": "2025-07-15", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": null, + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "2" + }, + { + "pac_id": "4", + "fecha": "2025-08-01", + "clase": "medicion", + "tipo": "biopsia", + "codigo": "cin", + "valor_codigo": "CIN2", + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "2" + }, + { + "pac_id": "4", + "fecha": "2025-08-10", + "clase": "diagnostico", + "tipo": "nota_medica", + "codigo": "nota_medica", + "valor_codigo": "D069", + "valor_numerico": null, + "fuente_tabla": "notamedica", + "fuente_id": "1" + }, + { + "pac_id": "5", + "fecha": "2025-08-12", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "SATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "7" + }, + { + "pac_id": "5", + "fecha": "2025-08-22", + "clase": "medicion", + "tipo": "bethesda", + "codigo": "bethesda", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "7" + }, + { + "pac_id": "5", + "fecha": "2025-08-22", + "clase": "medicion", + "tipo": "vph", + "codigo": "vph", + "valor_codigo": "NEGATIVO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "7" + }, + { + "pac_id": "5", + "fecha": "2025-09-01", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": null, + "valor_numerico": null, + "fuente_tabla": "biopsiacervical", + "fuente_id": "3" + }, + { + "pac_id": "5", + "fecha": "2025-12-01", + "clase": "orden", + "tipo": "orden", + "codigo": "orden", + "valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + "valor_numerico": null, + "fuente_tabla": "ordenesestudio", + "fuente_id": "4" + }, + { + "pac_id": "6", + "fecha": "2025-09-01", + "clase": "procedimiento", + "tipo": "citologia", + "codigo": "citologia_cervical", + "valor_codigo": "INSATISFACTORIO", + "valor_numerico": null, + "fuente_tabla": "citologiacervical", + "fuente_id": "8" + } +] diff --git a/tests/fixtures/kit_oracle_cacu.json b/tests/fixtures/kit_oracle_cacu.json new file mode 100644 index 0000000..d33961c --- /dev/null +++ b/tests/fixtures/kit_oracle_cacu.json @@ -0,0 +1,7735 @@ +{ + "cacu/CACU_CONFIRMACION_CITOLOGIA": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "citologia_alto_grado", + "LIEAG" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_CONFIRMACION_CITOLOGIA.measure-observation", + "4", + 4, + "CIN2", + null + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "citologia_alto_grado", + "LIEAG", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIN2", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_BIOPSIA", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "citologia_alto_grado", + "LIEAG" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_CONFIRMACION_CITOLOGIA.measure-observation", + "4", + 4, + "CIN2", + null + ] + ] + } + } + }, + "cacu/CACU_DIAS_TOMA_DIAGNOSTICO": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 72.0, + 72.0, + 72.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 72.0 + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 40.0, + 40.0, + 40.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 40.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 161.0, + 161.0, + 161.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "7", + null, + null, + 161.0 + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "9", + null, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 72.0, + 72.0, + 72.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 72.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 2, + 100.5, + 70.25, + 130.75, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.initial-population", + "9", + null, + null, + null + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 40.0 + ], + [ + "TOTAL", + "CACU_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "7", + null, + null, + 161.0 + ] + ] + } + } + }, + "cacu/CACU_EU13": { + "contrato": "C1", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null, + null + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null, + null + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null, + null + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ], + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "2", + 2, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "grupo_edad", + "45-54", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ], + [ + "principal", + "total", + "total", + 0, + 4, + 0.0, + 0.0, + 48.98908404, + 0, + 4, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ], + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ], + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "principal", + "CACU_EU13.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "CACU_EU13.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "5", + 5, + null, + null + ], + [ + "principal", + "CACU_EU13.initial-population", + "6", + 6, + null, + null + ] + ] + } + } + }, + "cacu/CACU_EU7": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "SIN_DATO", + null + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO", + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO", + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG", + null + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO", + null + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "ASC-H", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG", + null + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO", + null + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO", + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO", + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "ASC-H", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + "ASC-H", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 6, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 2, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 2, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 1, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 2, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "2", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "2", + "grupo_edad", + "45-54" + ], + [ + "3", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "3", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "NEGATIVO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "2", + 2, + "SIN_DATO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "3", + 3, + "LIEBG", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "NEGATIVO", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "estatus_seguimiento", + "PRE_COLPOSCOPIA", + "SIN_DATO", + 2, + 6, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "grupo_edad", + "45-54", + "SIN_DATO", + 2, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-H", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "ASC-US", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CIS", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEAG", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "LIEBG", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NEGATIVO", + 1, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "NORMAL", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 2, + 6, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [ + [ + "1", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "1", + "grupo_edad", + "45-54" + ], + [ + "4", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "4", + "grupo_edad", + "45-54" + ], + [ + "5", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "5", + "grupo_edad", + "45-54" + ], + [ + "6", + "estatus_seguimiento", + "PRE_COLPOSCOPIA" + ], + [ + "6", + "grupo_edad", + "45-54" + ] + ], + "units": [ + [ + "TOTAL", + "CACU_EU7.measure-observation", + "1", + 1, + "SIN_DATO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "4", + 4, + "LIEAG", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "5", + 5, + "NEGATIVO", + null + ], + [ + "TOTAL", + "CACU_EU7.measure-observation", + "6", + 6, + "SIN_DATO", + null + ] + ] + } + } + }, + "cacu/CACU_EU_TIEMPO_REPORTE": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 12.0, + 12.0, + 12.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "3", + null, + null, + 12.0 + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "1", + null, + null, + 10.0 + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "2", + null, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "4", + null, + null, + 10.0 + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "5", + null, + null, + 10.0 + ] + ] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "6", + null, + null, + 10.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 10.0, + 10.0, + 10.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "7", + null, + null, + 10.0 + ] + ] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "8", + null, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "9", + null, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 4, + 10.0, + 10.0, + 10.5, + 0, + 1, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "1", + null, + null, + 10.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "3", + null, + null, + 12.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "4", + null, + null, + 10.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "5", + null, + null, + 10.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 2, + 10.0, + 10.0, + 10.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.initial-population", + "9", + null, + null, + null + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "6", + null, + null, + 10.0 + ], + [ + "TOTAL", + "CACU_EU_TIEMPO_REPORTE.measure-observation", + "7", + null, + null, + 10.0 + ] + ] + } + } + }, + "cacu/CACU_RIESGO_BANDA": { + "contrato": "C2", + "periodos": { + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "ALTO", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "BAJO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "INTERMEDIO", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "ALTO", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "BAJO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "INTERMEDIO", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + } + } + }, + "cacu/IND1": { + "contrato": "C1", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null, + null + ] + ] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null, + null + ] + ] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null, + null + ] + ] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ] + ] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null, + null + ] + ] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null, + null + ] + ] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 0, + 1, + 0.0, + 0.0, + 79.345068821, + 0, + 1, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ] + ] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 4, + 25.0, + 4.55872603, + 69.93581599, + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.denominator", + "2", + 2, + null, + null + ], + [ + "principal", + "IND1.denominator", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "2", + 2, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "3", + 3, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.numerator", + "3", + 3, + null, + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "principal", + "total", + "total", + 1, + 4, + 25.0, + 4.55872603, + 69.93581599, + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "IND1.denominator", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.denominator", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.denominator", + "5", + 5, + null, + null + ], + [ + "principal", + "IND1.denominator", + "6", + 6, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "1", + 1, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "4", + 4, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "5", + 5, + null, + null + ], + [ + "principal", + "IND1.initial-population", + "6", + 6, + null, + null + ], + [ + "principal", + "IND1.numerator", + "4", + 4, + null, + null + ] + ] + } + } + } +} \ No newline at end of file diff --git a/tests/fixtures/kit_oracle_cama.json b/tests/fixtures/kit_oracle_cama.json new file mode 100644 index 0000000..ea67468 --- /dev/null +++ b/tests/fixtures/kit_oracle_cama.json @@ -0,0 +1,6242 @@ +{ + "cama/CAMA_BIOPSIAS": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "1", + null, + "BENIGNO", + null + ] + ] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "2", + null, + "CARCINOMA_INVASOR", + null + ] + ] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 3, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "1", + null, + "BENIGNO", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "BENIGNO", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_INVASOR", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "CARCINOMA_IN_SITU", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 3, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIOPSIAS.measure-observation", + "2", + null, + "CARCINOMA_INVASOR", + null + ] + ] + } + } + }, + "cama/CAMA_BIRADS": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "1", + 1, + "B1", + null + ] + ] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "B2", + null + ] + ] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "3", + 3, + "B0", + null + ] + ] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "3", + 3, + "B1", + null + ] + ] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B1", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B2", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B3", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 6, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 7, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 8, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 9, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "5", + 5, + "B1", + null + ] + ] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B1", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B2", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B3", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 6, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 7, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 8, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 9, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "5", + 5, + "SIN_DATO", + null + ] + ] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B1", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B2", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B3", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 5, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 6, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 7, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 8, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 9, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "6", + 6, + "B0", + null + ] + ] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 0, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "SIN_DATO", + null + ] + ] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 1, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "1", + 1, + "B1", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "B2", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "3", + 3, + "B0", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B0", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B1", + 1, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B2", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B3", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4A", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 5, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 6, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 7, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 8, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 1, + 9, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "2", + 2, + "SIN_DATO", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "5", + 5, + "B1", + null + ], + [ + "TOTAL", + "CAMA_BIRADS.measure-observation", + "6", + 6, + "B0", + null + ] + ] + } + } + }, + "cama/CAMA_BIRADS456_MASTOGRAFIA": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_MASTOGRAFIA.measure-observation", + "5", + null, + "B4A", + null + ] + ] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_MASTOGRAFIA.measure-observation", + "5", + null, + "B4A", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + } + } + }, + "cama/CAMA_BIRADS456_PACIENTE": { + "contrato": "C2", + "periodos": { + "2025-01": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_PACIENTE.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-07": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-08": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + 1, + 0, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + 0, + 1, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + 0, + 2, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B5", + 0, + 3, + 0 + ], + [ + "TOTAL", + "total", + "total", + "B6", + 0, + 4, + 0 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + 0, + 5, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_BIRADS456_PACIENTE.measure-observation", + "4", + 4, + "B4A", + null + ] + ] + }, + "2025-S2": { + "fecha_corte": null, + "published": [ + [ + "TOTAL", + "total", + "total", + "B4A", + null, + 0, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4B", + null, + 1, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B4C", + null, + 2, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B5", + null, + 3, + 1 + ], + [ + "TOTAL", + "total", + "total", + "B6", + null, + 4, + 1 + ], + [ + "TOTAL", + "total", + "total", + "SIN_DATO", + null, + 5, + 1 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "categoria", + "n", + "orden", + "suprimido" + ], + "strata": [], + "units": [] + } + } + }, + "cama/CAMA_CONFIRMACION_BIRADS45": { + "contrato": "C1", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.denominator", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.initial-population", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.numerator", + "5", + null, + null, + null + ] + ] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + 1, + 1, + 100.0, + 20.654931179, + 100.0, + 0, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [ + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.denominator", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.initial-population", + "5", + null, + null, + null + ], + [ + "principal", + "CAMA_CONFIRMACION_BIRADS45.numerator", + "5", + null, + null, + null + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "principal", + "total", + "total", + null, + null, + null, + null, + null, + 1, + 0, + 0 + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "numerador", + "denominador", + "valor", + "ic_bajo", + "ic_alto", + "suprimido", + "n_sin_evento", + "n_excluido" + ], + "strata": [], + "units": [] + } + } + }, + "cama/CAMA_DIAS_TOMA_DIAGNOSTICO": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 35.0, + 35.0, + 35.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 35.0 + ] + ] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 19.0, + 19.0, + 19.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 19.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ] + ] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 35.0, + 35.0, + 35.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "5", + null, + null, + 35.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 19.0, + 19.0, + 19.0, + 0, + 1, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_DIAS_TOMA_DIAGNOSTICO.measure-observation", + "6", + null, + null, + 19.0 + ] + ] + } + } + }, + "cama/CAMA_EU38A": { + "contrato": "C3r", + "periodos": { + "2025-01": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "1", + null, + null, + 7.0 + ] + ] + }, + "2025-02": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "2", + null, + null, + 7.0 + ] + ] + }, + "2025-03": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "3", + null, + null, + 7.0 + ] + ] + }, + "2025-04": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "4", + null, + null, + 7.0 + ] + ] + }, + "2025-05": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-06": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "5", + null, + null, + 7.0 + ] + ] + }, + "2025-07": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "6", + null, + null, + 7.0 + ] + ] + }, + "2025-08": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-09": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "7", + null, + null, + null + ] + ] + }, + "2025-10": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [] + }, + "2025-11": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 1, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "8", + null, + null, + 7.0 + ] + ] + }, + "2025-12": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + null, + null, + null, + null, + 0, + 0, + 1, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "9", + null, + null, + null + ] + ] + }, + "2025-S1": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 5, + 7.0, + 7.0, + 7.0, + 0, + 0, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "1", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "2", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "3", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "4", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "5", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "1", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "2", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "3", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "4", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "5", + null, + null, + 7.0 + ] + ] + }, + "2025-S2": { + "fecha_corte": "2026-11-08", + "published": [ + [ + "TOTAL", + "total", + "total", + 2, + 7.0, + 7.0, + 7.0, + 0, + 2, + 0, + "dias" + ] + ], + "published_columns": [ + "grupo", + "estrato_id", + "estrato_valor", + "n", + "mediana", + "q1", + "q3", + "n_sin_evento", + "n_excluido", + "suprimido", + "unidad" + ], + "strata": [], + "units": [ + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "6", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "7", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "8", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.initial-population", + "9", + null, + null, + null + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "6", + null, + null, + 7.0 + ], + [ + "TOTAL", + "CAMA_EU38A.measure-observation", + "8", + null, + null, + 7.0 + ] + ] + } + } + } +} \ No newline at end of file diff --git a/tests/test_cama_measures.py b/tests/test_cama_measures.py new file mode 100644 index 0000000..0f1b7f4 --- /dev/null +++ b/tests/test_cama_measures.py @@ -0,0 +1,87 @@ +"""What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit +computed on the same fixture data: every measure, every period, its units and its numbers. + +Fixtures: `base`, the CaMa fixture database through the cycle up to `modelos` (dbt's views); `manifest`, dbt's +`manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published +numbers for each measure and period (counts only; suppression off). +""" + +import json +import os +from dataclasses import replace +from pathlib import Path + +import pytest +from sqlalchemy import text + +from conftest import base_de +from webapi.compositions import answer_composition, composition_definitions +from webapi.durations import answer_duration, duration_definitions +from webapi.metrics import Question, answer, measure_definitions + +ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8")) +UNTIL_MODELS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture +def base(tmp_path, sin_supresion, manifest): + base = base_de("cama", tmp_path) + base.correr(*UNTIL_MODELS, parametros=sin_supresion, permitir_sin_definir=True) + yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.motor.dispose() + + +def repositories(base) -> dict: + d = base.dominio + return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, + "history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True} + + +def units(base, report_id: int) -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad " + "where report_id = :r"), {"r": report_id}).all())) + + +def published_rows(expected) -> list[dict]: + return [dict(zip(expected["published_columns"], row)) for row in expected["published"]] + + +@pytest.mark.parametrize("url", sorted(ORACLE)) +def test_each_measure_is_the_kit_s_in_every_period(base, manifest, url): + """Pins down every CaMa measure in every period: the kit's units (with each one's category or days) and its + numbers: a composition's count per category, a proportion's numerator and denominator, a duration's n, median, + quartiles and excluded where the kit didn't suppress them. Fails if an event model, a semantic definition or the + construct it uses drifts from what the kit meant.""" + for kind, of in (("proportion", measure_definitions), ("composition", composition_definitions), + ("duration", duration_definitions)): + if url in of(manifest): + definition = of(manifest)[url] + break + for period_id, expected in ORACLE[url]["periodos"].items(): + question = Question(url, period_id) + rows = published_rows(expected) + if kind == "composition": + result = answer_composition("cama", definition, question, **repositories(base)) + assert {k: v for k, v in result.categories.items() if v} == { + r["categoria"]: r["n"] for r in rows if r["estrato_id"] == "total" and r["n"]}, period_id + elif kind == "proportion": + result = answer("cama", definition, question, **repositories(base)) + (total,) = [r for r in rows if r["estrato_id"] == "total"] or [{"numerador": 0, "denominador": 0}] + assert (result.numerator, result.denominator) == (total["numerador"] or 0, total["denominador"] or 0), period_id + else: + result = answer_duration("cama", definition, question, **repositories(base)) + (total,) = [r for r in rows if r["estrato_id"] == "total"] + if not total["suprimido"]: + assert (result.n, result.median, result.q1, result.q3, result.excluded) == ( + total["n"], total["mediana"], total["q1"], total["q3"], total["n_excluido"]), period_id + assert units(base, result.report_id) == expected["units"], period_id diff --git a/tests/test_imports_endpoints.py b/tests/test_imports_endpoints.py index 9a18a0d..1ab9b57 100644 --- a/tests/test_imports_endpoints.py +++ b/tests/test_imports_endpoints.py @@ -183,6 +183,19 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client): assert paciente["pac_sexo"] == "M" +def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client): + """The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation. + + Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500. + """ + source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes") + response = client.post("/imports/commit", json={"sources": [source]}) + assert response.status_code == 200 + body = response.get_json() + assert body["results"][0]["created"] == 1 + assert body["indicadores_en_recalculo"] is False + + @pytest.fixture def sql_source_db(tmp_path): db_path = tmp_path / "external_source.db" diff --git a/tests/test_indicadores_cacu.py b/tests/test_indicadores_cacu.py deleted file mode 100644 index c2011b0..0000000 --- a/tests/test_indicadores_cacu.py +++ /dev/null @@ -1,338 +0,0 @@ -"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit.""" - -import pytest -from conftest import MESES, SEMESTRES, cliente_de -from indicadores_kit.registry.measures import RAIZ, measures_de -from indicadores_kit.serving.figuras import figuras_de - -PROYECTO = "cacu" -INDICADOR = "ind1" -DEFINICIONES = measures_de(PROYECTO) -(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR]) - - -@pytest.fixture(scope="module") -def client(tmp_path_factory): - yield from cliente_de(PROYECTO, tmp_path_factory) - - -def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}") - - -def _x(respuesta) -> list[str]: - return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]] - - -def test_listar_indicadores(client): - response = client.get(f"/{PROYECTO}/indicadores") - - assert response.status_code == 200 - lista = response.get_json() - visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto] - assert [fila["id"] for fila in lista] == sorted(visibles) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert fila["titulo"] == medida.title - assert fila["contrato"] == medida.extension.contrato - assert fila["figuras"] == figuras_de(medida) - assert fila["tipos_periodo"] == ["semestre", "mes"] - - -def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client): - """Los que su TOML marca `oculto` (p. ej. cacu_riesgo_banda hasta MD-Q5) no salen en el catálogo, pero responden.""" - ocultos = {nombre for nombre, medida in DEFINICIONES.items() if medida.extension.publicacion.oculto} - - assert ocultos - ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()} - - assert ids == set(DEFINICIONES) - ocultos - for indicador in ocultos: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200 - - -def test_un_indicador_retirado_da_404(client): - """T-22a (ADR-MD-009): los retirados (`/retirados/` del kit) ni se calculan ni se sirven.""" - retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")] - - assert retirados - for indicador in retirados: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404 - - -def test_figura_con_semestres(client): - response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro") - - assert response.status_code == 200 - assert response.mimetype == "application/json" - assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title - assert set(_x(response)) == set(SEMESTRES) - - -def test_figura_sin_periodos_usa_los_semestres_con_reporte(client): - response = _figura(client) - - assert response.status_code == 200 - assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran - - -def test_figura_con_meses(client): - response = _figura(client, query=f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert set(_x(response)) == set(MESES) - - -@pytest.mark.parametrize( - "query", - [ - "?tema=rojo", - "?periodos=2025-1", - "?periodos=2025-S3", - "?periodos=2025-13x", - "?periodos=2025-S1,", - "?periodos=abc", - "?periodos=2025-T1", # un tipo que el indicador no publica - "?periodos=2025-S1,2025-03", # tipos mezclados - ], -) -def test_figura_con_parametros_mal_formados_da_400(client, query): - response = _figura(client, query=query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "figura", "query"), - [ - ("CACU_NO_EXISTE", FIGURA, ""), - (INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato - (INDICADOR, "fig_no_existe", ""), - (INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte - (INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"), - (INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte - ], -) -def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query): - response = _figura(client, indicador, figura, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch): - from webapi import indicadores - - def falla(*args, **kwargs): - raise KeyError("columna") - - monkeypatch.setattr(indicadores, "figura_json", falla) - with pytest.raises(KeyError): - _figura(client, query="?periodos=2025-S1") - - -# --- Todos los indicadores del proyecto --- - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_figura_de_cada_indicador(client, indicador): - for figura in figuras_de(DEFINICIONES[indicador]): - response = _figura(client, indicador, figura) - - assert response.status_code == 200, (indicador, figura) - assert set(response.get_json()) >= {"data", "layout"} - - -def test_una_distribucion_sin_periodos_es_la_del_semestre_mas_reciente(client): - assert figuras_de(DEFINICIONES["cacu_eu7"]) == ["fig_c2_barras", "fig_c2_donas"] - - por_defecto = _figura(client, "cacu_eu7", "fig_c2_donas") - del_ultimo = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={SEMESTRES[-1]}") - de_todos = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={','.join(SEMESTRES)}") - - assert por_defecto.get_json() == del_ultimo.get_json() - assert len(de_todos.get_json()["data"]) == len(SEMESTRES) * len(por_defecto.get_json()["data"]) - - -# --- El catálogo, los periodos, los datos y los metadatos --- - -CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"} - - -def _ruta(client, indicador: str, ruta: str, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}") - - -def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client): - lista = client.get(f"/{PROYECTO}/indicadores").get_json() - - assert all(set(fila) == CATALOGO for fila in lista) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation) - assert fila["estratos"] == medida.extension.estratos - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador): - medida = DEFINICIONES[indicador] - - periodos = _ruta(client, indicador, "periodos") - datos = _ruta(client, indicador, "datos") - metadatos = _ruta(client, indicador, "metadatos") - - assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200) - assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos)) - assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos)) - de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"] - assert de_semestre == SEMESTRES - cuerpo = datos.get_json() - assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES) - assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"]) - assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"]) - assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura - assert metadatos.get_json()["tipo_calculo"] == medida.scoring - - -def test_datos_con_meses(client): - response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert response.get_json()["tipo_periodo"] == "mes" - assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES - - -def test_los_datos_dicen_de_que_reporte_salen(client): - cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json() - periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"] - - (reporte,) = cuerpo["reportes"] - assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1") - assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01") - assert cuerpo["version"] == DEFINICIONES[INDICADOR].version - - -@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"]) -def test_datos_con_parametros_mal_formados_da_400(client, query): - response = _ruta(client, INDICADOR, "datos", query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "ruta", "query"), - [ - ("NO_EXISTE", "datos", ""), - ("NO_EXISTE", "periodos", ""), - ("NO_EXISTE", "metadatos", ""), - (INDICADOR, "datos", "?periodos=2030-S1"), - ], -) -def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query): - response = _ruta(client, indicador, ruta, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -# --- Los filtros (T-19f) --- - - -@pytest.mark.parametrize("query", ["?filtro=grupo_edad", "?filtro=:25-34", "?filtro=grupo_edad:25-34,grupo_edad:35-44", - "?filtro=grupo_edad:25-34", "?filtro=ronda:1"]) -def test_un_filtro_mal_escrito_o_no_declarado_da_400(client, query): - """IND1 no declara filtros (EU7 y EU13 sí, desde T-24f): todo `?filtro=` da 400, en datos y en figuras.""" - for response in (_ruta(client, INDICADOR, "datos", query), _figura(client, query=query)): - assert response.status_code == 400 - assert "error" in response.get_json() - - -def test_sin_filtro_los_datos_no_traen_la_llave_filtros(client): - assert "filtros" not in _ruta(client, INDICADOR, "datos").get_json() - - -def test_los_filtros_se_leen_como_estrato_y_valor(): - from webapi.indicadores import filtros_pedidos - - assert filtros_pedidos(None) == {} and filtros_pedidos("") == {} - assert filtros_pedidos("grupo_edad:25-34,ronda:1") == {"grupo_edad": "25-34", "ronda": "1"} - with pytest.raises(ValueError, match="mal escrito"): - filtros_pedidos("grupo_edad") - - -# --- La ficha técnica (T-24e) --- - -# Las llaves de /metadatos antes de T-24e: no se quita ni se renombra ninguna. -METADATOS = { - "id", "titulo", "version", "estado", "contrato", "tipo_calculo", "unidad", "sentido", "descripcion", - "tipos_periodo", "figuras", "estratos", "grupos", "categorias", "grupos_de_categoria", "estandares", - "ficha", "parametros", -} # fmt: skip - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_los_metadatos_traen_referencias_poblaciones_y_figuras_sin_perder_llaves(client, indicador): - cuerpo = _ruta(client, indicador, "metadatos").get_json() - - assert set(cuerpo) == METADATOS | {"referencias", "poblaciones", "figuras_detalle"} - assert cuerpo["poblaciones"] - assert [d["figura"] for d in cuerpo["figuras_detalle"]] == cuerpo["figuras"] - if not DEFINICIONES[indicador].extension.publicacion.oculto: - assert all(d["descripcion"] and d["como_leer"] for d in cuerpo["figuras_detalle"]) - assert all(set(p) == {"grupo", "codigo", "descripcion"} and p["descripcion"] for p in cuerpo["poblaciones"]) - - -def test_la_ficha_de_eu7_cita_el_lineamiento_europeo(client): - cuerpo = _ruta(client, "cacu_eu7", "metadatos").get_json() - - assert cuerpo["referencias"] == [{ - "tipo": "citation", - "etiqueta": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)", - "ref": "indicador 7", - }] # fmt: skip - assert cuerpo["poblaciones"] == [{ - "grupo": "total", - "codigo": "measure-observation", - "descripcion": DEFINICIONES["cacu_eu7"].group[0].population[0].description, - }] # fmt: skip - - -# --- EU7 por estrato (T-24f): la dona y sus barras --- - - -def test_eu7_por_estatus_da_categoria_por_valor_con_etiquetas_y_totales(client): - cuerpo = _ruta(client, "cacu_eu7", "datos", "?estrato=estatus_seguimiento").get_json() - - assert cuerpo["estrato"] == "estatus_seguimiento" and cuerpo["valores_estrato"] - assert set(cuerpo["etiquetas_estrato"]) == set(cuerpo["valores_estrato"]) - assert {f["estrato"] for f in cuerpo["filas"]} == set(cuerpo["valores_estrato"]) - assert {t["estrato"] for t in cuerpo["totales_estrato"]} == set(cuerpo["valores_estrato"]) - - -def test_eu7_se_puede_filtrar_por_grupo_de_edad(client): - valor = _ruta(client, "cacu_eu7", "datos", "?estrato=grupo_edad").get_json()["valores_estrato"][0] - response = _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}") - - assert response.status_code == 200 - assert response.get_json()["filtros"] == {"grupo_edad": valor} - - -def test_el_catalogo_publica_los_filtros_con_sus_valores(client): - """T-24f (contrato de T-24a §3): con ellos se arma `?filtro=estrato:valor`.""" - por_id = {fila["id"]: fila for fila in client.get(f"/{PROYECTO}/indicadores").get_json()} - - assert por_id[INDICADOR]["filtros"] == [] # IND1 no declara filtros - (edad, estatus) = por_id["cacu_eu7"]["filtros"] - assert (edad["estrato"], edad["etiqueta"]) == ("grupo_edad", "Grupo de edad") - assert [v["valor"] for v in edad["valores"]][-1] == "sin_dato" - assert (estatus["estrato"], estatus["etiqueta"]) == ("estatus_seguimiento", "Estatus de seguimiento") - assert estatus["valores"] == [ - {"valor": "PRE_COLPOSCOPIA", "etiqueta": "Pre colposcopia"}, - {"valor": "POST_COLPOSCOPIA", "etiqueta": "Post colposcopia"}, - {"valor": "POST_TRATAMIENTO", "etiqueta": "Post tratamiento"}, - {"valor": "INFO_INSUFICIENTE", "etiqueta": "Información insuficiente"}, - ] - valor = edad["valores"][0]["valor"] - assert _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}").status_code == 200 diff --git a/tests/test_indicadores_cama.py b/tests/test_indicadores_cama.py deleted file mode 100644 index 0428e12..0000000 --- a/tests/test_indicadores_cama.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit.""" - -import pytest -from conftest import MESES, SEMESTRES, cliente_de -from indicadores_kit.registry.measures import RAIZ, measures_de -from indicadores_kit.serving.figuras import figuras_de - -PROYECTO = "cama" -INDICADOR = "cama_confirmacion_birads45" -DEFINICIONES = measures_de(PROYECTO) -(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR]) - - -@pytest.fixture(scope="module") -def client(tmp_path_factory): - yield from cliente_de(PROYECTO, tmp_path_factory) - - -def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}") - - -def _x(respuesta) -> list[str]: - return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]] - - -def test_listar_indicadores(client): - response = client.get(f"/{PROYECTO}/indicadores") - - assert response.status_code == 200 - lista = response.get_json() - visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto] - assert [fila["id"] for fila in lista] == sorted(visibles) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert fila["titulo"] == medida.title - assert fila["contrato"] == medida.extension.contrato - assert fila["figuras"] == figuras_de(medida) - assert fila["tipos_periodo"] == ["semestre", "mes"] - - -def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client): - """Provisional (oct 2026): cama_birads no se muestra. - - cama_birads lo sustituyen cama_birads_456_paciente y cama_birads_456_mastografia. - cama_confirmacion_birads45 vuelve a mostrarse: su tarjeta destacada y su - gráfica de tendencia (usuario, 2026-10-16). - """ - ocultos = {"cama_birads"} # cama_riesgo_banda es propuesta desde T-21h: no se calcula ni se sirve - ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()} - - assert ids == set(DEFINICIONES) - ocultos - for indicador in ocultos: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200 - - -def test_un_indicador_retirado_da_404(client): - """T-22a (ADR-MD-009): los retirados (`/retirados/` del kit) ni se calculan ni se sirven.""" - retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")] - - assert retirados - for indicador in retirados: - assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404 - - -def test_figura_con_semestres(client): - response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro") - - assert response.status_code == 200 - assert response.mimetype == "application/json" - assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title - assert set(_x(response)) == set(SEMESTRES) - - -def test_figura_sin_periodos_usa_los_semestres_con_reporte(client): - response = _figura(client) - - assert response.status_code == 200 - assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran - - -def test_figura_con_meses(client): - response = _figura(client, query=f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert set(_x(response)) == set(MESES) - - -@pytest.mark.parametrize( - "query", - [ - "?tema=rojo", - "?periodos=2025-1", - "?periodos=2025-S3", - "?periodos=2025-13x", - "?periodos=2025-S1,", - "?periodos=abc", - "?periodos=2025-T1", # un tipo que el indicador no publica - "?periodos=2025-S1,2025-03", # tipos mezclados - ], -) -def test_figura_con_parametros_mal_formados_da_400(client, query): - response = _figura(client, query=query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "figura", "query"), - [ - ("CAMA_NO_EXISTE", FIGURA, ""), - (INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato - (INDICADOR, "fig_no_existe", ""), - (INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte - (INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"), - (INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte - ], -) -def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query): - response = _figura(client, indicador, figura, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch): - from webapi import indicadores - - def falla(*args, **kwargs): - raise KeyError("columna") - - monkeypatch.setattr(indicadores, "figura_json", falla) - with pytest.raises(KeyError): - _figura(client, query="?periodos=2025-S1") - - -# --- Todos los indicadores del proyecto --- - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_figura_de_cada_indicador(client, indicador): - for figura in figuras_de(DEFINICIONES[indicador]): - response = _figura(client, indicador, figura) - - assert response.status_code == 200, (indicador, figura) - assert set(response.get_json()) >= {"data", "layout"} - - -# --- El catálogo, los periodos, los datos y los metadatos --- - -CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"} - - -def _ruta(client, indicador: str, ruta: str, query: str = ""): - return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}") - - -def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client): - lista = client.get(f"/{PROYECTO}/indicadores").get_json() - - assert all(set(fila) == CATALOGO for fila in lista) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation) - assert fila["estratos"] == medida.extension.estratos - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador): - medida = DEFINICIONES[indicador] - - periodos = _ruta(client, indicador, "periodos") - datos = _ruta(client, indicador, "datos") - metadatos = _ruta(client, indicador, "metadatos") - - assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200) - assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos)) - assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos)) - de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"] - assert de_semestre == SEMESTRES - cuerpo = datos.get_json() - assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES) - assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"]) - assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"]) - assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura - assert metadatos.get_json()["tipo_calculo"] == medida.scoring - - -def test_datos_con_meses(client): - response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}") - - assert response.status_code == 200 - assert response.get_json()["tipo_periodo"] == "mes" - assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES - - -def test_los_datos_dicen_de_que_reporte_salen(client): - cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json() - periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"] - - (reporte,) = cuerpo["reportes"] - assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1") - assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01") - assert cuerpo["version"] == DEFINICIONES[INDICADOR].version - - -@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"]) -def test_datos_con_parametros_mal_formados_da_400(client, query): - response = _ruta(client, INDICADOR, "datos", query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "ruta", "query"), - [ - ("NO_EXISTE", "datos", ""), - ("NO_EXISTE", "periodos", ""), - ("NO_EXISTE", "metadatos", ""), - (INDICADOR, "datos", "?periodos=2030-S1"), - ], -) -def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query): - response = _ruta(client, indicador, ruta, query) - - assert response.status_code == 404 - assert "error" in response.get_json() diff --git a/tests/test_indicadores_tea.py b/tests/test_indicadores_tea.py deleted file mode 100644 index 577c102..0000000 --- a/tests/test_indicadores_tea.py +++ /dev/null @@ -1,169 +0,0 @@ -import pytest -from indicadores_kit.registry.measures import RAIZ, measures_de -from indicadores_kit.serving.figuras import figuras_de -from indicadores_kit.tea import fixtures - -DEFINICIONES = measures_de("tea") -PERIODOS = ",".join(fixtures.PERIODOS) - - -@pytest.fixture(scope="module") -def client(tmp_path_factory): - """Una base de TEA temporal, con los 20 indicadores calculados (16 en el catálogo), por `TEA_DATABASE_URL`.""" - # Dentro de la fixture: la configuración de Persistance se lee al importarla, - # y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes. - from persistance.db import get_tea_engine - from persistance.settings import settings - - ruta = tmp_path_factory.mktemp("tea") / "tea.db" - with pytest.MonkeyPatch.context() as mp: - mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}") - get_tea_engine.cache_clear() - try: - fixtures.base_de_prueba(get_tea_engine()) - - from webapi import create_app - - app = create_app() - app.config.update(TESTING=True) - with app.test_client() as cliente: - yield cliente - finally: - get_tea_engine().dispose() - get_tea_engine.cache_clear() - - -def _figura(client, indicador: str, figura: str, query: str = ""): - return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}") - - -def test_listar_indicadores(client): - response = client.get("/tea/indicadores") - assert response.status_code == 200 - - lista = response.get_json() - visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto] - assert [fila["id"] for fila in lista] == sorted(visibles) - for fila in lista: - medida = DEFINICIONES[fila["id"]] - assert fila["titulo"] == medida.title - assert fila["contrato"] == medida.extension.contrato - assert fila["figuras"] == figuras_de(medida) - - -def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client): - """Provisional (oct 2026): solo se muestran M21, M22 y los tres destacados (M23 a M25).""" - visibles = { - "M21_diagnosticados_con_eeg", - "M22_diagnosticados_sin_eeg", - "M23_pacientes_evaluados", - "M24_confirmacion_diagnostico", - "M25_dias_mchat_diagnostico", - } - ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()} - - assert ids == visibles - for oculto in sorted(set(DEFINICIONES) - visibles): - assert client.get(f"/tea/indicadores/{oculto}/metadatos").status_code == 200 - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_figura_de_cada_indicador(client, indicador): - for figura in figuras_de(DEFINICIONES[indicador]): - response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro") - - assert response.status_code == 200, figura - assert response.mimetype == "application/json" - assert "data" in response.get_json() - - -def test_figura_sin_periodos_usa_todos_los_reportes(client): - (figura,) = figuras_de(DEFINICIONES["M21_diagnosticados_con_eeg"]) - - response = _figura(client, "M21_diagnosticados_con_eeg", figura) - - assert response.status_code == 200 - assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["M21_diagnosticados_con_eeg"].title - - -@pytest.mark.parametrize( - "query", - [ - "?tema=rojo", - "?periodos=2025-1", - "?periodos=2025-S1,", - "?periodos=abc", - "?periodos=,", - ], -) -def test_figura_con_parametros_mal_formados_da_400(client, query): - response = _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", query) - - assert response.status_code == 400 - assert "error" in response.get_json() - - -@pytest.mark.parametrize( - ("indicador", "figura", "query"), - [ - ("K99_no_existe", "fig_c1_grupos", ""), - ("M21_diagnosticados_con_eeg", "fig_c3r_caja", ""), # figura de otro contrato - ("M21_diagnosticados_con_eeg", "fig_no_existe", ""), - ("M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte - ("M21_diagnosticados_con_eeg", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"), - ], -) -def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query): - response = _figura(client, indicador, figura, query) - - assert response.status_code == 404 - assert "error" in response.get_json() - - -def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch): - from webapi import indicadores - - def falla(*args, **kwargs): - raise KeyError("columna") - - monkeypatch.setattr(indicadores, "figura_json", falla) - with pytest.raises(KeyError): - _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2025-S1") - - -# --- Los periodos, los datos y los metadatos --- - - -@pytest.mark.parametrize("indicador", sorted(DEFINICIONES)) -def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador): - medida = DEFINICIONES[indicador] - - periodos = client.get(f"/tea/indicadores/{indicador}/periodos") - datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}") - metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos") - - assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200) - assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS) - cuerpo = datos.get_json() - assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato) - assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS) - assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"]) - assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura - assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo - - -def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client): - response = client.get(f"/tea/indicadores/M21_diagnosticados_con_eeg/datos?periodos={PERIODOS}") - - grupos = list(response.get_json()["grupos"]) - assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético - assert grupos[-1] == "TOTAL" - - -def test_un_indicador_retirado_da_404(client): - """T-22a (ADR-MD-009): los retirados (`tea/retirados/` del kit) ni se calculan ni se sirven.""" - retirados = [ruta.stem for ruta in (RAIZ / "tea" / "retirados").glob("*.toml")] - - assert len(retirados) == 18 - for indicador in retirados: - assert client.get(f"/tea/indicadores/{indicador}/metadatos").status_code == 404 diff --git a/tests/test_kpis_route.py b/tests/test_kpis_route.py new file mode 100644 index 0000000..5b705f5 --- /dev/null +++ b/tests/test_kpis_route.py @@ -0,0 +1,135 @@ +"""What this module covers: `webapi.kpis`, the route that answers a measure's periods on request as a FHIR `Bundle` +of `MeasureReport`s. + +Fixtures: `base`, `manifest` and `kit` from `test_metrics_on_request` (the CaCu fixture database through the cycle, +dbt's manifest, the kit's snapshot; skipped without `DBT_MANIFEST`); `client`, a Flask app with only this domain's KPI +blueprint. +""" + +import json +import os +from pathlib import Path + +import pytest +from flask import Flask + +from test_metrics_on_request import EU7, EU13, IND1, base, kit, manifest, reports # noqa: F401 +from webapi.kpis import kpis_blueprint + + +@pytest.fixture +def client(base, manifest): # noqa: F811 + app = Flask(__name__) + app.register_blueprint(kpis_blueprint("cacu", base.dominio, manifest), url_prefix="/cacu") + return app.test_client() + + +def counts(resource: dict) -> dict[str, int]: + (group,) = resource["group"] + return {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} + + +def history_entry(resource: dict) -> int: + (entry,) = [e for e in resource["extension"] if e["url"].endswith("/reporte-id")] + return entry["valueInteger"] + + +def test_a_measure_s_periods_come_as_a_bundle_of_measure_reports(base, client, kit): # noqa: F811 + """Pins down the contract: one `MeasureReport` per period asked, in order, with the kit's numbers. Fails if the + route stops answering each period, changes the shape, or the counts drift from what the cycle published.""" + response = client.get("/cacu/indicadores/IND1?periodos=2025-S1,2025-S2") + bundle = response.get_json(force=True) + + assert response.status_code == 200 and response.mimetype == "application/fhir+json" + assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 2) + for entry, period_id in zip(bundle["entry"], ("2025-S1", "2025-S2")): + report = entry["resource"] + assert report["resourceType"] == "MeasureReport" and report["measure"] == "cacu/IND1|0.3.2" + numerator, denominator = kit[IND1][period_id]["published"]["total|total"] + assert counts(report) == {"initial-population": denominator, "denominator": denominator, + "numerator": numerator} + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_ind1.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") + + +def test_without_a_knowledge_cutoff_the_last_load_makes_the_answer_stable(base, client): # noqa: F811 + """Pins down: by default the knowledge cut-off is the last load's start, so asking again before the next load + reads the stored answer. Fails if the default becomes "now", which would store a new answer per request.""" + first = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True) + before = reports(base) + second = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True) + + assert history_entry(second["entry"][0]["resource"]) == history_entry(first["entry"][0]["resource"]) + assert reports(base) == before + + +def test_a_measure_with_strata_brings_its_stratifier(client): + """Pins down: EU13's reports carry its strata, by age and by follow-up status. Fails if the route drops one.""" + bundle = client.get("/cacu/indicadores/CACU_EU13?periodos=2025-S1").get_json(force=True) + stratifiers = bundle["entry"][0]["resource"]["group"][0]["stratifier"] + + assert [s["code"][0]["text"] for s in stratifiers] == ["grupo_edad", "estatus_seguimiento"] + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu13.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") + + +def test_the_list_names_what_is_answered_on_request(client): + """Pins down: `/indicadores` lists the measures the manifest defines for the domain. Fails if one is missing.""" + listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()} + + assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE", + "CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA", + "CACU_RIESGO_BANDA"} + + +def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client): + """Pins down the route for durations: the samples measurable and measured as populations, the median as the + score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day + by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its + contract changes.""" + bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True) + (entry,) = bundle["entry"] + report = entry["resource"] + (group,) = report["group"] + assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3" + assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == { + "initial-population": 4, "measure-observation": 2} + assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d" + assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75] + assert any(e["url"].endswith("corte-evento") for e in report["extension"]) + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") + + +@pytest.mark.parametrize(("path", "status"), [ + ("/cacu/indicadores/NOPE?periodos=2025-S1", 404), + ("/cacu/indicadores/IND1", 400), + ("/cacu/indicadores/IND1?periodos=2025-S1&corte_evento=30-06-2025", 400), + ("/cacu/indicadores/IND1?periodos=2025-S1&corte_conocimiento=ayer", 400), + ("/cacu/indicadores/IND1?periodos=2031-S1", 404), +]) +def test_a_bad_question_gets_a_clear_error(client, path, status): + """Pins down the errors: an unknown measure or period is 404, a missing or misspelled parameter 400. Fails if one + of them becomes a 500.""" + response = client.get(path) + + assert response.status_code == status and "error" in response.get_json() + + +def test_a_composition_comes_with_its_categories(client, kit): + """Pins down: EU7's reports carry the categories as a `resultado` stratifier, with the kit's counts, under the + route's default knowledge cut-off (the last load). Fails if the route stops telling compositions from + proportions, or a result's knowledge date stops being compared as the type it's stored in.""" + bundle = client.get("/cacu/indicadores/CACU_EU7?periodos=2025-S1,2025-S2").get_json(force=True) + stratifiers = [e["resource"]["group"][0]["stratifier"][0] for e in bundle["entry"]] + + assert [s["code"] for s in stratifiers] == [[{"text": "resultado"}]] * 2 + for stratifier, period_id in zip(stratifiers, ("2025-S1", "2025-S2")): + expected = {k.split("|")[2]: n for k, n in kit[EU7][period_id]["published"].items() if k.startswith("total|")} + assert {s["value"]["text"]: s["population"][0]["count"] for s in stratifier["stratum"]} == expected + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu7.json").write_text( + json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8") diff --git a/tests/test_measure_cases.py b/tests/test_measure_cases.py new file mode 100644 index 0000000..a0ffa77 --- /dev/null +++ b/tests/test_measure_cases.py @@ -0,0 +1,100 @@ +"""What this module covers: compositions answered from dbt's semantic layer on the hand-written cases their rules were +written with, one database per case: CACU_CONFIRMACION_CITOLOGIA (`fixtures/casos_confirmacion_citologia.toml`: the +last valid sample decides, the most severe biopsy of that sample by the cut-off is the category, a biopsy of another +sample doesn't count) and CACU_RIESGO_BANDA (`fixtures/casos_riesgo_banda.toml`: the current batch of estimates, the +latest version of each, the bands by the rules' cut points). + +Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each +`pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views +created by the cycle (`catalogos` … `modelos`; needs `DBT_MANIFEST`). +""" + +import json +import os +import tomllib +from dataclasses import replace +from datetime import date +from pathlib import Path + +import pytest +from sqlalchemy import text + +from conftest import base_de +from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, EvaluacionRiesgo, EvaluacionRiesgoLote +from core.cacu.models import BiopsiaCervical, CitologiaCervical, Paciente +from webapi.compositions import answer_composition, composition_definitions +from webapi.metrics import Question + +FIXTURES = Path(__file__).parent / "fixtures" +FILES = ("casos_confirmacion_citologia.toml", "casos_riesgo_banda.toml") +TABLES = {m.__tablename__: m for m in (CitologiaCervical, BiopsiaCervical, CohorteArmado, CohorteMiembro, + EvaluacionRiesgoLote, EvaluacionRiesgo)} +STAGING = ("citologiacervical", "biopsiacervical") +# Rows go in by their parents first. +ORDER = ("citologiacervical", "biopsiacervical", "cohorte_armado", "cohorte_miembro", "evaluacion_riesgo_lote", + "evaluacion_riesgo") + + +def cases(): + for name in FILES: + document = tomllib.loads((FIXTURES / name).read_text(encoding="utf-8")) + templates = document.get("plantillas", {}) + for case in document["caso"]: + rows = [row for t in case.get("incluye", ()) for row in templates[t]] + case["filas"] + yield pytest.param(document["measure"], {**case, "filas": rows}, id=case["nombre"]) + + +def rows_of(case: dict): + """What the case's rows insert: a patient for each `pac_id`, then every row by its parents first.""" + def insert(session): + for pac_id in sorted({row["pac_id"] for row in case["filas"] if "pac_id" in row}): + session.add(Paciente(pac_id=pac_id, pac_id_hospital=f"H-{pac_id:03d}", pac_sexo="Femenino", + pac_fecha_nacimiento=date(1980, 1, 1))) + session.flush() + for row in sorted(case["filas"], key=lambda r: ORDER.index(r["tabla"])): + data = {k: v for k, v in row.items() if k != "tabla"} + if row["tabla"] in STAGING: + data["pac_id_hospital"] = f"H-{row['pac_id']:03d}" + session.add(TABLES[row["tabla"]](**data)) + session.flush() + session.commit() + return insert + + +@pytest.mark.parametrize(("url", "case"), list(cases())) +def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case): + """Pins down each hand-written case: the count in each category it names (zero included), the patients in the + categories it lists and their stratum values, at its cut-off and with its rules. Fails if the measure stops + meaning what the case says; the case's name says which rule.""" + manifest = os.environ.get("DBT_MANIFEST") + if not manifest: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + base = base_de("cacu", tmp_path, rows_of(case)) + base.correr("catalogos", "cargar", "registro", "definiciones", "modelos", parametros=sin_supresion, + permitir_sin_definir=True) + with base.motor.begin() as connection: + for key, value in case.get("parametros", {}).items(): + connection.execute(text("update def_parametro set valor = :v where clave = :k"), + {"v": json.dumps(value), "k": key}) + definition = composition_definitions(Path(manifest))[url] + d = base.dominio + for period_id in sorted({*case.get("espera", {}), *case.get("unidades", {}), *case.get("estratos", {})}): + result = answer_composition( + "cacu", definition, Question(url, period_id, case.get("corte")), parameters=d.def_parametro_repository, + periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository, + allow_undecided=True) + for category, n in case.get("espera", {}).get(period_id, {}).items(): + assert result.categories.get(category.removeprefix("cat:"), 0) == n, (period_id, category) + with base.motor.connect() as connection: + units = connection.execute(text( + "select valor_id, unidad_id from measure_report_unidad where report_id = :r"), + {"r": result.report_id}).all() + strata = connection.execute(text( + "select estrato_id, unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r"), + {"r": result.report_id}).all() + for category, expected in case.get("unidades", {}).get(period_id, {}).items(): + assert sorted(u for v, u in units if v == category.removeprefix("cat:")) == sorted(map(str, expected)), ( + period_id, category) + for stratum, expected in case.get("estratos", {}).get(period_id, {}).items(): + assert {u: v for s, u, v in strata if s == stratum} == expected, (period_id, stratum) + base.motor.dispose() diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py new file mode 100644 index 0000000..c93f30d --- /dev/null +++ b/tests/test_metrics_on_request.py @@ -0,0 +1,461 @@ +"""What this module covers: `webapi.metrics` and `webapi.compositions`, CaCu's measures answered on request from +dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which +keeps each answer under its key. + +Fixtures: `base`, the CaCu fixture database through the cycle up to `modelos` (which creates dbt's event models); +`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13 +and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against. +""" + +import json +import os +import time +from dataclasses import replace +from datetime import date, datetime, timezone +from pathlib import Path + +import pytest +from sqlalchemy import text +from sqlmodel import Session, select + +from conftest import base_de +from core.cacu.models import BiopsiaCervical, CitologiaCervical +from webapi.compositions import answer_composition, composition_definitions, composition_report +from webapi.metrics import Question, answer, measure_definitions, measure_report +from webapi.orquestacion import correr + +IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7" +STATUS = "estatus_seguimiento" +HASTA_MODELOS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") +PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"] +SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json" + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture +def base(tmp_path, sin_supresion, manifest): + base = base_de("cacu", tmp_path) + base.correr(*HASTA_MODELOS, parametros=sin_supresion, permitir_sin_definir=True) + yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.motor.dispose() + + +@pytest.fixture +def kit(): + return json.loads(SNAPSHOT.read_text(encoding="utf-8")) + + +@pytest.fixture +def definition(manifest): + return measure_definitions(manifest)[IND1] + + +@pytest.fixture +def eu13(manifest): + return measure_definitions(manifest)[EU13] + + +@pytest.fixture +def eu7(manifest): + return composition_definitions(manifest)[EU7] + + +def repositories(base) -> dict: + d = base.dominio + return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, + "history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True} + + +def ask(base, definition, period_id, *, event_cutoff=None, knowledge_cutoff=None): + question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff) + if definition.url == EU7: + return answer_composition("cacu", definition, question, **repositories(base)) + return answer("cacu", definition, question, **repositories(base)) + + +def units(base, report_id: int) -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select grupo, resultado_id, unidad_id, pac_id, valor_id from measure_report_unidad where report_id = :r"), + {"r": report_id}).all())) + + +def strata_rows(base, report_id: int, stratum: str = "grupo_edad") -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r " + "and estrato_id = :e"), {"r": report_id, "e": stratum}).all())) + + +def proportion_cells(result) -> dict: + """An answer as the snapshot keeps what `v_c1` published: `{"stratum|value": [numerator, denominator]}`.""" + cells = {"total|total": [result.numerator, result.denominator]} + for stratum, values in result.strata.items(): + cells |= {f"{stratum}|{v}": [c.numerator, c.denominator] for v, c in values.items()} + return cells + + +def composition_cells(result) -> dict: + """An answer as the snapshot keeps what `v_c2` published: `{"stratum|value|category": n}`.""" + cells = {f"total|total|{c}": n for c, n in result.categories.items()} + for stratum, values in result.strata.items(): + cells |= {f"{stratum}|{v}|{c}": n for v, cs in values.items() for c, n in cs.items()} + return cells + + +def without(cells: dict, stratum: str) -> dict: + return {k: v for k, v in cells.items() if not k.startswith(f"{stratum}|")} + + +def reports(base) -> int: + with base.motor.connect() as connection: + return connection.execute(text("select count(*) from measure_report")).scalar_one() + + +def reload(base, change) -> None: + """Changes the staging as the ingestion would and runs `cargar`: a new load, known later than everything before.""" + time.sleep(0.01) + with Session(base.motor) as session: + change(session) + session.commit() + correr(base.ctx, solo=["cargar"]) + + +def test_ind1_answers_what_the_kit_computed(base, definition, kit): + """Pins down: with no cut-off, every period's IND1 has the kit's units and its numbers. Fails if the semantic + definition (event model, metrics, filter) stops meaning what the kit's IND1 meant.""" + for period_id in PERIODS: + result, expected = ask(base, definition, period_id), kit[IND1][period_id] + assert units(base, result.report_id) == expected["units"], period_id + assert proportion_cells(result)["total|total"] == expected["published"].get("total|total", [0, 0]), period_id + + +def test_eu13_with_its_age_strata_answers_what_the_kit_computed(base, eu13, kit): + """Pins down: EU13 gives the kit's units, each patient's age group at the period's start and the numbers by age + in every period. Fails if the event model, the report date's condition or the age from `dim_fecha` drift.""" + for period_id in PERIODS: + result, expected = ask(base, eu13, period_id), kit[EU13][period_id] + assert units(base, result.report_id) == expected["units"], period_id + assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id + assert without(proportion_cells(result), STATUS) == (expected["published"] or {"total|total": [0, 0]}), period_id + + +def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7, kit): + """Pins down EU7, a composition: each patient in the category of her last valid sample (with a result and a + satisfactory specimen) or SIN_DATO, with her age group, and the kit's counts by category, total and by age. + Fails if the ranking (validity, then the latest sample, then the source id) or the validity rule drifts.""" + for period_id in PERIODS: + result, expected = ask(base, eu7, period_id), kit[EU7][period_id] + assert units(base, result.report_id) == expected["units"], period_id + assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id + assert without(composition_cells(result), STATUS) == expected["published"], period_id + + +def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7): + """Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same + answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing.""" + for d in (definition, eu13, eu7): + first = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30)) + before = reports(base) + again = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30)) + assert (again.report_id, again.stored_before, reports(base)) == (first.report_id, True, before) + if d is eu7: + assert (again.categories, again.strata) == (first.categories, first.strata) + else: + assert proportion_cells(again) == proportion_cells(first) + + +def test_the_event_cutoff_leaves_out_later_facts(base, definition, kit): + """Pins down: S1 cut at March 31 counts the patients of January to March: the union of the kit's monthly units. + Fails if the cut-off stops filtering the event date.""" + result = ask(base, definition, "2025-S1", event_cutoff=date(2025, 3, 31)) + months = sorted({tuple(u) for m in (1, 2, 3) for u in kit[IND1][f"2025-{m:02d}"]["units"]}) + + assert units(base, result.report_id) == [list(u) for u in months] + + +def test_a_late_fact_counts_only_under_a_later_knowledge_cutoff(base, definition): + """Pins down: a cytology of S1 loaded later doesn't change what was known before its load; asked with a later + knowledge cut-off, it counts. Fails if `conocida_en` stops being a condition of the question.""" + known = datetime.now(timezone.utc) + before = ask(base, definition, "2025-S1", knowledge_cutoff=known) + + def late_cytology(session): + h005 = session.exec(select(CitologiaCervical).where(CitologiaCervical.pac_id_hospital == "H-005")).first() + session.add(CitologiaCervical(pac_id=h005.pac_id, pac_id_hospital="H-005", cit_fecha_toma=date(2025, 3, 10), + cit_calidad_especimen="SATISFACTORIO", cit_fecha_reporte=date(2025, 3, 20), + cit_celulas_escamosas="LIEAG")) + reload(base, late_cytology) + + again = ask(base, definition, "2025-S1", knowledge_cutoff=known) + fresh_then = ask(base, definition, "2025-S1", knowledge_cutoff=known, event_cutoff=date(2025, 6, 30)) + now = ask(base, definition, "2025-S1", knowledge_cutoff=datetime.now(timezone.utc)) + + assert again.report_id == before.report_id + assert (fresh_then.numerator, fresh_then.denominator) == (before.numerator, before.denominator) + assert (now.numerator, now.denominator) == (before.numerator + 1, before.denominator + 1) + + +def test_a_changed_fact_is_kept_by_the_history_not_by_the_knowledge_cutoff(base, definition): + """Pins down the limit of the knowledge cut-off: silver keeps one version of each row, so after H-004's LIEAG of + July becomes NEGATIVO, recomputing S2 as known before the change can't give the old numerator; only the stored + answer still does. Fails if silver starts keeping versions (`dbt snapshot`): then expect the old one.""" + known = datetime.now(timezone.utc) + shown = ask(base, definition, "2025-S2", knowledge_cutoff=known) + assert shown.numerator == 1 + + def corrected(session): + row = session.exec(select(CitologiaCervical).where( + CitologiaCervical.pac_id_hospital == "H-004", CitologiaCervical.cit_fecha_toma == date(2025, 7, 1))).one() + row.cit_celulas_escamosas = "NEGATIVO" + reload(base, corrected) + + stored = ask(base, definition, "2025-S2", knowledge_cutoff=known) + recomputed_then = ask(base, definition, "2025-S2", knowledge_cutoff=known, event_cutoff=date(2025, 12, 31)) + + assert (stored.report_id, stored.numerator) == (shown.report_id, 1) + assert recomputed_then.numerator == 0 # the July result now counts as known after `known`: it's left out + assert ask(base, definition, "2025-S2", knowledge_cutoff=datetime.now(timezone.utc)).numerator == 0 + + +def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base, eu13): + """Pins down EU13's numerator, which the fixture leaves at 0: once H-004's biopsy of August 1 (from the July 1 + sample) is LIEAG she counts in 2025-07 and 2025-S2, and an event cut-off before the report leaves her out. + Fails if the numerator stops following the sample's period, the grade rule, or the report's date.""" + def lieag(session): + biopsy = session.exec(select(BiopsiaCervical).where(BiopsiaCervical.pac_id_hospital == "H-004")).one() + biopsy.bx_cin_grado = "LIEAG" + reload(base, lieag) + + assert ask(base, eu13, "2025-07").numerator == 1 + assert ask(base, eu13, "2025-S2").numerator == 1 + assert ask(base, eu13, "2025-S2", event_cutoff=date(2025, 7, 31)).numerator == 0 + + +def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7): + """Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's + inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's + categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer.""" + period = base.dominio.dim_periodo_repository.get("2025-S1") + at = datetime(2026, 1, 2, tzinfo=timezone.utc) + + report = measure_report(definition, Question(IND1, "2025-S1"), ask(base, definition, "2025-S1"), period, at) + (group,) = report["group"] + assert report["measure"] == "cacu/IND1|0.3.2" + assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"} + assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == { + "initial-population": 4, "denominator": 4, "numerator": 1} + assert group["measureScore"] == {"value": 0.25} + assert report["improvementNotation"]["coding"][0]["code"] == "decrease" + + stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period, + at)["group"][0]["stratifier"] + assert [s["code"] for s in stratifiers] == [[{"text": "grupo_edad"}], [{"text": STATUS}]] + + composition = composition_report(eu7, Question(EU7, "2025-S1"), ask(base, eu7, "2025-S1"), period, at) + by_result = composition["group"][0]["stratifier"][0] + assert by_result["code"] == [{"text": "resultado"}] + assert {s["value"]["text"]: s["population"][0]["count"] for s in by_result["stratum"]} == { + "LIEBG": 1, "NEGATIVO": 2, "SIN_DATO": 1} + if os.environ.get("MEASURE_REPORT_OUT"): + Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8") + + +ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json" +TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE" +DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO" + + +@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO]) +def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url): + """Pins down the duration construct, for the time to the result and the time to the first note that resolves + the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the + cut-off (and, to diagnosis, unless a cervical cancer note came before it); the measured ones carry their days + (`dim_fecha.dia_num` differences); n, the median and the quartiles (inclusive, ANSI) and the excluded are the + kit's where it didn't suppress them (suppression isn't part of the prototype). Fails if the horizon, the day + arithmetic, the resolving note, the exclusion or the quartiles' interpolation drift.""" + from webapi.durations import answer_duration, duration_definitions + + expected = json.loads(ORACLE.read_text(encoding="utf-8"))[url] + definition = duration_definitions(manifest)[url] + for period_id, kit_report in expected["periodos"].items(): + result = answer_duration("cacu", definition, Question(url, period_id), **repositories(base)) + assert units_with_numbers(base, result.report_id) == kit_report["units"], period_id + published = dict(zip(kit_report["published_columns"], next( + row for row in kit_report["published"] if row[1] == "total"))) + if published["suprimido"]: + continue + assert (result.n, result.median, result.q1, result.q3, result.excluded) == ( + published["n"], published["mediana"], published["q1"], published["q3"], published["n_excluido"]), period_id + + +def units_with_numbers(base, report_id: int) -> list[list]: + with base.motor.connect() as connection: + return sorted(map(list, connection.execute(text( + "select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad " + "where report_id = :r"), {"r": report_id}).all())) + + +def test_the_follow_up_status_is_the_kit_s_in_every_period(base, eu13, eu7): + """Pins down: EU13's and EU7's `estatus_seguimiento` gives each unit the kit's status at the period's start, and + the kit's published numbers by status. Fails if the timeline stratum, the procedures it infers or the order of + the values drift. The fixture's patients are all PRE_COLPOSCOPIA; the other statuses are pinned down by + `test_the_follow_up_status_follows_the_timeline`.""" + oracle = json.loads(ORACLE.read_text(encoding="utf-8")) + for period_id in PERIODS: + for definition in (eu13, eu7): + result, expected = ask(base, definition, period_id), oracle[definition.url]["periodos"][period_id] + assert strata_rows(base, result.report_id, STATUS) == sorted( + [u, v] for u, s, v in expected["strata"] if s == STATUS), (definition.url, period_id) + rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]] + if definition is eu13: + published = {f"{STATUS}|{r['estrato_valor']}": [r["numerador"], r["denominador"]] + for r in rows if r["estrato_id"] == STATUS} + ours = {k: v for k, v in proportion_cells(result).items() if k.startswith(f"{STATUS}|")} + else: + published = {f"{STATUS}|{r['estrato_valor']}|{r['categoria']}": r["n"] + for r in rows if r["estrato_id"] == STATUS and r["n"]} + ours = {k: v for k, v in composition_cells(result).items() if k.startswith(f"{STATUS}|")} + assert ours == published, (definition.url, period_id) + + +def kit_status(base, reference: str) -> dict[str, str]: + """What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules.""" + import tomllib + + from indicadores_kit.cacu.seguimiento import estatus_al, reglas_de + from indicadores_kit.registry.parametros import RUTA_PARAMETROS + from indicadores_kit.serving.seguimiento import leer_estrato + from sqlalchemy import bindparam + + rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8")) + + def rule(key): + node = rules + for part in key.split("."): + node = node[part] + return node["valor"] + + values = {name: rule(key) for name, key in leer_estrato("cacu", STATUS).parametros.items()} + status = estatus_al(bindparam("referencia"), reglas_de(values)) + query = select(status.c.pac_id, status.c.estatus) + named = set(query.compile().params) + with base.motor.connect() as connection: + rows = connection.execute(query, {n: v for n, v in {**values, "referencia": reference}.items() if n in named}) + return {str(pac_id): value for pac_id, value in rows} + + +def follow_up(session) -> None: + """Notes and orders that move three of the fixture's patients along follow-up, in a load of their own. + + Patient 1 (sampled 2025-02-10): a valuation visit, a colposcopy note by its reason (with an accent) and a biopsy + order that day, then a treatment note: POST_TRATAMIENTO from then on. Patient 4 (sampled 2025-05-30): a + valuation visit, then a colposcopy note whose ICD-10 came «S/C» but whose diagnosis text names HPV: + POST_COLPOSCOPIA. Patient 3 (sampled 2025-01-20): a colposcopy note with no valuation before it, which doesn't + count, and her first cytology ordered by a specialty outside surveillance: no status holds, INFO_INSUFICIENTE. + """ + from core.cacu.indicadores.models import Carga, Observacion, Procedimiento + + load = Carga(fuente="seguimiento", inicio=datetime.now(timezone.utc)) + session.add(load) + session.flush() + + def procedure(pac_id, study, kind, when, key, **observed) -> Procedimiento: + p = Procedimiento(fuente_tabla="seguimiento", fuente_id=key, carga_id=load.carga_id, pac_id=pac_id, + estudio_id=study, clase=kind, fecha=date.fromisoformat(when)) + session.add(p) + session.flush() + for result, (column_name, value) in observed.items(): + session.add(Observacion(procedimiento_id=p.procedimiento_id, carga_id=load.carga_id, pac_id=pac_id, + resultado_id=result.replace("__", "."), **{column_name: value})) + return p + + def note(pac_id, when, key, *, cie, specialty="CLINICA_MUJER_COLPOSCOPIA", reason=None, text_dx=None): + observed = {"nota_medica__diagnostico": ("valor_texto", cie), + "nota_medica__especialidad": ("valor_id", specialty)} + if reason: + observed["nota_medica__motivo"] = ("valor_texto", reason) + if text_dx: + observed["nota_medica__diagnostico_texto"] = ("valor_texto", text_dx) + procedure(pac_id, "nota_medica", "encuentro", when, key, **observed) + + note(1, "2025-02-20", "n1a", cie="R876") + note(1, "2025-03-03", "n1b", cie="Z000", reason="Acude a colposcopía") + procedure(1, "biopsia", "orden", "2025-03-03", "o1") + note(1, "2025-04-01", "n1c", cie="D06", specialty="CIRUGIA_ONCOLOGICA") + note(4, "2025-06-05", "n4a", cie="R876") + note(4, "2025-06-10", "n4b", cie="S/C", text_dx="Virus del papiloma humano") + note(3, "2025-01-25", "n3a", cie="Z000", reason="COLPOSCOPIA") + order = procedure(3, "citologia", "orden", "2025-01-19", "c3", + orden__especialidad=("valor_id", "CIRUGIA_ONCOLOGICA")) + (sample,) = session.exec(select(Procedimiento).where( + Procedimiento.pac_id == 3, Procedimiento.estudio_id == "citologia", Procedimiento.clase == "toma", + Procedimiento.fecha == date(2025, 1, 20))).all() + sample.padre_id = order.procedimiento_id + + +def test_the_follow_up_status_follows_the_timeline(base, eu13, eu7): + """Pins down: with colposcopies and a treatment on the timeline, every unit of EU13 and EU7 in every period gets + the status the kit's `estatus_al` gives her at the period's start, and all four statuses come out; asked with a + knowledge cut-off before those facts arrived, they're PRE_COLPOSCOPIA again. Fails if an inferred procedure + (the valuation requirement, the same-day order, the accent-blind reason, the diagnosis text), the timeline + stratum or the values' order stops meaning what the kit's rules mean.""" + with base.motor.connect() as connection: + before_load = connection.execute(text("select max(inicio) from carga")).scalar_one() + with Session(base.motor) as session: + follow_up(session) + session.commit() + + seen = set() + for period_id in PERIODS: + start = base.dominio.dim_periodo_repository.get(period_id).inicio.isoformat() + expected = kit_status(base, start) + for definition in (eu13, eu7): + ours = dict(strata_rows(base, ask(base, definition, period_id).report_id, STATUS)) + assert ours == {unit: expected[unit] for unit in ours}, (definition.url, period_id) + seen |= set(ours.values()) + assert seen == {"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA", "POST_TRATAMIENTO", "INFO_INSUFICIENTE"} + + known_then = datetime.fromisoformat(before_load) + earlier = ask(base, eu13, "2025-10", knowledge_cutoff=known_then) + assert set(dict(strata_rows(base, earlier.report_id, STATUS)).values()) == {"PRE_COLPOSCOPIA"} + + +def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_yet(base, manifest): + """Pins down the cut-off of the time to diagnosis: in 2025-S2 cut at September 30, the July sample resolved in + August is measured (40 days); the August sample, resolved only in January, and the September one, with no note, + are still within 180 days, so they aren't measured yet; the October sample is after the cut. Fails if a note + after the cut-off counts, or a pending sample enters the initial population.""" + from webapi.durations import answer_duration, duration_definitions + + definition = duration_definitions(manifest)[DIAS_TOMA_DIAGNOSTICO] + result = answer_duration("cacu", definition, Question(DIAS_TOMA_DIAGNOSTICO, "2025-S2", date(2025, 9, 30)), + **repositories(base)) + assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0) + + +CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA" + + +def test_the_confirmation_by_biopsy_is_the_kit_s_in_every_period(base, manifest): + """Pins down the composition that follows the chosen fact: each patient whose last valid sample of the period is + high grade, in the grade of the most severe biopsy that sample led to by the cut-off (SIN_BIOPSIA without one), + by that sample's result; units, strata and counts are the kit's in every period. Fails if the two-level ranking, + the admission on the chosen sample, the severity order or the chosen-row stratum drift.""" + oracle = json.loads(ORACLE.read_text(encoding="utf-8"))[CONFIRMACION] + definition = composition_definitions(manifest)[CONFIRMACION] + for period_id, expected in oracle["periodos"].items(): + result = answer_composition("cacu", definition, Question(CONFIRMACION, period_id), **repositories(base)) + assert units(base, result.report_id) == [u[:5] for u in expected["units"]], period_id + assert strata_rows(base, result.report_id, "citologia_alto_grado") == sorted( + [u, v] for u, s, v in expected["strata"] if s == "citologia_alto_grado"), period_id + rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]] + published = {f"{r['estrato_id']}|{r['estrato_valor']}|{r['categoria']}": r["n"] for r in rows if r["n"]} + assert {k: v for k, v in composition_cells(result).items() if v} == published, period_id diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 76c1dd7..b8cf16c 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -1,21 +1,19 @@ -"""El ciclo deja los mismos reportes que la base de demostración del kit. +"""What this module covers: the whole cycle on the CaCu fixture database, in order, once and again. -Dos bases con el mismo staging (los fixtures del kit): -- una armada por la orquestación: Alembic, carga, vistas, registro y cálculo; -- otra por `indicadores_kit.demostracion.base_de_prueba`, que es la que usa la compuerta. - -Los reportes tienen que coincidir valor por valor. Volver a correr el ciclo no -agrega reportes. +Fixtures: `bases`, one database loaded by the cycle from the kit's synthetic staging, with dbt's manifest +(`DBT_MANIFEST`) for the definitions and the event models. The cycle computes no measure: they're answered on request +(`test_metrics_on_request`), so running it again adds no report. """ +import os from datetime import date +from pathlib import Path from importlib import import_module import pytest from sqlalchemy import create_engine, text from sqlmodel import Session -from indicadores_kit.demostracion import base_de_prueba from webapi.orquestacion import Contexto, correr from webapi.orquestacion.conexion import apuntar @@ -27,12 +25,9 @@ CONSULTA = text(""" FROM measure_report_unidad u JOIN measure_report r USING (report_id)""") -def valores(motor) -> list[tuple]: - with motor.connect() as con: - return sorted(tuple(str(x) for x in fila) for fila in con.execute(CONSULTA)) -@pytest.fixture(scope="module", params=["cacu", "cama", "tea"]) +@pytest.fixture(scope="module", params=["cacu", "cama"]) def bases(request, tmp_path_factory): proyecto = request.param carpeta = tmp_path_factory.mktemp(proyecto) @@ -40,16 +35,14 @@ def bases(request, tmp_path_factory): apuntar(proyecto, url) # `observar` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de # dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo. - ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True) + ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"])) correr(ctx, solo=["migrar"]) motor = create_engine(url) with Session(motor) as sesion: import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) sesion.commit() pasos = correr(ctx) - demostracion = create_engine(f"sqlite:///{carpeta / 'demostracion.db'}") - base_de_prueba(demostracion, proyecto) - return proyecto, ctx, motor, demostracion, pasos + return proyecto, ctx, motor, None, pasos def test_corre_todos_los_pasos_en_orden(bases): @@ -57,17 +50,13 @@ def test_corre_todos_los_pasos_en_orden(bases): nombres = [p.nombre for p in pasos] # `migrar` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9). assert nombres[0] == "migrar" and nombres.index("catalogos") < nombres.index("cargar") - assert nombres.index("calcular") < nombres.index("observar") + assert nombres.index("cargar") < nombres.index("modelos") and "calcular" not in nombres -def test_los_reportes_son_los_de_la_base_de_demostracion(bases): - _, _, motor, demostracion, _ = bases - orquestados, esperados = valores(motor), valores(demostracion) - assert orquestados, "el ciclo no calculó nada" - assert orquestados == esperados def test_volver_a_correr_no_agrega_reportes(bases): + """Pins down: the cycle computes no measure (they're answered on request): running it adds no report.""" _, ctx, motor, _, _ = bases with motor.connect() as con: antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() @@ -88,37 +77,6 @@ def test_en_cacu_arma_su_cohorte_una_vez(bases): text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one() -def test_cada_reporte_guarda_sus_unidades(bases): - """Todo reporte lleva la huella de sus unidades de §6f (T-19b, T-19e): sin ella, las vistas lo darían en 0.""" - _, _, motor, _, _ = bases - with motor.connect() as con: - sin = con.execute(text("SELECT COUNT(*) FROM measure_report WHERE huella IS NULL")).scalar_one() - con_unidades = con.execute(text("SELECT COUNT(DISTINCT report_id) FROM measure_report_unidad")).scalar_one() - assert sin == 0 and con_unidades > 0 -def test_cada_reporte_se_mide_y_se_guarda_en_una_sola_sesion(bases): - """La regla de §6 en `calcular`: antes eran dos sesiones (medir y guardar).""" - from functools import partial - - from indicadores_kit.oro.calculo import medir_con_unidades - from indicadores_kit.registry.measures import measures_de - from indicadores_kit.tablas import tablas_de - from persistance.aristas.oro import CalculoRepository - - proyecto, _, motor, _, _ = bases - tablas = tablas_de(proyecto) - abiertas = [] - - def fabrica(): - abiertas.append(1) - return Session(motor) - - calculo = CalculoRepository(fabrica, tablas.MeasureReport, periodo=tablas.DimPeriodo) - medida = next(iter(measures_de(proyecto).values())) - tipo = medida.extension.publicacion.tipos_periodo[0] - periodo_id = calculo.periodos(tipo, date(ANIO, 1, 1), date(ANIO + 1, 1, 1))[0] - abiertas.clear() - calculo.calcular(partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas)) - assert len(abiertas) == 1 diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index ccc3392..fbaf427 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -1,4 +1,4 @@ -"""Los pasos de oro sobre la base del dominio: el registro, las definiciones y el cálculo. +"""Los pasos de oro sobre la base del dominio: el registro y las definiciones (el catálogo, del manifiesto de dbt). Vienen del kit (`test_pasos` y `test_produccion`, MD-16). El reporte se lee por los repositorios de Persistance, como lo leería `WebApi`. @@ -7,91 +7,34 @@ repositorios de Persistance, como lo leería `WebApi`. from datetime import date import pytest -from sqlalchemy import text -from sqlmodel import select -from indicadores_kit.cacu import fixtures as fixtures_cacu -from indicadores_kit.cama import fixtures as fixtures_cama from indicadores_kit.plata.carga import tablas_de_staging -from indicadores_kit.registry.measures import leer_measure, measures_de, ruta_de_measure from indicadores_kit.registry.edades import grupos_de_cortes from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.serving.contratos import ultimo_reporte from indicadores_kit.tablas import tablas_de -from indicadores_kit.tea import fixtures as fixtures_tea from webapi.orquestacion.proyecto import tipos_de_periodo from conftest import ANIO # El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}. -EJEMPLO = {"cacu": "ind1", "cama": "cama_confirmacion_birads45", "tea": "M24_confirmacion_diagnostico"} -TOTAL = {"cacu": "principal", "cama": "principal", "tea": "TOTAL"} -ESPERADO = { - "cacu": fixtures_cacu.ESPERADO_IND1, - "cama": fixtures_cama.ESPERADO_CAMA_CONFIRMACION_BIRADS45, - "tea": {p: v["TOTAL"][:2] for p, v in fixtures_tea.ESPERADO["M24_confirmacion_diagnostico"].items()}, -} -# Un dato de staging que cambia el numerador del ejemplo: (tabla de STAGING, columna con que se busca, su valor, -# columna que cambia, valor nuevo). CaCu: la citología NEGATIVO de H-001 pasa a LIEAG (anómala). CaMa: la -# mastografía B0 del 10 de marzo, que ya tiene biopsia, pasa a B4A (de sospecha). TEA: la nota R62.0 de T-03 pasa -# a F84.0 (confirma el diagnóstico). -CAMBIO = { - "cacu": ("citologiacervical", "cit_fecha_toma", date(2025, 2, 10), "cit_celulas_escamosas", "LIEAG"), - "cama": ("mastografia", "mast_fecha_toma", date(2025, 3, 10), "mast_birads", "B4A"), - "tea": ("nota_medica", "nm_id", "nm-03", "nm_cie_codigo", "F84.0"), -} - - def cargas(proyecto) -> tuple[str, ...]: """El paso que lleva el staging a la plata (staging directo, T-20c).""" return ("cargar",) -def hasta_calcular(proyecto) -> tuple[str, ...]: - return ("catalogos", *cargas(proyecto), "vistas", "registro", "definiciones", "calcular") -def cambiar_staging(base) -> None: - tabla, llave, valor_llave, columna, nuevo = CAMBIO[base.proyecto] - modelo = {m.__tablename__: m for m in tablas_de_staging(base.proyecto)}[tabla] - with base.staging() as sesion: - (fila,) = sesion.exec(select(modelo).where(getattr(modelo, llave) == valor_llave)).all() - setattr(fila, columna, nuevo) - sesion.commit() -def ejemplo(proyecto): - return leer_measure(ruta_de_measure(proyecto, EJEMPLO[proyecto])) -def conteos(base, report_id: int) -> tuple[int, int]: - """(denominador sin exclusiones, numerador) del grupo total, de lo que publica `v_c1` (T-19e).""" - with base.motor.connect() as con: - return tuple(con.execute(text( - "SELECT denominador, numerador FROM v_c1 WHERE report_id = :r AND grupo = :g AND estrato_id = 'total'"), - {"r": report_id, "g": TOTAL[base.proyecto]}).one()) -def reportes_del_ejemplo(base, periodo_id="2025-S1", nombre=None) -> list: - measure = leer_measure(ruta_de_measure(base.proyecto, nombre)) if nombre else ejemplo(base.proyecto) - return [r for r in base.dominio.measure_report_repository.list(limit=10_000) - if r.measure_url == measure.url and r.periodo_id == periodo_id] -def ultimo(base, periodo_id="2025-S1") -> int: - with base.staging() as sesion: - return ultimo_reporte(sesion, ejemplo(base.proyecto), periodo_id, tablas=tablas_de(base.proyecto)) -def test_de_staging_al_reporte_leido_por_repository(base, sin_supresion): - reportes = base.correr(*hasta_calcular(base.proyecto), parametros=sin_supresion, permitir_sin_definir=True)["calcular"] - - assert set(reportes) == set(measures_de(base.proyecto)) - for periodo, esperado in ESPERADO[base.proyecto].items(): - (reporte,) = reportes_del_ejemplo(base, periodo) - assert reporte.report_id in reportes[EJEMPLO[base.proyecto]] - assert conteos(base, reporte.report_id) == esperado def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base): @@ -99,7 +42,7 @@ def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base): base.correr("registro", anio_inicio=ANIO - 1) tablas = tablas_de(base.proyecto) - esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO - 1, ANIO, tablas=tablas) + esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas) assert base.dominio.dim_periodo_repository.count() == len(esperados) assert base.dominio.measure_report_repository.count() == 0 @@ -120,18 +63,6 @@ def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base): assert sorted(grupos) == sorted(esperados) # TEA no tiene cortes: vacía -def test_con_reportes_guardados_se_cambia_un_parametro_y_se_agrega_un_anio(base, sin_supresion): - """Antes (I-K54) esto fallaba: reemplazar dim_periodo violaba la llave de measure_report.""" - base.correr(*hasta_calcular(base.proyecto), permitir_sin_definir=True) - reportes = base.dominio.measure_report_repository.count() - - base.correr("registro", anio_fin=ANIO + 1, parametros=sin_supresion) - - assert base.dominio.def_parametro_repository.get("comun.umbral_supresion").valor == "1" - tablas = tablas_de(base.proyecto) - esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO, ANIO + 1, tablas=tablas) - assert base.dominio.dim_periodo_repository.count() == len(esperados) - assert base.dominio.measure_report_repository.count() == reportes def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): @@ -148,45 +79,19 @@ def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): assert base.dominio.dim_periodo_repository.count() == periodos -def test_las_definiciones_son_las_de_los_toml(base): +def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): + """Pins down: `definiciones` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a + measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.correr("definiciones")["definiciones"] - assert resumen["definiciones"] == len(measures_de(base.proyecto)) + # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata. + assert resumen["definiciones"] == {"cacu": 10, "cama": 7}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == len(measures_de(base.proyecto)) + assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain assert base.correr("definiciones")["definiciones"]["borradas"] == 0 -def test_recalcular_tras_una_carga_sin_cambios_no_agrega_reportes(base): - """T-2 de v0.4.0 (D-5): lo idéntico no se guarda otra vez.""" - base.correr(*hasta_calcular(base.proyecto), permitir_sin_definir=True) - antes = base.dominio.measure_report_repository.count() - - base.correr(*cargas(base.proyecto), "calcular", permitir_sin_definir=True) - - assert base.dominio.measure_report_repository.count() == antes - (reporte,) = reportes_del_ejemplo(base) - assert ultimo(base) == reporte.report_id and reporte.parametros_sha is not None -def test_con_un_dato_nuevo_recalcular_agrega_un_reporte_y_se_lee_el_ultimo(base, sin_supresion): - base.correr(*hasta_calcular(base.proyecto), parametros=sin_supresion, permitir_sin_definir=True) - (primero,) = reportes_del_ejemplo(base) - - cambiar_staging(base) - base.correr(*cargas(base.proyecto), "calcular", parametros=sin_supresion, permitir_sin_definir=True) - - reportes = sorted(reportes_del_ejemplo(base), key=lambda r: r.report_id) - assert [r.report_id for r in reportes][0] == primero.report_id and len(reportes) == 2 - assert ultimo(base) == reportes[1].report_id - assert conteos(base, reportes[0].report_id)[1] != conteos(base, reportes[1].report_id)[1] -def test_el_corte_no_distingue_los_reportes_de_un_indicador_que_no_lo_usa(base): - """MV-3: `measure_report.fecha_corte` existe tras migrar; un indicador que no la usa la deja nula.""" - base.correr(*hasta_calcular(base.proyecto), corte=date(2025, 3, 31), permitir_sin_definir=True) - base.correr("calcular", corte=date(2025, 12, 31), permitir_sin_definir=True) - - # El ejemplo de CaMa usa el corte (`:fecha_corte`); ahí se mira otro que no lo usa. - (reporte,) = reportes_del_ejemplo(base, nombre={"cama": "cama_biopsias"}.get(base.proyecto)) - assert reporte.fecha_corte is None diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index f6af8e8..b4bc39c 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -23,14 +23,14 @@ def antes(deps: dict[str, set[str]], paso: str) -> set[str]: return previos -@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) +@pytest.mark.parametrize("proyecto", ["cacu", "cama"]) def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto): deps = dependencias(proyecto) assert deps["migrar"] == set() assert {"migrar", "catalogos"} <= antes(deps, "cargar") # decisión 6 de §9 - assert {"cargar", "vistas", "registro", "definiciones"} <= antes(deps, "calcular") - assert {"registro", "calcular"} <= antes(deps, "observar") - assert {"cargar", "calcular"} <= antes(deps, "verificar_plata") + assert {"cargar"} <= antes(deps, "modelos") + assert {"registro"} <= antes(deps, "observar") + assert {"cargar", "catalogos"} <= antes(deps, "verificar_plata") def test_solo_cacu_arma_cohortes_y_estima_por_ahora(): diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 529edfa..9631914 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -19,7 +19,6 @@ from indicadores_kit.plata.periodo_observacion import ( from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo from indicadores_kit.registry.parametros import RUTA_PARAMETROS, ParametroSinDefinir from indicadores_kit.tablas import tablas_de -from indicadores_kit.tea import fixtures as fixtures_tea from sqlalchemy import inspect, text from sqlmodel import select @@ -27,7 +26,6 @@ from sqlmodel import select CAMBIO = { "cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"), "cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"), - "tea": ("evaluacion_psicologica", "psi_fecha_ados2", date(2024, 12, 1)), } CORTE = date(2025, 12, 31) @@ -107,13 +105,6 @@ def test_cargar_lleva_el_staging_a_persona_y_la_plata(base): assert contar(base, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'orden_estudio_servicio'") == 0 -@pytest.mark.parametrize("proyecto", ["tea"]) -def test_los_descartes_y_los_huerfanos_quedan_en_la_carga(base): - base.correr("catalogos", "cargar") - - descartes = json.loads(ultima_carga(base).descartes) - assert {m: n for m, n in descartes.items() if m.startswith("eeg")} == fixtures_tea.DESCARTES - assert descartes["huerfanos"] > 0 # los segmentos de los EEG que no entraron (I-MD17) def test_volver_a_cargar_sin_cambios_no_toca_nada(base): @@ -137,16 +128,6 @@ def test_un_cambio_en_staging_toca_un_procedimiento(base): assert plata_de(base) == antes -def test_cada_proyecto_carga_con_su_base_en_el_mismo_proceso(tmp_path): - fuentes = {} - for proyecto in ("cacu", "cama", "tea"): - base = base_de(proyecto, tmp_path) - base.correr("catalogos", "cargar") - fuentes[proyecto] = ultima_carga(base).fuente - base.motor.dispose() - - assert fuentes["cacu"].startswith("citologiacervical") and fuentes["cama"].startswith("mastografia") - assert "eeg_estudio" in fuentes["tea"] # --- vistas --- @@ -156,8 +137,8 @@ def test_las_vistas_se_construyen_y_se_pueden_repetir(base): primera = base.correr("vistas")["vistas"] assert base.correr("vistas")["vistas"] == primera - # Desde F6 (ADR-MD-009) no hay vistas por tipo: `v_persona` y, desde MD-19, las del número publicado. - assert sorted(inspect(base.motor).get_view_names()) == ["v_c1", "v_c2", "v_c3r", "v_measure_report_vigente", "v_persona"] + # Only `v_persona`: the published numbers are answered on request, so the publication views aren't built. + assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"] # --- observar --- diff --git a/tests/test_orquestacion_regla_repositorios.py b/tests/test_orquestacion_regla_repositorios.py index cc601b7..f13c068 100644 --- a/tests/test_orquestacion_regla_repositorios.py +++ b/tests/test_orquestacion_regla_repositorios.py @@ -23,7 +23,7 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo): assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos" -@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)]) +@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)]) def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes): repos = repositorios_de(proyecto) assert (repos.oro.cohorte is not None) == con_cohortes diff --git a/tests/test_orquestacion_riesgos.py b/tests/test_orquestacion_riesgos.py index 55dac31..5cb1a4c 100644 --- a/tests/test_orquestacion_riesgos.py +++ b/tests/test_orquestacion_riesgos.py @@ -43,7 +43,7 @@ class EstimadorFijo: @pytest.fixture def cacu(base): - base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True) + base.correr("catalogos", "cargar", "modelos", "cohortes", permitir_sin_definir=True) return base @@ -95,21 +95,3 @@ DE_PUNTA_A_PUNTA = { } -@pytest.mark.parametrize("proyecto", sorted(DE_PUNTA_A_PUNTA)) -def test_el_lote_confirmado_sale_en_el_resumen_por_banda(base, proyecto, sin_supresion): - """De punta a punta: la cohorte, estimar a su horizonte, confirmar y el resumen por banda.""" - url, horizonte, measure = DE_PUNTA_A_PUNTA[proyecto] - base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True) - estimador = EstimadorFijo(url, horizonte=horizonte, probabilidad=0.3) # 0.3 >= corte_alto: ALTO - (lote_id, _) = base.correr("estimar", estimadores={url: estimador})["estimar"][url] - confirmar_riesgos(proyecto, lote_id, "revisado") - # Sin supresión: los fixtures tienen menos miembros por semestre que el umbral (CaMa la tiene activa). - base.correr("vistas", "registro", "definiciones", "calcular", parametros=sin_supresion, permitir_sin_definir=True) - - en_el_anio = cuenta(base, f"""SELECT COUNT(*) FROM cohorte_miembro - WHERE strftime('%Y', fecha_indice) = '{base.ctx.anio_inicio}'""") - altos = cuenta(base, f"""SELECT COALESCE(SUM(v.n), 0) FROM v_c2 v - JOIN v_measure_report_vigente r ON r.report_id = v.report_id - WHERE r.measure_url = '{measure}' AND r.periodo_id LIKE '%-S_' - AND v.categoria = 'ALTO' AND v.estrato_id = 'total'""") - assert en_el_anio > 0 and altos == en_el_anio diff --git a/tests/test_orquestacion_timeline.py b/tests/test_orquestacion_timeline.py index 0d6e638..8d07c93 100644 --- a/tests/test_orquestacion_timeline.py +++ b/tests/test_orquestacion_timeline.py @@ -1,64 +1,72 @@ -"""What this module covers: the timeline repository that `repositorios_de` wires into `ctx.repos.plata` -reads the same rows as the kit's own query, in each project. +"""What this module covers: the timeline `repositorios_de` wires into `ctx.repos.plata` is dbt's view +`cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's +facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them. -Fixtures: `base` (from `conftest.py`), a project database for each of CaCu, CaMa and TEA; each test loads -its catalogs and data with `base.correr("catalogos", "cargar")`. `kit_rows` reads the same timeline -straight through the kit (`filas_de_linea`) to compare against. +Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created +(`catalogos`, `cargar`, `modelos`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on +that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time). """ +import json +import os from datetime import date, datetime, timedelta, timezone -from importlib import import_module +from pathlib import Path -from indicadores_kit.oro.cohortes.armado import filas_de_linea -from indicadores_kit.tablas import tablas_de -from sqlmodel import Session +import pytest CORTE = date(2025, 12, 31) +INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"} +KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json" -def kit_rows(base, **filters): - """The project's timeline read through the kit with `filters` (the kit's Spanish keywords).""" - fuentes = import_module(f"indicadores_kit.{base.proyecto}.linea_de_tiempo").FUENTES_PLATA - with Session(base.motor) as session: - return filas_de_linea(session, tablas_de(base.proyecto), fuentes, **filters) +@pytest.fixture +def proyecto(): + return "cacu" -def test_the_whole_timeline_matches_the_kit(base): - """Pins down: with only a clinical cut-off, the wired repository returns exactly the kit's rows, and - there are some. - - Fails if the orchestration binds another query, another project's tables or sources, or `until` - stops reaching the kit as `hasta`. - """ - base.correr("catalogos", "cargar") - rows = base.ctx.repos.plata.timeline.read(until=CORTE) - assert rows - assert rows == kit_rows(base, hasta=CORTE) +@pytest.fixture +def loaded(base): + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + base.correr("catalogos", "cargar", "modelos") + return base -def test_the_patient_filter_matches_the_kit(base): - """Pins down: `patients` reaches the kit as `pacientes`: only those patients come back, with the - kit's rows. +@pytest.fixture +def kit_rows(): + return json.loads(KIT_ROWS.read_text(encoding="utf-8")) - Fails if the patient filter is dropped or renamed on the way to the kit's query. - """ - base.correr("catalogos", "cargar") - patients = sorted({row["pac_id"] for row in kit_rows(base)})[:2] - rows = base.ctx.repos.plata.timeline.read(patients=patients, until=CORTE) + +def as_kit(rows) -> list[dict]: + """Rows as the snapshot keeps them: text values, no load time, without the inferred procedures.""" + return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"} + for row in rows if row["tipo"] not in INFERRED] + + +def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows): + """Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its + order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or + the view stops giving one of the kit's rows.""" + rows = loaded.ctx.repos.plata.timeline.read(until=CORTE) + assert as_kit(rows) == kit_rows + assert {row["tipo"] for row in rows} & INFERRED + assert all(isinstance(row["fecha"], date) for row in rows) + + +def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows): + """Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied.""" + patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2] + rows = loaded.ctx.repos.plata.timeline.read(patients=patients, until=CORTE) assert {row["pac_id"] for row in rows} == set(patients) - assert rows == kit_rows(base, pacientes=patients, hasta=CORTE) + assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients] -def test_known_until_cuts_at_what_was_loaded(base): - """Pins down: `known_until` reaches the kit as `conocida_hasta`: before the load nothing is known, - after it everything is, the same as reading without the cut. - - Fails if the load cut-off is ignored, or applied to the clinical date instead of the load time. - """ - before = datetime.now(timezone.utc) - timedelta(days=1) - base.correr("catalogos", "cargar") - after = datetime.now(timezone.utc) + timedelta(days=1) - timeline = base.ctx.repos.plata.timeline - assert timeline.read(until=CORTE, known_until=before) == [] - assert timeline.read(until=CORTE, known_until=after) == kit_rows(base, hasta=CORTE, conocida_hasta=after) - assert timeline.read(until=CORTE, known_until=after) == timeline.read(until=CORTE) +def test_known_until_cuts_at_what_was_loaded(loaded): + """Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known, + after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text.""" + timeline = loaded.ctx.repos.plata.timeline + everything = timeline.read(until=CORTE) + known = {row["conocida_en"] for row in everything} + assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known) + assert timeline.read(until=CORTE, known_until=min(known) - timedelta(seconds=1)) == [] + assert timeline.read(until=CORTE, known_until=datetime.now(timezone.utc) + timedelta(days=1)) == everything diff --git a/tests/test_reportes.py b/tests/test_reportes.py index da18b06..93078f8 100644 --- a/tests/test_reportes.py +++ b/tests/test_reportes.py @@ -105,8 +105,10 @@ def test_indicators_recompute_from_imported_rows(client): estado = client.get("/reportes/indicadores").get_json()["cacu"] assert estado["estado"] == "ok", estado assert estado["pendiente"] is False - assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "calcular"} - assert client.get("/cacu/indicadores").get_json() + assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "modelos"} + assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == { + "IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE", + "CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"} assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202 assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404 diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 6c07d11..d02f5fb 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -142,6 +142,16 @@ def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns() catalog.coerce("X") + + +def test_postal_code_restores_leading_zero_from_numeric_sources(): + from webapi.imports.schemas.coercion import coerce_postal_code + + assert coerce_postal_code(1000) == "01000" + assert coerce_postal_code(64000.0) == "64000" + assert coerce_postal_code(" 01000 ") == "01000" + assert coerce_postal_code("") is None + def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog(): """`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C from narrative text (a standard ACR BI-RADS subcategory), but the schema @@ -154,16 +164,6 @@ def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog(): for value in ("4A", "BI-RADS 4B", "bi-rads 4c"): assert catalog.coerce(value) == "B4" - -def test_postal_code_restores_leading_zero_from_numeric_sources(): - from webapi.imports.schemas.coercion import coerce_postal_code - - assert coerce_postal_code(1000) == "01000" - assert coerce_postal_code(64000.0) == "64000" - assert coerce_postal_code(" 01000 ") == "01000" - assert coerce_postal_code("") is None - - def test_column_matcher_handles_accents_prefixes_and_global_one_to_one(): targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"] by_source = { diff --git a/tests/test_schemas_registry.py b/tests/test_schemas_registry.py index cf0208e..bdef2e5 100644 --- a/tests/test_schemas_registry.py +++ b/tests/test_schemas_registry.py @@ -34,6 +34,8 @@ def test_every_registered_schema_is_constructible(entity_key): # --- Spot checks ----------------------------------------------------------- # CaMa entity with a required, unique integer ord_numero_hospital and an # *_ALIAS-backed enum field. + + def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio(): with pytest.raises(ValidationError) as excinfo: CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1") diff --git a/webapi/__init__.py b/webapi/__init__.py index a722c27..4eca115 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -6,12 +6,10 @@ from flask import Flask, jsonify from flask.json.provider import DefaultJSONProvider from webapi.blueprints.cacu import cacu_bp -from webapi.blueprints.cama import cama_bp from webapi.blueprints.data import data_bp from webapi.blueprints.governance import governance_bp from webapi.blueprints.imports import imports_bp from webapi.blueprints.reportes import reportes_bp -from webapi.blueprints.tea import tea_bp from webapi.seguimiento import blueprint_de_seguimiento @@ -71,12 +69,20 @@ def create_app() -> Flask: return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413 app.register_blueprint(cacu_bp, url_prefix="/cacu") - app.register_blueprint(cama_bp, url_prefix="/cama") - app.register_blueprint(tea_bp, url_prefix="/tea") app.register_blueprint(imports_bp, url_prefix="/imports") app.register_blueprint(data_bp, url_prefix="/data") app.register_blueprint(governance_bp, url_prefix="/governance") app.register_blueprint(reportes_bp, url_prefix="/reportes") + # The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest. + if os.environ.get("DBT_MANIFEST"): + from importlib import import_module + from pathlib import Path + + from webapi.kpis import kpis_blueprint + + for domain in ("cacu", "cama"): + app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"), + Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}") # 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. from persistance import cacu as cacu_repositories diff --git a/webapi/blueprints/cacu.py b/webapi/blueprints/cacu.py index ba72d75..38d532a 100644 --- a/webapi/blueprints/cacu.py +++ b/webapi/blueprints/cacu.py @@ -1,7 +1,3 @@ from flask import Blueprint -from persistance.db import get_cacu_session -from webapi.indicadores import registrar_indicadores - cacu_bp = Blueprint("cacu", __name__) -registrar_indicadores(cacu_bp, "cacu", get_cacu_session) diff --git a/webapi/blueprints/cama.py b/webapi/blueprints/cama.py deleted file mode 100644 index f8a39c4..0000000 --- a/webapi/blueprints/cama.py +++ /dev/null @@ -1,7 +0,0 @@ -from flask import Blueprint - -from persistance.db import get_cama_session -from webapi.indicadores import registrar_indicadores - -cama_bp = Blueprint("cama", __name__) -registrar_indicadores(cama_bp, "cama", get_cama_session) diff --git a/webapi/blueprints/imports.py b/webapi/blueprints/imports.py index 6976e27..29f6098 100644 --- a/webapi/blueprints/imports.py +++ b/webapi/blueprints/imports.py @@ -28,7 +28,7 @@ from webapi.imports.services.import_service import ( serialize_errors, validate_source, ) -from webapi.indicadores_vivos import ColaDeRecalculo +from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo from webapi.imports.services.introspection_service import ( detect_pdf, document_report, @@ -403,7 +403,7 @@ def commit(): finally: import_audit.record(audit) recalculating = False - if audit.domain and any(r.created or r.updated for r in results): + if audit.domain in DOMINIOS and any(r.created or r.updated for r in results): try: ColaDeRecalculo().solicitar(audit.domain) recalculating = True diff --git a/webapi/blueprints/tea.py b/webapi/blueprints/tea.py deleted file mode 100644 index bc0c8cc..0000000 --- a/webapi/blueprints/tea.py +++ /dev/null @@ -1,7 +0,0 @@ -from flask import Blueprint -from persistance.db import get_tea_session - -from webapi.indicadores import registrar_indicadores - -tea_bp = Blueprint("tea", __name__) -registrar_indicadores(tea_bp, "tea", get_tea_session) diff --git a/webapi/compositions.py b/webapi/compositions.py new file mode 100644 index 0000000..91322b8 --- /dev/null +++ b/webapi/compositions.py @@ -0,0 +1,329 @@ +"""A composition answered on request: how a period's units split across the categories of their latest valid fact. + +The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring: +composition` and gives the category rule (`categoria`): which column is the category, what makes a fact valid +(a template like a metric's `filter`), the dates the event and knowledge cut-offs apply to, and the order that picks +each unit's latest fact. Which fact is a unit's latest depends on the question (its period and cut-offs), so it's +computed in the answer, with `ROW_NUMBER()`, not stored in the model. The rest (the question, the history, strata +by age at the period's start) is `webapi.metrics`'. +""" + +import dataclasses +import hashlib +import json +from collections.abc import Iterable +from datetime import datetime, timedelta, timezone +from importlib import import_module +from pathlib import Path + +from core.indicadores.tipos import FechaHoraUTC +from jinja2 import Environment +from sqlalchemy import Select, String, and_, bindparam, case, cast, column, desc, distinct, func, literal, select, table, text + +from webapi.metrics import ( + AGGREGATION_VERSION, + HISTORY_ENTRY, + EVENT_CUTOFF, + KNOWLEDGE_CUTOFF, + POPULATION_SYSTEM, + MeasureQueries, + Population, + Question, + Stratum, + _population, + _semantic_model_of, + key_of, + rule_values, +) + + +@dataclasses.dataclass(frozen=True) +class FollowUp: + """A fact that follows the chosen one (a biopsy of the chosen sample): the category comes from the first of + them by `order`, among those that exist and were dated and known by the cut-offs; `none` if there's none.""" + + exists: str + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + order: tuple[str, ...] + none: str + + +@dataclasses.dataclass(frozen=True) +class Category: + value: str + no_data: str + valid_sql: str + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + order: tuple[str, ...] + admits_sql: str | None = None # which units count, judged on their chosen fact + follow_up: FollowUp | None = None + # A number's band instead of the value itself: (band, rule of its upper bound), in order; the last has no bound. + bands: tuple[tuple[str, str | None], ...] = () + + +@dataclasses.dataclass(frozen=True) +class CompositionDefinition: + """A composition, shaped so `MeasureQueries` can build its period, cut-offs and strata.""" + + url: str + version: str + metric: str + relation: str + model_checksum: str + time_dimension: str + dimensions: dict[str, str] + units: Population + category: Category + group: str + basis: str + rules: dict[str, str] + strata: tuple[Stratum, ...] + + @property + def measure_id(self) -> str: + return self.url.rsplit("/", 1)[-1] + + @property + def numerator(self) -> Population: + return self.units + + @property + def denominator(self) -> Population: + return self.units + + improvement_notation = None + + +def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]: + """The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`.""" + m = json.loads(manifest.read_text(encoding="utf-8")) + semantic = {node["name"]: node for node in m["semantic_models"].values()} + models = {node["unique_id"]: node for node in m["nodes"].values()} + definitions = {} + for metric in m["metrics"].values(): + meta = metric["config"].get("meta", {}) + if metric["type"] != "simple" or meta.get("scoring") != "composition": + continue + model = _semantic_model_of(metric, semantic) + node = models[model["depends_on"]["nodes"][0]] + rule = meta["categoria"] + definitions[meta["measure_url"]] = CompositionDefinition( + url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"], + model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"], + dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]}, + **{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}}, + units=_population(metric, model), + category=Category(rule["valor"], rule["sin_dato"], rule["valido"], tuple(rule.get("fechada_en", ())), + tuple(rule.get("conocida_en", ())), tuple(rule["orden"]), rule.get("admite"), + _follow_up(rule.get("seguimiento")), + tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))), + group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), + strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), + ) + return definitions + + +def _follow_up(rule: dict | None) -> FollowUp | None: + if rule is None: + return None + return FollowUp(rule["existe"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())), + tuple(rule["orden"]), rule["sin_seguimiento"]) + + +class CompositionQueries(MeasureQueries): + """Each unit's category in the period, from the latest of its facts, valid ones first.""" + + def __init__(self, definition: CompositionDefinition, question: Question, rule_values: dict, period_table): + super().__init__(definition, question, rule_values, period_table) + c, f = definition.category, definition.category.follow_up + names = [c.value, *c.order, *c.dated_at, *c.known_at, + *((f.exists, *f.order, *f.dated_at, *f.known_at) if f else ()), + *(s.spec["valor"] for s in definition.strata if s.kind == "del_elegido")] + known = {definition.dimensions[n] for n in (*c.known_at, *(f.known_at if f else ()))} + for name in {definition.dimensions[n] for n in names} - set(self.events.c.keys()): + self.events.append_column(column(name, FechaHoraUTC) if name in known else column(name)) + + def _template(self, sql: str): + """A `meta` condition, rendered like a metric's `filter`, with the rules it names bound (a list as `in`).""" + rendered = Environment().from_string(sql).render( + Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}") + names = [n for n in self.values if f":{n}" in rendered] + return text(f"({rendered})").bindparams(*( + bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names)) + + def _value(self): + """The category's value: the column's, or the band its number falls in, by the question's rules.""" + c = self.d.category + if not c.bands: + return self._column(c.value) + number = self._column(c.value) + *bounded, (last, _) = c.bands + return case(*((number < self.values[rule], literal(band)) for band, rule in bounded), else_=literal(last)) + + def _counted(self): + """The follow-up fact of this row exists and was dated and known by the cut-offs.""" + f = self.d.category.follow_up + conditions = [self._column(f.exists).is_not(None)] + if self.q.event_cutoff is not None: + conditions += [self._column(n) <= self.q.event_cutoff.isoformat() for n in f.dated_at] + if self.q.knowledge_cutoff is not None: + conditions += [self._column(n) <= self.q.knowledge_cutoff for n in f.known_at] + return and_(*conditions) + + def _valid(self): + c = self.d.category + conditions = [self._template(c.valid_sql)] + for name in c.dated_at: + conditions.append(self._column(name).is_not(None)) + if self.q.event_cutoff is not None: + conditions.append(self._column(name) <= self.q.event_cutoff.isoformat()) + if self.q.knowledge_cutoff is not None: + conditions += [self._column(name) <= self.q.knowledge_cutoff for name in c.known_at] + return and_(*conditions) + + def latest(self, *, with_strata: bool = False): + """One row per unit: its category (`categoria`) and, with strata, its value of each (`estrato_`).""" + unit = self.events.c[self.d.units.measure_expr] + c, f = self.d.category, self.d.category.follow_up + valid = self._valid() + order = [desc(case((valid, 1), else_=0)), *(desc(self._column(n)) for n in c.order)] + value = self._value() + category = case((valid, value)) + if f is not None: + counted = self._counted() + order += [desc(case((counted, 1), else_=0)), *(desc(self._column(n)) for n in f.order)] + category = case((valid & ~counted, literal(f.none)), (valid, value)) + admitted = valid if c.admits_sql is None else and_(valid, self._template(c.admits_sql)) + where = self._in_question() + units = self._filter(self.d.units) + if units is not None: + where = and_(where, units) + strata = [self.stratum_value(s).label(f"estrato_{s.name}") for s in self.d.strata] if with_strata else [] + ranked = (select(unit.label("unidad"), category.label("categoria"), case((admitted, 1), else_=0).label("admitida"), + *strata, func.row_number().over(partition_by=unit, order_by=order).label("lugar")) + .select_from(self._from(with_strata=with_strata)).where(where).subquery("por_unidad")) + chosen = [ranked.c.lugar == 1] + ([ranked.c.admitida == 1] if c.admits_sql is not None else []) + return (select(ranked.c.unidad, func.coalesce(ranked.c.categoria, c.no_data).label("categoria"), + *(ranked.c[f"estrato_{s.name}"] for s in self.d.strata if with_strata)) + .where(*chosen).subquery("ultima")) + + def category_counts(self) -> Select: + latest = self.latest() + return (select(latest.c.categoria, func.count(distinct(latest.c.unidad))) + .group_by(latest.c.categoria).order_by(latest.c.categoria)) + + def counts_by_stratum(self, stratum: Stratum) -> Select: + latest = self.latest(with_strata=True) + value = latest.c[f"estrato_{stratum.name}"] + return (select(value, latest.c.categoria, func.count(distinct(latest.c.unidad))) + .group_by(value, latest.c.categoria)) + + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: + latest = self.latest(with_strata=True) + (code,) = self.d.units.codes + yield unit_model, select( + literal(report_id).label("report_id"), literal(self.d.group).label("grupo"), + cast(latest.c.unidad, String(64)).label("unidad_id"), + literal(f"{self.d.measure_id}.{code}").label("resultado_id"), + (latest.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"), + latest.c.categoria.label("valor_id"), + ) + for stratum in self.d.strata: + yield stratum_model, select( + literal(report_id).label("report_id"), cast(latest.c.unidad, String(64)).label("unidad_id"), + literal(stratum.name).label("estrato_id"), latest.c[f"estrato_{stratum.name}"].label("estrato_valor"), + ) + + +@dataclasses.dataclass(frozen=True) +class CompositionAnswer: + report_id: int + categories: dict[str, int] + strata: dict[str, dict[str, dict[str, int]]] + stored_before: bool + + @property + def total(self) -> int: + return sum(self.categories.values()) + + +def answer_composition(project: str, definition: CompositionDefinition, question: Question, *, parameters, periods, + history, queries, allow_undecided: bool = False, + now: datetime | None = None) -> CompositionAnswer: + """The stored answer, or a new one: the database ranks each unit's facts, counts and writes the units.""" + values = rule_values(parameters, definition, allow_undecided) + key, key_sha = key_of(definition, question, values) + stored = history.find(definition.url, key_sha) + if stored is not None: + return _from_counts(stored, history.counts(stored)) + + period = periods.get(question.period_id) + if period is None: + raise LookupError(f"dim_periodo has no period {question.period_id!r}") + sql = CompositionQueries(definition, question, values, periods.model.__table__) + _, rows = queries.rows(sql.category_counts()) + categories = {category: n for category, n in rows} + strata = {} + for stratum in definition.strata: + _, cells = queries.rows(sql.counts_by_stratum(stratum)) + for value, category, n in cells: + strata.setdefault(stratum.name, {}).setdefault(value, {})[category] = n + models = import_module(f"core.{project}.indicadores.models") + (any_rule,) = parameters.list(limit=1) + report = models.MeasureReport( + measure_url=definition.url, measure_version=definition.version, + kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha, + parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff, + periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin, + status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), + agregacion_version=AGGREGATION_VERSION, + huella=hashlib.sha256(json.dumps([key_sha, sorted(categories.items()), sorted( + (s, v, c, n) for s, by in strata.items() for v, cs in by.items() for c, n in cs.items())]).encode() + ).hexdigest(), + ) + report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, + models.MeasureReportUnidadEstrato)) + return CompositionAnswer(report_id, categories, strata, stored_before=False) + + +def _from_counts(report_id: int, counts: dict) -> CompositionAnswer: + categories, strata = {}, {} + for (stratum, value, _, category), n in counts.items(): + if stratum == "total": + categories[category] = n + else: + strata.setdefault(stratum, {}).setdefault(value, {})[category] = n + return CompositionAnswer(report_id, categories, strata, stored_before=True) + + +def composition_report(definition: CompositionDefinition, question: Question, result: CompositionAnswer, period, + generated_at: datetime) -> dict: + """The answer as a FHIR R4 `MeasureReport`: the units counted, and a stratifier by category (and by each stratum).""" + (code,) = definition.units.codes + + def stratum(value: str, n: int) -> dict: + return {"value": {"text": value}, "population": [ + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": n}]} + + stratifiers = [{"code": [{"text": definition.category.value}], + "stratum": [stratum(c, n) for c, n in sorted(result.categories.items())]}] + for name, by_value in result.strata.items(): + stratifiers.append({"code": [{"text": name}], + "stratum": [stratum(v, sum(cs.values())) for v, cs in sorted(by_value.items())]}) + group = {"id": definition.group, "population": [ + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.total}, + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": result.total}, + ], "stratifier": stratifiers} + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}] + if question.event_cutoff is not None: + extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()}) + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + return { + "resourceType": "MeasureReport", "status": "complete", "type": "summary", + "measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(), + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, "group": [group], + } diff --git a/webapi/durations.py b/webapi/durations.py new file mode 100644 index 0000000..8c8ff95 --- /dev/null +++ b/webapi/durations.py @@ -0,0 +1,291 @@ +"""A duration answered on request: the days each unit takes from one fact to the next, summarized by quartiles. + +The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring: +continuous-variable` and gives the observation rule (`observacion`): the column with each unit's days, the dates the +cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't passed by the event cut-off isn't +measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in +dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`). + +The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. +""" + +import dataclasses +import hashlib +import json +from collections.abc import Iterable +from datetime import date, datetime, timedelta, timezone +from importlib import import_module +from pathlib import Path + +from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true + +from webapi.metrics import ( + AGGREGATION_VERSION, + EVENT_CUTOFF, + HISTORY_ENTRY, + KNOWLEDGE_CUTOFF, + POPULATION_SYSTEM, + MeasureQueries, + Population, + Question, + _population, + _semantic_model_of, + key_of, + rule_values, +) + +OBSERVATION = "measure-observation" +LOADS = table("carga", column("inicio"), column("fin")) +DAYS = table("dim_fecha", column("fecha"), column("dia_num")) + + +def inclusive_quartiles(values) -> Select: + """(n, q1, median, q3) of a subquery's `numero`, by the inclusive method in ANSI SQL. + + The quartile `q` is at position `(n - 1) q` of the sorted values (from 0), interpolating between its two + neighbors, as `statistics.quantiles(method="inclusive")`; with one value, the three are it. Window functions, + `CAST` and `CASE` only: the same SQL on every engine. + """ + ranked = select(values.c.numero, + (func.row_number().over(order_by=values.c.numero) - 1).label("i"), + func.count().over().label("n")).subquery("ordenados") + cells = [] + for name, q in (("q1", 0.25), ("mediana", 0.5), ("q3", 0.75)): + position = (ranked.c.n - 1) * q + floor = cast(position, Integer) + fraction = position - floor + cells.append((func.sum(case((ranked.c.i == floor, ranked.c.numero * (1 - fraction)), else_=0.0)) + + func.sum(case((ranked.c.i == floor + 1, ranked.c.numero * fraction), else_=0.0))).label(name)) + return select(func.count(ranked.c.numero).label("n"), *cells) + + +@dataclasses.dataclass(frozen=True) +class Observation: + value: str + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + horizon_rule: str | None + start_day: str + horizon_days: int | None = None # a fixed horizon, when the model used the same one to find the next fact + + def horizon(self, values: dict) -> int: + return self.horizon_days if self.horizon_rule is None else values[self.horizon_rule] + + +@dataclasses.dataclass(frozen=True) +class DurationDefinition: + """A duration, shaped so `MeasureQueries` can build its period and cut-offs.""" + + url: str + version: str + metric: str + relation: str + model_checksum: str + time_dimension: str + dimensions: dict[str, str] + units: Population + observation: Observation + group: str + basis: str + rules: dict[str, str] + improvement_notation: str | None = None + strata: tuple = () + + @property + def measure_id(self) -> str: + return self.url.rsplit("/", 1)[-1] + + @property + def numerator(self) -> Population: + return self.units + + @property + def denominator(self) -> Population: + return self.units + + +def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]: + """The simple metrics of the manifest whose `meta` declares a duration, by `measure_url`.""" + m = json.loads(manifest.read_text(encoding="utf-8")) + semantic = {node["name"]: node for node in m["semantic_models"].values()} + models = {node["unique_id"]: node for node in m["nodes"].values()} + definitions = {} + for metric in m["metrics"].values(): + meta = metric["config"].get("meta", {}) + if metric["type"] != "simple" or meta.get("scoring") != "continuous-variable": + continue + model = _semantic_model_of(metric, semantic) + node = models[model["depends_on"]["nodes"][0]] + rule = meta["observacion"] + definitions[meta["measure_url"]] = DurationDefinition( + url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"], + model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"], + dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]}, + **{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}}, + units=_population(metric, model), + observation=Observation(rule["valor"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())), + rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"], + int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None), + group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), + improvement_notation=meta.get("improvement_notation"), + ) + return definitions + + +class DurationQueries(MeasureQueries): + """Each unit of the period: measured or not yet, and its days if it has them.""" + + def __init__(self, definition: DurationDefinition, question: Question, rule_values: dict, period_table): + super().__init__(definition, question, rule_values, period_table) + o = definition.observation + for name in {definition.dimensions[n] for n in (o.value, o.start_day, *o.dated_at)} - set(self.events.c.keys()): + self.events.append_column(column(name)) + + def _has_value(self): + o, q = self.d.observation, self.q + conditions = [self._column(o.value).is_not(None)] + conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at] + if q.knowledge_cutoff is not None: + conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at] + return and_(*conditions) + + def per_unit(self): + """One row per unit in the period: `unidad`, `numero` (its days, or null) and whether it's still `pendiente`.""" + o = self.d.observation + cutoff_day = select(DAYS.c.dia_num).where(DAYS.c.fecha == self.q.event_cutoff.isoformat()).scalar_subquery() + has_value = self._has_value() + pending = and_(not_(has_value), + cutoff_day - self._column(o.start_day) < o.horizon(self.values)) + where = self._in_question() + units = self._filter(self.d.units) + if units is not None: + where = and_(where, units) + unit = self.events.c[self.d.units.measure_expr] + return (select(unit.label("unidad"), case((has_value, self._column(o.value)), else_=null()).label("numero"), + case((pending, 1), else_=0).label("pendiente")) + .select_from(self._from(with_strata=False)).where(where).distinct().subquery("por_unidad")) + + def summary(self) -> Select: + units = self.per_unit() + measured = select(units.c.numero).where(units.c.numero.is_not(None)).subquery("medidos") + quartiles = inclusive_quartiles(measured).subquery("cuartiles") + initial = select(func.count(units.c.unidad).label("inicial")).where(units.c.pendiente == 0).subquery("inicial") + # Two one-row subqueries side by side. + return (select(initial.c.inicial, quartiles.c.n, quartiles.c.q1, quartiles.c.mediana, quartiles.c.q3) + .select_from(initial.join(quartiles, true()))) + + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: + units = self.per_unit() + (initial,) = self.d.units.codes + for code, where, number in ((initial, units.c.pendiente == 0, null()), + (OBSERVATION, units.c.numero.is_not(None), units.c.numero)): + yield unit_model, select( + literal(report_id).label("report_id"), literal(self.d.group).label("grupo"), + cast(units.c.unidad, String(64)).label("unidad_id"), + literal(f"{self.d.measure_id}.{code}").label("resultado_id"), + (units.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"), + cast(number, unit_model.__table__.c.numero.type).label("numero"), + ).where(where) + + +@dataclasses.dataclass(frozen=True) +class DurationAnswer: + report_id: int + initial: int + n: int + q1: float | None + median: float | None + q3: float | None + stored_before: bool + event_cutoff: date | None = None # the one it was computed at: the question's, or the last load's day + + @property + def excluded(self) -> int: + return self.initial - self.n + + +def last_load_day(queries) -> date | None: + """The day of the latest load: its `fin`, or its `inicio` if it didn't finish.""" + _, ((last,),) = queries.rows(select(func.max(func.coalesce(LOADS.c.fin, LOADS.c.inicio)))) + return None if last is None else date.fromisoformat(str(last)[:10]) + + +def answer_duration(project: str, definition: DurationDefinition, question: Question, *, parameters, periods, + history, queries, allow_undecided: bool = False, now: datetime | None = None) -> DurationAnswer: + """The stored answer, or a new one: the database decides each unit, counts, takes the quartiles and stores.""" + if question.event_cutoff is None: + question = dataclasses.replace(question, event_cutoff=last_load_day(queries)) + values = rule_values(parameters, definition, allow_undecided) + if definition.observation.horizon_rule is None: + values["horizonte_dias"] = definition.observation.horizon_days + key, key_sha = key_of(definition, question, values) + models = import_module(f"core.{project}.indicadores.models") + stored = history.find(definition.url, key_sha) + if stored is not None: + return dataclasses.replace(_from_stored(definition, stored, queries, models.MeasureReportUnidad), + event_cutoff=question.event_cutoff) + + period = periods.get(question.period_id) + if period is None: + raise LookupError(f"dim_periodo has no period {question.period_id!r}") + sql = DurationQueries(definition, question, values, periods.model.__table__) + _, ((initial, n, q1, median, q3),) = queries.rows(sql.summary()) + (any_rule,) = parameters.list(limit=1) + report = models.MeasureReport( + measure_url=definition.url, measure_version=definition.version, + kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha, + parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff, + periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin, + status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), + agregacion_version=AGGREGATION_VERSION, + huella=hashlib.sha256(json.dumps([key_sha, initial, n, q1, median, q3]).encode()).hexdigest(), + ) + report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, + models.MeasureReportUnidadEstrato)) + return DurationAnswer(report_id, initial, n, *_numbers(n, q1, median, q3), stored_before=False, + event_cutoff=question.event_cutoff) + + +def _numbers(n, q1, median, q3): + return (None, None, None) if not n else (float(q1), float(median), float(q3)) + + +def _from_stored(definition: DurationDefinition, report_id: int, queries, unit_model) -> DurationAnswer: + """A stored duration read back from its units: the initial ones counted, the quartiles of their days.""" + u = unit_model.__table__.c + initial = f"{definition.measure_id}.{definition.units.codes[0]}" + observed = select(u.numero).where(u.report_id == report_id, u.resultado_id == f"{definition.measure_id}.{OBSERVATION}") + _, ((n, q1, median, q3),) = queries.rows(inclusive_quartiles(observed.subquery("medidos"))) + _, ((count,),) = queries.rows(select(func.count()).where(u.report_id == report_id, u.resultado_id == initial)) + return DurationAnswer(report_id, count, n, *_numbers(n, q1, median, q3), stored_before=True) + + +def duration_report(definition: DurationDefinition, question: Question, result: DurationAnswer, period, + generated_at: datetime) -> dict: + """The answer as a FHIR R4 `MeasureReport`: the units measurable and measured, the median as the score, and the + quartiles as its components.""" + group = {"id": definition.group, "population": [ + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.initial}, + {"code": {"coding": [{"system": POPULATION_SYSTEM, "code": OBSERVATION}]}, "count": result.n}, + ]} + if result.median is not None: + group["measureScore"] = {"value": result.median, "unit": "d", + "extension": [{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", + "valueDecimal": result.q1}, + {"url": "https://isssteleon.org/fhir/StructureDefinition/q3", + "valueDecimal": result.q3}]} + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}, + {"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or question.event_cutoff).isoformat()}] + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + report = { + "resourceType": "MeasureReport", "status": "complete", "type": "summary", + "measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(), + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, "group": [group], + } + if definition.improvement_notation: + report["improvementNotation"] = {"coding": [{ + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": definition.improvement_notation}]} + return report diff --git a/webapi/indicadores.py b/webapi/indicadores.py deleted file mode 100644 index f1fe055..0000000 --- a/webapi/indicadores.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA). - -`registrar_indicadores` agrega a un blueprint: - - GET /indicadores catálogo de indicadores (con sus `filtros`) - GET /indicadores//periodos periodos con reporte - GET /indicadores//datos?periodos=&estrato=&filtro= los números, sin figura - GET /indicadores//metadatos ficha metodológica - GET /indicadores//figuras/?periodos=&tema=&filtro= - -Las definiciones salen del kit (`measures_de`), los datos de -`indicadores_kit.serving.datos` y las figuras de -`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y -se traducen los errores a códigos HTTP. La forma de cada respuesta es un -contrato con el frontend: no se quita ni se renombra un campo. - -`?filtro=estrato:valor[,estrato:valor]` (T-19f) cuenta lo mismo solo con las -unidades que tienen esos valores: el mismo contrato, y en `/datos` la llave -`filtros`. Solo se aceptan los filtros que el indicador declara -(`extension.filtros`) y los valores de su catálogo; si no, 400. -""" - -import json -import re -from collections.abc import Callable - -from flask import Blueprint, Response, jsonify, request -from indicadores_kit.registry.measures import Measure, measures_de -from indicadores_kit.serving.contratos import FiltroNoDeclarado -from indicadores_kit.serving.datos import datos_de, filtros_de, metadatos_de, periodos_de, resumen_de -from indicadores_kit.serving.figuras import ( - TEMAS, - figura_json, - figuras_de, - periodos_con_reporte, - periodos_por_defecto, -) -from indicadores_kit.tablas import tablas_de -from sqlmodel import Session - -# Cómo se escribe un periodo de cada tipo (`registry/periodos.py`) y un ejemplo para el mensaje. -FORMATOS = { - "dia": (re.compile(r"\d{4}-\d{2}-\d{2}"), "AAAA-MM-DD"), - "semana_epidemiologica": (re.compile(r"\d{4}-SE\d{2}"), "AAAA-SEnn"), - "semana_habil": (re.compile(r"\d{4}-SH\d{2}"), "AAAA-SHnn"), - "semana_iso": (re.compile(r"\d{4}-W\d{2}"), "AAAA-Wnn"), - "mes": (re.compile(r"\d{4}-\d{2}"), "AAAA-MM"), - "bimestre": (re.compile(r"\d{4}-B[1-6]"), "AAAA-B1 a AAAA-B6"), - "trimestre": (re.compile(r"\d{4}-T[1-4]"), "AAAA-T1 a AAAA-T4"), - "semestre": (re.compile(r"\d{4}-S[12]"), "AAAA-S1 o AAAA-S2"), -} - - -def _error(mensaje: str, codigo: int): - return jsonify({"error": mensaje}), codigo - - -def _json(contenido) -> Response: - """Sin `jsonify`, que ordena las llaves: grupos y categorías van en su orden de presentación.""" - return Response(json.dumps(contenido, ensure_ascii=False), mimetype="application/json") - - -def _tipo_de(periodo: str, tipos: list[str]) -> str | None: - """El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`).""" - return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None) - - -def filtros_pedidos(texto: str | None) -> dict[str, str]: - """`estrato:valor[,estrato:valor]` -> `{estrato: valor}`. Vacío si no se pidió; `ValueError` si viene mal escrito.""" - if not texto: - return {} - filtros = {} - for parte in texto.split(","): - estrato, separador, valor = parte.partition(":") - if not separador or not estrato or not valor: - raise ValueError(f"filtro mal escrito {parte!r}; use estrato:valor") - if estrato in filtros: - raise ValueError(f"el filtro {estrato!r} va dos veces") - filtros[estrato] = valor - return filtros - - -def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]: - """Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`. - - Raises: - ValueError: un periodo mal formado, de un tipo que el indicador no - publica (`extension.publicacion.tipos_periodo`), o de tipos mezclados. - """ - if not texto: - return [], None - tipos = medida.extension.publicacion.tipos_periodo - periodos = list(dict.fromkeys(texto.split(","))) - encontrados = {_tipo_de(periodo, tipos) for periodo in periodos} - if None in encontrados: - formatos = "; ".join(FORMATOS[tipo][1] for tipo in tipos) - raise ValueError(f"Periodos mal formados: {texto!r}; este indicador publica {formatos}.") - if len(encontrados) > 1: - raise ValueError(f"Periodos de tipos distintos: {texto!r}; pida un solo tipo a la vez.") - return periodos, encontrados.pop() - - -def registrar_indicadores( - blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session] -) -> None: - """Agrega las rutas de indicadores de `proyecto` al blueprint. - - `get_session` es la fábrica de `Persistance` (`get__session`): - se llama en cada petición, no al registrar. - """ - definiciones = measures_de(proyecto) # fijas: se leen una vez - tablas = tablas_de(proyecto) - - def listar_indicadores(): - # Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo. - # `filtros` (T-24f): los que admite cada uno, con sus valores del catálogo, para armar `?filtro=`. - sesion = get_session() - try: - return _json([ - {**resumen_de(id_, medida), "filtros": filtros_de(sesion, medida)} - for id_, medida in definiciones.items() - if not medida.extension.publicacion.oculto - ]) - finally: - sesion.close() - - def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]: - """Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica.""" - if periodos: - return periodos - tipo = medida.extension.publicacion.tipos_periodo[0] - return periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo) - - def get_periodos(indicador: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - sesion = get_session() - try: - periodos = periodos_de(sesion, medida, tablas=tablas) - finally: - sesion.close() - return _json({"id": indicador, "version": medida.version, "periodos": periodos}) - - def get_metadatos(indicador: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - sesion = get_session() - try: - metadatos = metadatos_de(sesion, medida, tablas=tablas) - finally: - sesion.close() - return _json({"id": indicador, **metadatos}) - - def get_datos(indicador: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - estrato = request.args.get("estrato") or None - if estrato is not None and estrato not in medida.extension.estratos: - return _error( - f"estrato desconocido {estrato!r}; este indicador tiene {medida.extension.estratos}", - 400, - ) - try: - periodos, _ = periodos_pedidos(request.args.get("periodos"), medida) - filtros = filtros_pedidos(request.args.get("filtro")) - except ValueError as error: - return _error(str(error), 400) - - sesion = get_session() - try: - periodos = _periodos_o_los_que_haya(sesion, medida, periodos) - if not periodos: - return _error("el indicador no tiene reportes calculados", 404) - datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato, filtros=filtros or None) - except FiltroNoDeclarado as error: - return _error(str(error), 400) - except KeyError: - # KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte. - raise - except LookupError as error: - return _error(str(error), 404) - finally: - sesion.close() - return _json({"id": indicador, **datos}) - - def get_figura(indicador: str, figura: str): - medida = definiciones.get(indicador) - if medida is None: - return _error("indicador desconocido", 404) - if figura not in figuras_de(medida): - return _error( - f"figura {figura!r} no es del contrato {medida.extension.contrato}", 404 - ) - - tema = request.args.get("tema", "claro") - if tema not in TEMAS: - return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400) - try: - periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida) - filtros = filtros_pedidos(request.args.get("filtro")) - except ValueError as error: - return _error(str(error), 400) - - sesion = get_session() - try: - # Sin pedir ninguno: todos, o solo el más reciente si la figura se lee en un periodo. - periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas) - if not periodos: - return _error("el indicador no tiene reportes calculados", 404) - texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros or None) - except FiltroNoDeclarado as error: - return _error(str(error), 400) - except KeyError: - # KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte. - raise - except LookupError as error: - return _error(str(error), 404) - finally: - sesion.close() - return Response(texto, mimetype="application/json") - - blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores) - blueprint.add_url_rule("/indicadores//periodos", "get_periodos", get_periodos) - blueprint.add_url_rule("/indicadores//datos", "get_datos", get_datos) - blueprint.add_url_rule("/indicadores//metadatos", "get_metadatos", get_metadatos) - blueprint.add_url_rule( - "/indicadores//figuras/", "get_figura", get_figura - ) diff --git a/webapi/indicadores_vivos.py b/webapi/indicadores_vivos.py index ee6b0e8..0b38ccc 100644 --- a/webapi/indicadores_vivos.py +++ b/webapi/indicadores_vivos.py @@ -26,7 +26,7 @@ from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message -DOMINIOS = ("cacu", "cama", "tea") +DOMINIOS = ("cacu", "cama") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) diff --git a/webapi/kpis.py b/webapi/kpis.py new file mode 100644 index 0000000..abf497e --- /dev/null +++ b/webapi/kpis.py @@ -0,0 +1,111 @@ +"""`GET //indicadores/`: a measure's periods answered on request, as a FHIR `Bundle` of `MeasureReport`s. + +Query: `periodos` (comma-separated `dim_periodo` ids, required), `corte_evento` (`YYYY-MM-DD`, optional: facts dated +after it don't count) and `corte_conocimiento` (ISO date-time, optional: facts known after it don't count; by default +the start of the last load, so the same question asked before the next load reads the stored answer). The definitions +come from dbt's manifest (`DBT_MANIFEST`): proportions (`webapi.metrics`), compositions (`webapi.compositions`) and +durations (`webapi.durations`; without `corte_evento`, the day of the last load). +""" + +import json +from collections.abc import Callable +from datetime import date, datetime, timezone +from pathlib import Path + +from core.indicadores.tipos import FechaHoraUTC +from flask import Blueprint, Response, jsonify, request +from sqlalchemy import column, func, select, table + +from webapi.compositions import CompositionDefinition, answer_composition, composition_definitions, composition_report +from webapi.durations import DurationDefinition, answer_duration, duration_definitions, duration_report +from webapi.metrics import Question, UndecidedRule, answer, measure_definitions, measure_report + +LOADS = table("carga", column("inicio", FechaHoraUTC)) + + +def definitions_of(project: str, manifest: Path) -> dict: + """Every measure the manifest defines for the domain, by its id (the end of its url).""" + every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)} + return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")} + + +def kpis_blueprint(project: str, repositories, manifest: Path, *, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: + """The blueprint of a domain, to register with `url_prefix="/"`. `repositories` is the domain's + `persistance.` module.""" + blueprint = Blueprint(f"{project}_kpis", __name__) + definitions = definitions_of(project, manifest) + + @blueprint.get("/indicadores") + def list_kpis(): + """The measures answered on request: id, url, version and scoring.""" + return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)} + for i, d in sorted(definitions.items())]) + + @blueprint.get("/indicadores/") + def get_kpi(measure_id: str): + """A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history.""" + definition = definitions.get(measure_id) + if definition is None: + return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404 + try: + periods = [p for p in request.args.get("periodos", "").split(",") if p] + if not periods: + raise ValueError("falta `periodos`") + event_cutoff = _date(request.args.get("corte_evento")) + knowledge_cutoff = _datetime(request.args.get("corte_conocimiento")) or _last_load(repositories) + except ValueError as error: + return jsonify({"error": str(error)}), 400 + ask, serialize = ANSWERS[scoring_of(definition)] + entries = [] + for period_id in periods: + period = repositories.dim_periodo_repository.get(period_id) + if period is None: + return jsonify({"error": f"no hay un periodo {period_id!r}"}), 404 + question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff) + try: + result = ask(project, definition, question, parameters=repositories.def_parametro_repository, + periods=repositories.dim_periodo_repository, history=repositories.history_repository, + queries=repositories.dbt_query_repository) + except UndecidedRule as error: + return jsonify({"error": str(error)}), 409 + entries.append({"resource": serialize(definition, question, result, period, now())}) + bundle = {"resourceType": "Bundle", "type": "searchset", "total": len(entries), "entry": entries} + return Response(json.dumps(bundle, ensure_ascii=False), mimetype="application/fhir+json") + + return blueprint + + +ANSWERS = {"proportion": (answer, measure_report), "composition": (answer_composition, composition_report), + "continuous-variable": (answer_duration, duration_report)} + + +def scoring_of(definition) -> str: + if isinstance(definition, CompositionDefinition): + return "composition" + return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion" + + +def _date(value: str | None) -> date | None: + if not value: + return None + try: + return date.fromisoformat(value) + except ValueError: + raise ValueError(f"`corte_evento` no es una fecha AAAA-MM-DD: {value!r}") from None + + +def _datetime(value: str | None) -> datetime | None: + if not value: + return None + try: + moment = datetime.fromisoformat(value) + except ValueError: + raise ValueError(f"`corte_conocimiento` no es una fecha y hora ISO: {value!r}") from None + return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc) + + +def _last_load(repositories) -> datetime | None: + """The start of the domain's last load: what's known now, and stable until the next load.""" + _, ((last,),) = repositories.dbt_query_repository.rows(select(func.max(LOADS.c.inicio))) + return last diff --git a/webapi/metrics.py b/webapi/metrics.py new file mode 100644 index 0000000..23b3574 --- /dev/null +++ b/webapi/metrics.py @@ -0,0 +1,502 @@ +"""A measure answered on request: the question carries the period and both cut-offs, the definition is dbt's. + +The definition lives in dbt's semantic layer (`manifest.json`): a semantic model over an event-grain model (one row +per fact, with its date and when it became known), simple metrics for each population and a `ratio` metric whose +`meta` holds the rest of the measure, its strata included. dbt validates it; nothing here runs MetricFlow, which +doesn't support the project's engines. What runs instead is the small part of it these measures use: +`count_distinct` measures with a categorical filter, over a period of `dim_periodo`, broken down by strata, as +SQLAlchemy Core so every engine gets its own SQL. + +A question is a measure, a period, an event cut-off (facts dated after it don't count) and a knowledge cut-off (facts +known after it don't count). Its answer is stored once (`MeasureHistoryRepository`); asking again reads it. The +database counts and writes the units and their strata; only the counts reach Python. +""" + +import dataclasses +import hashlib +import json +from collections.abc import Callable, Iterable +from datetime import date, datetime, timedelta, timezone +from importlib import import_module +from pathlib import Path + +from core.indicadores.tipos import FechaHoraUTC +from jinja2 import Environment +from sqlalchemy import ( + Select, + String, + and_, + bindparam, + case, + cast, + column, + distinct, + func, + literal, + or_, + select, + table, + text, +) + +AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read +TOTAL = "total" +NO_DATA = "sin_dato" +AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo" +TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" +OF_THE_CHOSEN = "del_elegido" + + +class UndecidedRule(ValueError): + """A rule a measure needs is still `sin_definir`.""" + + +@dataclasses.dataclass(frozen=True) +class Population: + """A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates. + + `dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the + dates the knowledge cut-off applies to. + """ + + metric: str + measure_expr: str + filter_sql: str | None + codes: tuple[str, ...] + dated_at: tuple[str, ...] + known_at: tuple[str, ...] + + +@dataclasses.dataclass(frozen=True) +class Stratum: + """A breakdown of the measure, as its `meta.estratos` entry declares it. `kind` says how its value is computed: + + - `edad_al_inicio_del_periodo`: the age group at the period's start, from the model's `nacimiento` column; + - `linea_de_tiempo_al_inicio_del_periodo`: what the patient's timeline (`linea`, a model with `pac_id`, `tipo`, + `fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose + condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a + timeline `tipo` to whether there was one; + - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category. + """ + + name: str + kind: str + spec: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) + + @property + def birth(self) -> str: + return self.spec["nacimiento"] + + @classmethod + def of(cls, name: str, spec: dict) -> "Stratum": + if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN): + raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered") + return cls(name, spec["tipo"], spec) + + +@dataclasses.dataclass(frozen=True) +class MeasureDefinition: + """A `ratio` metric with its numerator and denominator, the event model they count over, and its `meta`.""" + + url: str + version: str + metric: str + relation: str + model_checksum: str + time_dimension: str + dimensions: dict[str, str] + numerator: Population + denominator: Population + group: str + basis: str + rules: dict[str, str] + strata: tuple[Stratum, ...] + improvement_notation: str | None = None + + @property + def measure_id(self) -> str: + return self.url.rsplit("/", 1)[-1] + + +def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]: + """The ratio metrics of the manifest that declare a `measure_url`, by that url.""" + m = json.loads(manifest.read_text(encoding="utf-8")) + metrics = {node["name"]: node for node in m["metrics"].values()} + semantic = {node["name"]: node for node in m["semantic_models"].values()} + models = {node["unique_id"]: node for node in m["nodes"].values()} + definitions = {} + for metric in metrics.values(): + meta = metric["config"].get("meta", {}) + if metric["type"] != "ratio" or "measure_url" not in meta: + continue + params = metric["type_params"] + numerator, denominator = metrics[params["numerator"]["name"]], metrics[params["denominator"]["name"]] + model = _semantic_model_of(numerator, semantic) + node = models[model["depends_on"]["nodes"][0]] + definitions[meta["measure_url"]] = MeasureDefinition( + url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], + relation=node["alias"], model_checksum=node["checksum"]["checksum"], + time_dimension=model["defaults"]["agg_time_dimension"], + dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]}, + **{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}}, + numerator=_population(numerator, model), denominator=_population(denominator, model), + group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), + strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), + improvement_notation=meta.get("improvement_notation"), + ) + return definitions + + +def _semantic_model_of(metric: dict, semantic: dict) -> dict: + measure = metric["type_params"]["measure"]["name"] + for model in semantic.values(): + if any(m["name"] == measure for m in model["measures"]): + return model + raise LookupError(f"no semantic model has the measure {measure!r} of {metric['name']}") + + +def _population(metric: dict, model: dict) -> Population: + measure_name = metric["type_params"]["measure"]["name"] + (measure,) = [m for m in model["measures"] if m["name"] == measure_name] + if measure["agg"] != "count_distinct": + raise NotImplementedError(f"{metric['name']}: only count_distinct measures are answered, not {measure['agg']}") + filters = (metric.get("filter") or {}).get("where_filters", []) + meta = metric["config"].get("meta", {}) + return Population( + metric=metric["name"], measure_expr=measure["expr"] or measure["name"], + filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None, + codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())), + known_at=tuple(meta.get("conocida_en", ())), + ) + + +# --- the question and its SQL ---------------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class Question: + """What is asked: a measure in a period, with what was dated and known up to the cut-offs.""" + + measure_url: str + period_id: str + event_cutoff: date | None = None + knowledge_cutoff: datetime | None = None + + +DIM_FECHA = ("fecha", "anio", "mes", "dia") +DIM_GRUPO_EDAD = ("etiqueta", "edad_min", "edad_max") + + +class MeasureQueries: + """The SQL of one definition for one question: counts per population and stratum, and the rows to store.""" + + def __init__(self, definition: MeasureDefinition, question: Question, rule_values: dict, period_table): + self.d, self.q, self.values = definition, question, rule_values + names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr} + # When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in. + known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at} + for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)): + known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())} + self.events = table(definition.relation, *( + column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) + if name.isidentifier())) + self.periods = period_table + self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") + self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio") + self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD)) + self._timelines: dict[str, object] = {} + + def _column(self, dimension: str): + return self.events.c[self.d.dimensions[dimension]] + + def _filter(self, population: Population): + conditions = [] + if population.filter_sql: + rendered = Environment().from_string(population.filter_sql).render( + Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}") + names = [n for n in self.values if f":{n}" in rendered] + conditions.append(text(rendered).bindparams(*( + bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names))) + if self.q.event_cutoff is not None: + conditions += [self._column(name) <= self.q.event_cutoff.isoformat() for name in population.dated_at] + conditions += [self._column(name).is_not(None) for name in population.dated_at] + if self.q.knowledge_cutoff is not None: + conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at] + conditions += [self._column(name).is_not(None) for name in population.known_at] + return and_(*conditions) if conditions else None + + def _in_question(self): + when, p = self.events.c[self.d.time_dimension], self.periods.c + conditions = [p.periodo_id == self.q.period_id] + if self.q.event_cutoff is not None: + conditions.append(when <= self.q.event_cutoff.isoformat()) + return and_(*conditions) + + def _from(self, *, with_strata: bool): + when, p = self.events.c[self.d.time_dimension], self.periods.c + joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin)) + if not with_strata: + return joined + for stratum in self.d.strata: + if stratum.kind == OF_THE_CHOSEN: + continue + if stratum.kind == AGE_AT_PERIOD_START: + joined = (joined + .join(self.start_day, self.start_day.c.fecha == p.inicio) + .outerjoin(self.birth_day, self.birth_day.c.fecha == self._column(stratum.birth)) + .outerjoin(self.age_groups, and_(self._age() >= self.age_groups.c.edad_min, + self._age() <= self.age_groups.c.edad_max))) + else: + had = self._timeline(stratum) + joined = joined.outerjoin(had, had.c.pac_id == self._column("paciente")) + return joined + + def _timeline(self, stratum: Stratum): + """Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start. + + Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped + by on every engine. + """ + if stratum.name in self._timelines: + return self._timelines[stratum.name] + kinds = sorted({k for v in stratum.spec["valores"] for alternative in v["si"] for k in alternative}) + line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"), + column("conocida_en", FechaHoraUTC)) + period = self.periods.alias(f"periodo_{stratum.name}") + conditions = [line.c.tipo.in_(kinds), line.c.fecha < period.c.inicio] + if self.q.knowledge_cutoff is not None: + conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff) + had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds)) + .select_from(line.join(period, period.c.periodo_id == self.q.period_id)) + .where(*conditions).group_by(line.c.pac_id).subquery(f"linea_{stratum.name}")) + self._timelines[stratum.name] = had + return had + + def _age(self): + """Completed years at the period's start, from the parts of `dim_fecha`: no engine date functions.""" + start, birth = self.start_day.c, self.birth_day.c + not_yet = or_(start.mes < birth.mes, and_(start.mes == birth.mes, start.dia < birth.dia)) + return start.anio - birth.anio - case((not_yet, 1), else_=0) + + def stratum_value(self, stratum: Stratum): + if stratum.kind == AGE_AT_PERIOD_START: + return func.coalesce(self.age_groups.c.etiqueta, NO_DATA) + if stratum.kind == OF_THE_CHOSEN: + return self._column(stratum.spec["valor"]) + had = self._timeline(stratum).c + + def holds(alternative: dict): + return and_(*(func.coalesce(had[k], 0) == (1 if wanted else 0) for k, wanted in alternative.items())) + + return case(*((or_(*map(holds, v["si"])), literal(v["valor"])) for v in stratum.spec["valores"]), + else_=literal(stratum.spec["resto"])) + + def _cells(self): + unit = self.events.c[self.d.numerator.measure_expr] + for name, population in (("numerator", self.d.numerator), ("denominator", self.d.denominator)): + condition = self._filter(population) + counted = unit if condition is None else case((condition, unit)) + yield func.count(distinct(counted)).label(name) + + def counts(self) -> Select: + return select(*self._cells()).select_from(self._from(with_strata=False)).where(self._in_question()) + + def counts_by_stratum(self, stratum: Stratum) -> Select: + value = self.stratum_value(stratum).label("valor") + return (select(value, *self._cells()).select_from(self._from(with_strata=True)) + .where(self._in_question()).group_by(value)) + + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: + """What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum.""" + for population in (self.d.denominator, self.d.numerator): + unit = self.events.c[population.measure_expr] + condition = self._filter(population) + where = self._in_question() if condition is None else and_(self._in_question(), condition) + for code in population.codes: + yield unit_model, (select( + literal(report_id).label("report_id"), literal(self.d.group).label("grupo"), + cast(unit, String(64)).label("unidad_id"), + literal(f"{self.d.measure_id}.{code}").label("resultado_id"), + (unit if self.d.basis == "paciente" else literal(None)).label("pac_id"), + ).select_from(self._from(with_strata=False)).where(where).distinct()) + unit = self.events.c[self.d.denominator.measure_expr] + condition = self._filter(self.d.denominator) + where = self._in_question() if condition is None else and_(self._in_question(), condition) + for stratum in self.d.strata: + yield stratum_model, (select( + literal(report_id).label("report_id"), cast(unit, String(64)).label("unidad_id"), + literal(stratum.name).label("estrato_id"), self.stratum_value(stratum).label("estrato_valor"), + ).select_from(self._from(with_strata=True)).where(where).distinct()) + + +# --- answering --------------------------------------------------------------------------------------------------------- + + +def rule_values(parameters, definition: MeasureDefinition, allow_undecided: bool = False) -> dict: + values = {} + for name, rule in definition.rules.items(): + row = parameters.get(rule) + if row is None: + raise KeyError(f"{definition.url}: there's no rule {rule!r} in def_parametro") + if row.estado == "sin_definir" and not allow_undecided: + raise UndecidedRule(f"{definition.url}: the rule {rule!r} is undecided ({row.fuente})") + values[name] = json.loads(row.valor) + return values + + +def key_of(definition: MeasureDefinition, question: Question, values: dict) -> tuple[str, str]: + """The full key of a question, as JSON, and its hash.""" + key = json.dumps({ + "measure": definition.url, "version": definition.version, "metric": definition.metric, + "periodo": question.period_id, + "corte_evento": question.event_cutoff.isoformat() if question.event_cutoff else None, + "corte_conocimiento": question.knowledge_cutoff.isoformat() if question.knowledge_cutoff else None, + "sql": values, "estratos": {s.name: s.spec for s in definition.strata}, + }, sort_keys=True, ensure_ascii=False) + return key, hashlib.sha256(key.encode("utf-8")).hexdigest() + + +@dataclasses.dataclass(frozen=True) +class Counts: + numerator: int + denominator: int + + @property + def proportion(self) -> float | None: + return self.numerator / self.denominator if self.denominator else None + + +@dataclasses.dataclass(frozen=True) +class Answer: + report_id: int + total: Counts + strata: dict[str, dict[str, Counts]] + stored_before: bool + + @property + def numerator(self) -> int: + return self.total.numerator + + @property + def denominator(self) -> int: + return self.total.denominator + + @property + def proportion(self) -> float | None: + return self.total.proportion + + +def answer(project: str, definition: MeasureDefinition, question: Question, *, parameters, periods, history, + queries, allow_undecided: bool = False, now: datetime | None = None) -> Answer: + """The stored answer to the question, or a new one computed by the database and stored. + + `parameters`, `periods`, `history` and `queries` are the domain's repositories (`def_parametro`, `dim_periodo`, + `MeasureHistoryRepository`, `DbtQueryRepository`). A stored answer is read back from its units' counts. + """ + values = rule_values(parameters, definition, allow_undecided) + key, key_sha = key_of(definition, question, values) + stored = history.find(definition.url, key_sha) + if stored is not None: + return _from_counts(definition, stored, history.counts(stored)) + + period = periods.get(question.period_id) + if period is None: + raise LookupError(f"dim_periodo has no period {question.period_id!r}") + sql = MeasureQueries(definition, question, values, periods.model.__table__) + _, ((numerator, denominator),) = queries.rows(sql.counts()) + strata = {} + for stratum in definition.strata: + _, cells = queries.rows(sql.counts_by_stratum(stratum)) + strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells} + models = import_module(f"core.{project}.indicadores.models") + (any_rule,) = parameters.list(limit=1) + report = models.MeasureReport( + measure_url=definition.url, measure_version=definition.version, + kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha, + parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff, + periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin, + status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), + agregacion_version=AGGREGATION_VERSION, + huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted( + (s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode() + ).hexdigest(), + ) + report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, + models.MeasureReportUnidadEstrato)) + return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False) + + +def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer: + numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0], + definition.denominator.codes[0])) + cells: dict[tuple[str, str], list[int]] = {} + for (stratum, value, resultado, _), n in counts.items(): + cell = cells.setdefault((stratum, value), [0, 0]) + if resultado == numerator: + cell[0] = n + elif resultado == denominator: + cell[1] = n + strata: dict[str, dict[str, Counts]] = {} + for (stratum, value), (n, d) in cells.items(): + if stratum != TOTAL: + strata.setdefault(stratum, {})[value] = Counts(n, d) + return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True) + + +# --- the contract -------------------------------------------------------------------------------------------------- + +POPULATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-population" +EVENT_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-evento" +KNOWLEDGE_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento" +HISTORY_ENTRY = "https://isssteleon.org/fhir/StructureDefinition/reporte-id" + + +def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]: + by_code = {**{code: counts.denominator for code in definition.denominator.codes}, + **{code: counts.numerator for code in definition.numerator.codes}} + return [{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": count} + for code, count in by_code.items()] + + +def _scored(entry: dict, counts: Counts) -> dict: + if counts.proportion is not None: + entry["measureScore"] = {"value": counts.proportion} + return entry + + +def measure_report(definition: MeasureDefinition, question: Question, result: Answer, period, + generated_at: datetime) -> dict: + """The answer as a FHIR R4 `MeasureReport` (summary): one group, its populations, its score and its strata. + + The cut-offs aren't FHIR elements: they go as extensions of the report, with the history entry it was read from. + """ + group = _scored({"id": definition.group, "population": _populations(definition, result.total)}, result.total) + if result.strata: + group["stratifier"] = [ + {"code": [{"text": name}], "stratum": [ + _scored({"value": {"text": value}, "population": _populations(definition, counts)}, counts) + for value, counts in sorted(values.items())]} + for name, values in result.strata.items() + ] + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}] + if question.event_cutoff is not None: + extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()}) + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + report = { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": f"{definition.url}|{definition.version}", + "date": generated_at.isoformat(), + # FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`. + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, + "group": [group], + } + if definition.improvement_notation: + report["improvementNotation"] = {"coding": [{ + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": definition.improvement_notation}]} + return report + diff --git a/webapi/orquestacion/__main__.py b/webapi/orquestacion/__main__.py index e84aa1e..f970967 100644 --- a/webapi/orquestacion/__main__.py +++ b/webapi/orquestacion/__main__.py @@ -15,7 +15,7 @@ from pathlib import Path from webapi.orquestacion.contexto import Contexto from webapi.orquestacion.ejecutor import correr -PROYECTOS = ("cacu", "cama", "tea") +PROYECTOS = ("cacu", "cama") def main(argv: list[str] | None = None) -> None: diff --git a/webapi/orquestacion/ciclo.py b/webapi/orquestacion/ciclo.py index 3989b80..3ac515f 100644 --- a/webapi/orquestacion/ciclo.py +++ b/webapi/orquestacion/ciclo.py @@ -11,38 +11,36 @@ Bronce lo escribe la ingesta, fuera del ciclo. """ import logging -from datetime import date +from datetime import date, datetime from functools import partial from importlib import import_module from pathlib import Path from hamilton.function_modifiers import config from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata -from indicadores_kit.esquema import ddl_de_vistas -from indicadores_kit.oro.calculo import fecha_de_ultima_carga, medir_con_unidades from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado from indicadores_kit.oro.cohortes.definicion import leer_definicion from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging from indicadores_kit.plata.periodo_observacion import periodos_de_observacion +from indicadores_kit.plata.vistas import ddl_de_vistas as ddl_de_v_persona from indicadores_kit.registry.apoyo import ( CLAVE_DIM_FECHA_DESDE, filas_de_dim_fecha, grupos_de_edad_de, ) from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.registry.measures import measures_de, rutas_de_measures from indicadores_kit.registry.parametros import ( RUTA_PARAMETROS, leer_parametros, valores_del_archivo, ) from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.registry.publicacion import semillas_de from indicadores_kit.tablas import tablas_de from persistance.aristas.plata import guardar_carga_en -from sqlmodel import SQLModel, select +from sqlmodel import SQLModel, func, select from webapi.orquestacion.contexto import Contexto +from webapi.orquestacion.semantic_layer import catalog_layers, event_views from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo registro_de_eventos = logging.getLogger(__name__) @@ -93,8 +91,8 @@ def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel: def vistas(cargar: SQLModel, ctx: Contexto) -> int: - """Las vistas de versión vigente y las del proyecto: la DDL la arma el kit y la corre el repositorio.""" - return len(ctx.repos.plata.vistas.construir(ddl_de_vistas(ctx.proyecto))) + """`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base.""" + return len(ctx.repos.plata.vistas.construir(ddl_de_v_persona(tablas_de(ctx.proyecto).Persona))) def registro(migrar: str, ctx: Contexto) -> list[str]: @@ -106,7 +104,7 @@ def registro(migrar: str, ctx: Contexto) -> list[str]: de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `.grupos_edad`, si el proyecto los tiene (TEA no). """ - tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto) + tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto, _manifest(ctx)) ruta = ctx.parametros or RUTA_PARAMETROS parametros = leer_parametros(ruta, tablas=tablas) periodos = periodos_de_tipos(tipos, ctx.anio_inicio, ctx.anio_fin, tablas=tablas) @@ -132,35 +130,26 @@ def _cubre(fechas, desde: date, hasta: date) -> bool: def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]: - """Las definiciones del proyecto -> el catálogo de publicación de §6f (`cat_measure*`, `cat_estrato*`). + """The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest. - Se sincroniza: lo que una unidad de un reporte usa no se borra (T-19b). Se leen y validan todos los - archivos antes de escribir: uno inválido no toca las tablas. + It's synchronized: what a report's unit uses isn't deleted. """ - tablas, rutas = tablas_de(ctx.proyecto), rutas_de_measures(ctx.proyecto) - semillas = semillas_de(ctx.proyecto, rutas, valores_del_archivo(ctx.parametros or RUTA_PARAMETROS), tablas=tablas) - return {"definiciones": len(semillas.measures), **ctx.repos.oro.publicacion.sincronizar(semillas.por_capas())} + capas = catalog_layers(ctx.proyecto, _manifest(ctx)) + return {"definiciones": len(capas[0]), **ctx.repos.oro.publicacion.sincronizar(capas)} -def calcular(vistas: int, registro: list[str], definiciones: dict[str, int], ctx: Contexto) -> dict[str, list[int]]: - """Cada definición en cada periodo de cada tipo que publica, dentro de los años del contexto. - - Cada reporte se mide y se guarda en una sola sesión (`CalculoRepository.calcular`). - """ - desde, hasta = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1) - calculo, tablas = ctx.repos.oro.calculo, tablas_de(ctx.proyecto) - reportes = {} - for nombre, medida in measures_de(ctx.proyecto).items(): - for tipo in medida.extension.publicacion.tipos_periodo: - for periodo_id in calculo.periodos(tipo, desde, hasta): - medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas, - corte=ctx.corte, permitir_sin_definir=ctx.permitir_sin_definir) - reportes.setdefault(nombre, []).append(calculo.calcular(medir)) - return reportes +def modelos(cargar: SQLModel, ctx: Contexto) -> int: + """The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base.""" + return len(ctx.repos.plata.vistas.construir(event_views(_manifest(ctx), ctx.proyecto))) -# `observar` y `verificar_plata` van después de `calcular` para que una regla suya sin definir no lo detenga (I-MD1). -def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int]], ctx: Contexto) -> int: +def _manifest(ctx: Contexto) -> Path: + if ctx.dbt_manifest is None: + raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there") + return ctx.dbt_manifest + + +def observar(cargar: SQLModel, registro: list[str], ctx: Contexto) -> int: """`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente.""" return ctx.repos.plata.observacion.observar(partial( periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte, @@ -168,8 +157,7 @@ def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int )) -def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[str, list[int]], - ctx: Contexto) -> dict[str, int]: +def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], ctx: Contexto) -> dict[str, int]: """Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro.""" conteos = ctx.repos.plata.vinculos.verificar(partial(calidad_de_la_plata, tablas=tablas_de(ctx.proyecto))) for nombre, n in conteos.items(): @@ -179,17 +167,19 @@ def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[ @config.when(con_cohortes=True) -def cohortes(cargar: SQLModel, ctx: Contexto) -> 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).""" +def cohortes(modelos: int, ctx: Contexto) -> 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 (`modelos` creates it), the same the models and the measures' strata read. + """ tablas = tablas_de(ctx.proyecto) tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES - fuentes = import_module(f"indicadores_kit.{ctx.proyecto}.linea_de_tiempo").FUENTES_PLATA inicio, fin = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1) def armado(definicion, sesion): - corte = ctx.corte or fecha_de_ultima_carga(sesion, tablas) - return armado_de(sesion, definicion, inicio, fin, corte, tablas=tablas, cohortes=tablas_cohorte, - fuentes=fuentes) + corte = ctx.corte or _fecha_de_ultima_carga(sesion, tablas) + return armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, + linea=ctx.repos.plata.timeline.query) armados = {} for ruta in definiciones_de_cohorte(ctx.proyecto): @@ -229,3 +219,11 @@ def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, t armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos ) return lotes + + +def _fecha_de_ultima_carga(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]) diff --git a/webapi/orquestacion/contexto.py b/webapi/orquestacion/contexto.py index 50b3e26..37e2dac 100644 --- a/webapi/orquestacion/contexto.py +++ b/webapi/orquestacion/contexto.py @@ -1,5 +1,6 @@ """Lo que recibe cada paso del ciclo.""" +import os from collections.abc import Mapping from dataclasses import dataclass, field from datetime import date @@ -7,6 +8,12 @@ from pathlib import Path from typing import Any +def manifiesto_de_dbt() -> Path | None: + """The deployment's dbt manifest, from `DBT_MANIFEST`.""" + ruta = os.environ.get("DBT_MANIFEST") + return Path(ruta) if ruta else None + + @dataclass(frozen=True) class Contexto: """Lo que recibe un paso: el proyecto y las opciones del ciclo. @@ -26,6 +33,9 @@ class Contexto: corte: date | None = None permitir_sin_definir: bool = False parametros: Path | None = None + # The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle + # creates their event models (`modelos`) and seeds the publication catalog (`definiciones`). + dbt_manifest: Path | None = field(default_factory=manifiesto_de_dbt) # Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimar(columnas, filas)`, `procedencia()` # y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimar` no hace nada. estimadores: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False) diff --git a/webapi/orquestacion/proyecto.py b/webapi/orquestacion/proyecto.py index 78086d3..5cab24e 100644 --- a/webapi/orquestacion/proyecto.py +++ b/webapi/orquestacion/proyecto.py @@ -1,14 +1,16 @@ -"""Lo que el ciclo necesita saber de las definiciones del kit para un proyecto.""" +"""Lo que el ciclo necesita saber de las definiciones de un proyecto: sus periodos (dbt) y sus cohortes (el kit).""" +import json from pathlib import Path from indicadores_kit.oro.cohortes.definicion import RAIZ -from indicadores_kit.registry.measures import measures_de -def tipos_de_periodo(proyecto: str) -> list[str]: - """Los tipos de periodo que publican las definiciones del proyecto (semestre y, en CaCu y CaMa, mes).""" - return sorted({t for m in measures_de(proyecto).values() for t in m.extension.publicacion.tipos_periodo}) +def tipos_de_periodo(proyecto: str, manifest: Path) -> list[str]: + """The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest.""" + metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() + return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", []) + if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")}) def definiciones_de_cohorte(proyecto: str) -> list[Path]: diff --git a/webapi/orquestacion/repositorios.py b/webapi/orquestacion/repositorios.py index 12cab49..68f87e6 100644 --- a/webapi/orquestacion/repositorios.py +++ b/webapi/orquestacion/repositorios.py @@ -8,8 +8,6 @@ dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión. from dataclasses import dataclass from importlib import import_module -from indicadores_kit.plata.linea_de_tiempo import linea_de_tiempo_plata -from indicadores_kit.tablas import tablas_de from persistance.aristas.bronce import StagingRepository from persistance.aristas.oro import ( CalculoRepository, @@ -21,7 +19,6 @@ from persistance.aristas.plata import ( CargaRepository, CatalogoRepository, ObservacionRepository, - TimelineQuery, TimelineRepository, VinculosRepository, VistasRepository, @@ -45,7 +42,7 @@ class Plata: vistas: VistasRepository observacion: ObservacionRepository vinculos: VinculosRepository - timeline: TimelineRepository | None = None # the patients' timeline, through the kit's query + timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it @dataclass(frozen=True) @@ -82,7 +79,7 @@ def repositorios_de(proyecto: str) -> Repositorios: vistas=dominio.vistas_repository, observacion=dominio.observar_repository, vinculos=dominio.vinculos_repository, - timeline=dominio.timeline_repository.with_query(timeline_query(proyecto)), + timeline=dominio.timeline_repository, ), materializador=dominio.materializador, oro=Oro( @@ -96,13 +93,3 @@ def repositorios_de(proyecto: str) -> Repositorios: ), ) - -def timeline_query(proyecto: str) -> TimelineQuery: - """The project's timeline query: the kit's `linea_de_tiempo_plata` over its `FUENTES_PLATA`.""" - tablas = tablas_de(proyecto) - fuentes = import_module(f"indicadores_kit.{proyecto}.linea_de_tiempo").FUENTES_PLATA - - def query(*, patients, until, known_until): - return linea_de_tiempo_plata(tablas, fuentes, pacientes=patients, hasta=until, conocida_hasta=known_until) - - return query diff --git a/webapi/orquestacion/semantic_layer.py b/webapi/orquestacion/semantic_layer.py new file mode 100644 index 0000000..9642c57 --- /dev/null +++ b/webapi/orquestacion/semantic_layer.py @@ -0,0 +1,78 @@ +"""What the cycle takes from dbt's manifest: the event models to create and the catalog the reports point to. + +The measures are defined in dbt's semantic layer (`webapi.metrics`, `webapi.compositions`). Their event models have +to exist in the database for a measure to be asked; `event_views` gives the DDL that creates them from dbt's compiled +SQL, as `dbt run` would for a view. The publication catalog (`cat_measure*`, `cat_estrato`) is what the reports' +units point to; `catalog_layers` builds it from the same definitions, parents before children. +""" + +import json +from importlib import import_module +from pathlib import Path + +from sqlalchemy import text + +from webapi.compositions import composition_definitions +from webapi.durations import OBSERVATION, duration_definitions +from webapi.kpis import scoring_of +from webapi.metrics import measure_definitions + +CONTRACTS = {"proportion": "C1", "composition": "C2", "continuous-variable": "C3r"} # the publication views +STRATUM_LABELS = {"grupo_edad": "Grupo de edad"} # unless the stratum's `etiqueta` says otherwise + + +def event_views(manifest: Path, project: str) -> list: + """`drop view if exists` and `create view … as ` for every model the project's measures read, + parents first. + + Those are the project's models semantic models count over (`models//…`) and the timelines its strata + read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined + in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here. + """ + m = json.loads(manifest.read_text(encoding="utf-8")) + nodes = {n["unique_id"]: n for n in m["nodes"].values()} + by_name = {n["name"]: uid for uid, n in nodes.items() if n["resource_type"] == "model"} + roots = {uid for uid in (s["depends_on"]["nodes"][0] for s in m["semantic_models"].values()) + if nodes[uid]["fqn"][1] == project} + roots |= {by_name[spec["linea"]] for metric in m["metrics"].values() + if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/") + for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec} + ordered: list[str] = [] + + def visit(uid: str) -> None: + if uid in ordered or uid not in nodes: + return + for parent in nodes[uid]["depends_on"]["nodes"]: + visit(parent) + if nodes[uid]["config"]["materialized"] != "ephemeral": + ordered.append(uid) + + for uid in sorted(roots): + visit(uid) + ddl = [text(f"drop view if exists {nodes[uid]['alias']}") for uid in reversed(ordered)] + return ddl + [text(f"create view {nodes[uid]['alias']} as {nodes[uid]['compiled_code']}") for uid in ordered] + + +def catalog_layers(project: str, manifest: Path) -> list[list]: + """The catalog rows of every measure the manifest defines for the project, in layers: parents first.""" + t = import_module(f"core.{project}.indicadores.models") + # The title on screen: `meta.titulo` when the label had to differ (dbt wants labels unique in the project). + labels = {n["name"]: n["config"].get("meta", {}).get("titulo") or n["label"] + for n in json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()} + definitions = [d for d in (*measure_definitions(manifest).values(), *composition_definitions(manifest).values(), + *duration_definitions(manifest).values()) if d.url.startswith(f"{project}/")] + labels_of = {s.name: s.spec.get("etiqueta") or STRATUM_LABELS.get(s.name, s.name) + for d in definitions for s in d.strata} + strata = sorted(labels_of) + measures, children = [], [] + for d in definitions: + contract = CONTRACTS[scoring_of(d)] + measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric], + contrato=contract, unidad=d.basis)) + codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()))) + children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c, + etiqueta=c) for c in codes] + children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0)) + children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata] + stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata] + return [stratum_rows + measures, children] -- 2.53.0 From 73b1db11214d5ecbd51b2fe8c03615cbc7e5a6c3 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 09/24] English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports --- Dockerfile | 2 +- README.md | 4 +- docker-entrypoint.sh | 4 +- tests/conftest.py | 24 +-- tests/test_cama_measures.py | 8 +- tests/test_measure_cases.py | 6 +- tests/test_metrics_on_request.py | 14 +- tests/test_orquestacion_ciclo.py | 28 ++-- tests/test_orquestacion_oro.py | 26 ++-- tests/test_orquestacion_pasos.py | 26 ++-- tests/test_orquestacion_plata.py | 62 ++++---- tests/test_orquestacion_regla_repositorios.py | 16 +- tests/test_orquestacion_riesgos.py | 20 +-- tests/test_orquestacion_timeline.py | 12 +- tests/test_patient_risk.py | 4 +- tests/test_reportes.py | 8 +- tests/test_seguimiento.py | 8 +- webapi/__init__.py | 8 +- webapi/blueprints/imports.py | 6 +- webapi/blueprints/{reportes.py => reports.py} | 26 ++-- webapi/{seguimiento.py => follow_up.py} | 14 +- webapi/imports/audit.py | 2 +- webapi/orchestration/__init__.py | 37 +++++ webapi/orchestration/__main__.py | 63 ++++++++ .../connection.py} | 2 +- .../contexto.py => orchestration/context.py} | 30 ++-- .../ciclo.py => orchestration/cycle.py} | 140 +++++++++--------- .../proyecto.py => orchestration/project.py} | 4 +- webapi/orchestration/repositories.py | 95 ++++++++++++ .../ejecutor.py => orchestration/runner.py} | 60 ++++---- .../semantic_layer.py | 0 webapi/orquestacion/__init__.py | 39 ----- webapi/orquestacion/__main__.py | 63 -------- webapi/orquestacion/repositorios.py | 95 ------------ webapi/patient_risk.py | 4 +- ...{indicadores_vivos.py => recomputation.py} | 62 ++++---- 36 files changed, 510 insertions(+), 512 deletions(-) rename webapi/blueprints/{reportes.py => reports.py} (72%) rename webapi/{seguimiento.py => follow_up.py} (86%) create mode 100644 webapi/orchestration/__init__.py create mode 100644 webapi/orchestration/__main__.py rename webapi/{orquestacion/conexion.py => orchestration/connection.py} (92%) rename webapi/{orquestacion/contexto.py => orchestration/context.py} (67%) rename webapi/{orquestacion/ciclo.py => orchestration/cycle.py} (56%) rename webapi/{orquestacion/proyecto.py => orchestration/project.py} (86%) create mode 100644 webapi/orchestration/repositories.py rename webapi/{orquestacion/ejecutor.py => orchestration/runner.py} (54%) rename webapi/{orquestacion => orchestration}/semantic_layer.py (100%) delete mode 100644 webapi/orquestacion/__init__.py delete mode 100644 webapi/orquestacion/__main__.py delete mode 100644 webapi/orquestacion/repositorios.py rename webapi/{indicadores_vivos.py => recomputation.py} (71%) diff --git a/Dockerfile b/Dockerfile index 788bc0e..9df8966 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,7 +31,7 @@ ENV MLFLOW_TRACKING_URI=sqlite:////data/mlflow.db ENV MLFLOW_ARTIFACT_ROOT=/data/mlflow-artefactos # No usage telemetry from MLflow: the server runs on a closed network. ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true -# Aggregate import log and the live indicator queue (webapi.indicadores_vivos). +# Aggregate import log and the live indicator queue (webapi.recomputation). ENV WEBAPI_REPORT_DIR=/data/reportes ENV INDICADORES_DIR=/data/indicadores ENV MLFLOW_DISABLE_AGENT_HINT=1 diff --git a/README.md b/README.md index 26f2be7..dcc30cb 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ webapi/ │ └── audit.py bitácora agregada (sin datos de pacientes) ├── nlp.py python -m webapi.nlp evaluate|train: extracción contra una clave de respuestas ├── indicadores.py rutas de indicadores (del equipo de indicadores) -├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga +├── recomputation.py cola y servicio que recalcula indicadores tras cada carga └── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION) ``` @@ -90,7 +90,7 @@ for d in cacu cama tea governance; do uv run alembic -c ../Persistance/persistance/$d/alembic.ini upgrade head done uv run python main.py # http://localhost:5050 -uv run python -m webapi.indicadores_vivos # recálculo de indicadores, en otra terminal +uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal ``` Medir la extracción de documentos contra una clave de respuestas (por documento y diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index dc83ff7..46bdf4c 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -16,11 +16,11 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER esac done -# The live indicator worker (webapi.indicadores_vivos) shares the image; the +# The live indicator worker (webapi.recomputation) shares the image; the # API container runs the migrations, so the worker starts after it. if [ "$1" = "indicadores" ]; then cd /app/WebApi - exec uv run --no-sync python -m webapi.indicadores_vivos + exec uv run --no-sync python -m webapi.recomputation fi cd /app/WebApi diff --git a/tests/conftest.py b/tests/conftest.py index fe080dc..5dd6327 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,8 +5,8 @@ `_DATABASE_URL` alone has no effect once an engine exists. `wire_domain` resets all three (env var, singleton, cache). -The `base`/`base_de` family (below `ANIO`) is for `webapi.orquestacion`: -una base del dominio por prueba, migrada por el paso `migrar`, con el staging +The `base`/`base_de` family (below `ANIO`) is for `webapi.orchestration`: +una base del dominio por prueba, migrada por el paso `migrate`, con el staging sintético del kit. """ import os @@ -20,9 +20,9 @@ from sqlalchemy import create_engine from sqlmodel import Session from indicadores_kit.registry.parametros import RUTA_PARAMETROS -from webapi.orquestacion import Contexto, correr -from webapi.orquestacion.conexion import apuntar -from webapi.orquestacion.repositorios import repositorios_de +from webapi.orchestration import Context, run +from webapi.orchestration.connection import point_to +from webapi.orchestration.repositories import repositories_of # Tests use throwaway SQLite files as "arbitrary SQL sources"; production # excludes sqlite by default (see webapi.imports.connectors.sql_policy). @@ -44,13 +44,13 @@ class Base: """El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance.""" proyecto: str - ctx: Contexto + ctx: Context dominio: object motor: object - def correr(self, *pasos: str, **cambios) -> dict: + def run(self, *pasos: str, **cambios) -> dict: """Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una.""" - return {p.nombre: p.resumen for p in correr(replace(self.ctx, **cambios), solo=pasos)} + return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)} def staging(self): """Una sesión sobre la base, para cambiar el staging como lo haría la ingesta.""" @@ -60,10 +60,10 @@ class Base: def base_de(proyecto: str, carpeta, datos=None) -> Base: """A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts.""" url = f"sqlite:///{carpeta / f'{proyecto}.db'}" - apuntar(proyecto, url) + point_to(proyecto, url) manifest = os.environ.get("DBT_MANIFEST") - ctx = Contexto(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositorios_de(proyecto)) - correr(ctx, solo=["migrar"]) + ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto)) + run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: (datos or import_module(f"indicadores_kit.{proyecto}.fixtures").insertar)(sesion) @@ -141,7 +141,7 @@ def cliente_de(proyecto: str, tmp_path_factory): """Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging.""" carpeta = tmp_path_factory.mktemp(proyecto) base = base_de(proyecto, carpeta) - base.correr("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos", permitir_sin_definir=True) + base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True) try: from webapi import create_app diff --git a/tests/test_cama_measures.py b/tests/test_cama_measures.py index 0f1b7f4..b292d3a 100644 --- a/tests/test_cama_measures.py +++ b/tests/test_cama_measures.py @@ -1,7 +1,7 @@ """What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit computed on the same fixture data: every measure, every period, its units and its numbers. -Fixtures: `base`, the CaMa fixture database through the cycle up to `modelos` (dbt's views); `manifest`, dbt's +Fixtures: `base`, the CaMa fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published numbers for each measure and period (counts only; suppression off). """ @@ -20,7 +20,7 @@ from webapi.durations import answer_duration, duration_definitions from webapi.metrics import Question, answer, measure_definitions ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8")) -UNTIL_MODELS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @pytest.fixture @@ -34,8 +34,8 @@ def manifest(): @pytest.fixture def base(tmp_path, sin_supresion, manifest): base = base_de("cama", tmp_path) - base.correr(*UNTIL_MODELS, parametros=sin_supresion, permitir_sin_definir=True) - yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True)) base.motor.dispose() diff --git a/tests/test_measure_cases.py b/tests/test_measure_cases.py index a0ffa77..73369d4 100644 --- a/tests/test_measure_cases.py +++ b/tests/test_measure_cases.py @@ -6,7 +6,7 @@ latest version of each, the bands by the rules' cut points). Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each `pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views -created by the cycle (`catalogos` … `modelos`; needs `DBT_MANIFEST`). +created by the cycle (`catalogs` … `event_models`; needs `DBT_MANIFEST`). """ import json @@ -70,8 +70,8 @@ def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case if not manifest: pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") base = base_de("cacu", tmp_path, rows_of(case)) - base.correr("catalogos", "cargar", "registro", "definiciones", "modelos", parametros=sin_supresion, - permitir_sin_definir=True) + base.run("catalogs", "load", "registry", "definitions", "event_models", parameters=sin_supresion, + allow_undecided=True) with base.motor.begin() as connection: for key, value in case.get("parametros", {}).items(): connection.execute(text("update def_parametro set valor = :v where clave = :k"), diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py index c93f30d..ea6f3e0 100644 --- a/tests/test_metrics_on_request.py +++ b/tests/test_metrics_on_request.py @@ -2,7 +2,7 @@ dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which keeps each answer under its key. -Fixtures: `base`, the CaCu fixture database through the cycle up to `modelos` (which creates dbt's event models); +Fixtures: `base`, the CaCu fixture database through the cycle up to `event_models` (which creates dbt's event models); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13 and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against. """ @@ -22,11 +22,11 @@ from conftest import base_de from core.cacu.models import BiopsiaCervical, CitologiaCervical from webapi.compositions import answer_composition, composition_definitions, composition_report from webapi.metrics import Question, answer, measure_definitions, measure_report -from webapi.orquestacion import correr +from webapi.orchestration import run IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7" STATUS = "estatus_seguimiento" -HASTA_MODELOS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos") +HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models") PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"] SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json" @@ -42,8 +42,8 @@ def manifest(): @pytest.fixture def base(tmp_path, sin_supresion, manifest): base = base_de("cacu", tmp_path) - base.correr(*HASTA_MODELOS, parametros=sin_supresion, permitir_sin_definir=True) - yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True)) + base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True)) base.motor.dispose() @@ -120,12 +120,12 @@ def reports(base) -> int: def reload(base, change) -> None: - """Changes the staging as the ingestion would and runs `cargar`: a new load, known later than everything before.""" + """Changes the staging as the ingestion would and runs `load`: a new load, known later than everything before.""" time.sleep(0.01) with Session(base.motor) as session: change(session) session.commit() - correr(base.ctx, solo=["cargar"]) + run(base.ctx, only=["load"]) def test_ind1_answers_what_the_kit_computed(base, definition, kit): diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index b8cf16c..8ec5f4a 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -14,8 +14,8 @@ import pytest from sqlalchemy import create_engine, text from sqlmodel import Session -from webapi.orquestacion import Contexto, correr -from webapi.orquestacion.conexion import apuntar +from webapi.orchestration import Context, run +from webapi.orchestration.connection import point_to ANIO = 2025 # Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas). @@ -32,25 +32,25 @@ def bases(request, tmp_path_factory): proyecto = request.param carpeta = tmp_path_factory.mktemp(proyecto) url = f"sqlite:///{carpeta / 'orquestada.db'}" - apuntar(proyecto, url) - # `observar` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de + point_to(proyecto, url) + # `observe` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de # dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo. - ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"])) - correr(ctx, solo=["migrar"]) + ctx = Context(proyecto, ANIO, ANIO, allow_undecided=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"])) + run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) sesion.commit() - pasos = correr(ctx) + pasos = run(ctx) return proyecto, ctx, motor, None, pasos def test_corre_todos_los_pasos_en_orden(bases): proyecto, _, _, _, pasos = bases - nombres = [p.nombre for p in pasos] - # `migrar` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9). - assert nombres[0] == "migrar" and nombres.index("catalogos") < nombres.index("cargar") - assert nombres.index("cargar") < nombres.index("modelos") and "calcular" not in nombres + nombres = [p.name for p in pasos] + # `migrate` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9). + assert nombres[0] == "migrate" and nombres.index("catalogs") < nombres.index("load") + assert nombres.index("load") < nombres.index("event_models") and "calcular" not in nombres @@ -60,7 +60,7 @@ def test_volver_a_correr_no_agrega_reportes(bases): _, ctx, motor, _, _ = bases with motor.connect() as con: antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() - correr(ctx) + run(ctx) with motor.connect() as con: assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes @@ -68,9 +68,9 @@ def test_volver_a_correr_no_agrega_reportes(bases): def test_en_cacu_arma_su_cohorte_una_vez(bases): proyecto, ctx, motor, _, pasos = bases if proyecto != "cacu": - assert "cohortes" not in [p.nombre for p in pasos] # T-21h: TEA y CaMa, solo propuestas + assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas return - (armado_id, nuevo), = [p.resumen for p in pasos if p.nombre == "cohortes"][0].values() + (armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values() 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( diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index fbaf427..7bfe6ab 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -13,14 +13,14 @@ from indicadores_kit.registry.edades import grupos_de_cortes from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo from indicadores_kit.registry.periodos import periodos_de_tipos from indicadores_kit.tablas import tablas_de -from webapi.orquestacion.proyecto import tipos_de_periodo +from webapi.orchestration.project import period_types from conftest import ANIO # El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}. def cargas(proyecto) -> tuple[str, ...]: """El paso que lleva el staging a la plata (staging directo, T-20c).""" - return ("cargar",) + return ("load",) @@ -38,19 +38,19 @@ def cargas(proyecto) -> tuple[str, ...]: def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base): - base.correr("registro") - base.correr("registro", anio_inicio=ANIO - 1) + base.run("registry") + base.run("registry", year_from=ANIO - 1) tablas = tablas_de(base.proyecto) - esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas) + esperados = periodos_de_tipos(period_types(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas) assert base.dominio.dim_periodo_repository.count() == len(esperados) assert base.dominio.measure_report_repository.count() == 0 def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base): """I-MD27 (T-24f): de `comun.dim_fecha.desde` al fin del último año, y los grupos de `.grupos_edad`.""" - base.correr("registro") - base.correr("registro", anio_fin=ANIO + 1) # repetir deja la tabla igual, con el año nuevo + base.run("registry") + base.run("registry", year_to=ANIO + 1) # repetir deja la tabla igual, con el año nuevo valores = valores_del_archivo(RUTA_PARAMETROS) desde = date.fromisoformat(valores["comun.dim_fecha.desde"]) @@ -66,13 +66,13 @@ def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base): def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): - base.correr("registro") + base.run("registry") periodos = base.dominio.dim_periodo_repository.count() malo = tmp_path / "malo.toml" malo.write_text('[comun.x]\nvalor = 1\nestado = "provisional"\n', encoding="utf-8") with pytest.raises(ValueError, match="fuente"): - base.correr("registro", anio_inicio=ANIO - 1, anio_fin=ANIO + 1, parametros=malo) + base.run("registry", year_from=ANIO - 1, year_to=ANIO + 1, parameters=malo) assert base.dominio.def_parametro_repository.get("comun.x") is None assert base.dominio.def_parametro_repository.get("comun.umbral_supresion") is not None @@ -80,15 +80,15 @@ def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path): def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): - """Pins down: `definiciones` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a + """Pins down: `definitions` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" - resumen = base.correr("definiciones")["definiciones"] + resumen = base.run("definitions")["definitions"] # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata. - assert resumen["definiciones"] == {"cacu": 10, "cama": 7}[base.proyecto] + assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain - assert base.correr("definiciones")["definiciones"]["borradas"] == 0 + assert base.run("definitions")["definitions"]["borradas"] == 0 diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index b4bc39c..e8ded34 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -3,38 +3,38 @@ import pytest from hamilton import driver -from webapi.orquestacion import ciclo, pasos_de +from webapi.orchestration import cycle, steps_of def dependencias(proyecto: str) -> dict[str, set[str]]: - dr = driver.Builder().with_modules(ciclo).with_config({"con_cohortes": proyecto == "cacu"}).build() + dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build() return {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"} def antes(deps: dict[str, set[str]], paso: str) -> set[str]: """Todos los pasos que corren antes de `paso`.""" previos = set() - pendientes = list(deps[paso]) - while pendientes: - anterior = pendientes.pop() + pending = list(deps[paso]) + while pending: + anterior = pending.pop() if anterior not in previos: previos.add(anterior) - pendientes.extend(deps[anterior]) + pending.extend(deps[anterior]) return previos @pytest.mark.parametrize("proyecto", ["cacu", "cama"]) def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto): deps = dependencias(proyecto) - assert deps["migrar"] == set() - assert {"migrar", "catalogos"} <= antes(deps, "cargar") # decisión 6 de §9 - assert {"cargar"} <= antes(deps, "modelos") - assert {"registro"} <= antes(deps, "observar") - assert {"cargar", "catalogos"} <= antes(deps, "verificar_plata") + assert deps["migrate"] == set() + assert {"migrate", "catalogs"} <= antes(deps, "load") # decisión 6 de §9 + assert {"load"} <= antes(deps, "event_models") + assert {"registry"} <= antes(deps, "observe") + 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 {"cohortes", "estimar"} <= set(pasos_de("cacu")) + assert {"cohorts", "estimate"} <= set(steps_of("cacu")) for proyecto in ("cama", "tea"): - assert not {"cohortes", "estimar"} & set(pasos_de(proyecto)) + assert not {"cohorts", "estimate"} & set(steps_of(proyecto)) diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 9631914..96d743b 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -31,7 +31,7 @@ CORTE = date(2025, 12, 31) def ultima_carga(base): - return max(base.ctx.repos.plata.carga.list(limit=100), key=lambda c: c.carga_id) + return max(base.ctx.repos.silver.loads.list(limit=100), key=lambda c: c.carga_id) def contar(base, sql: str) -> int: @@ -60,7 +60,7 @@ def cambiar_staging(base) -> str: def filas_del_catalogo(base) -> dict[str, int]: """Cuántas filas tiene cada tabla de catálogo en la base.""" - plata = base.ctx.repos.plata.catalogos + plata = base.ctx.repos.silver.catalogs with base.staging() as sesion: return { "estudios": len(sesion.exec(select(plata.model)).all()), @@ -74,15 +74,15 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base): del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados), "valores": len(catalogo.valores)} - assert base.correr("catalogos")["catalogos"] == {**del_toml, "retirados": 0} + assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0} assert filas_del_catalogo(base) == del_toml def test_volver_a_correr_catalogos_no_cambia_nada(base): - base.correr("catalogos") + base.run("catalogs") antes = filas_del_catalogo(base) - assert base.correr("catalogos")["catalogos"]["retirados"] == 0 + assert base.run("catalogs")["catalogs"]["retirados"] == 0 assert filas_del_catalogo(base) == antes @@ -90,14 +90,14 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base): def test_cargar_lleva_el_staging_a_persona_y_la_plata(base): - base.correr("catalogos") - carga = base.correr("cargar")["cargar"] + base.run("catalogs") + carga = base.run("load")["load"] procedimientos, observaciones = plata_de(base) assert procedimientos and observaciones assert carga.fin is not None and (carga.filas_nuevas, carga.filas_cambiadas, carga.filas_sin_cambio) == ( procedimientos, 0, 0) - assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronce.staging.leer( + assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronze.staging.read( {"p": tablas_de_staging(base.proyecto)[0]})["p"]) # Ningún reporte ni parte sin su toma (salvo los huérfanos, que no se escriben). assert contar(base, "SELECT COUNT(*) FROM procedimiento WHERE clase IN ('reporte', 'parte') AND padre_id IS NULL") == 0 @@ -108,10 +108,10 @@ def test_cargar_lleva_el_staging_a_persona_y_la_plata(base): def test_volver_a_cargar_sin_cambios_no_toca_nada(base): - base.correr("catalogos", "cargar") + base.run("catalogs", "load") antes = plata_de(base) - segunda = base.correr("cargar")["cargar"] + segunda = base.run("load")["load"] assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 0, antes[0]) assert plata_de(base) == antes for tabla in ("procedimiento", "observacion_clinica"): @@ -119,11 +119,11 @@ def test_volver_a_cargar_sin_cambios_no_toca_nada(base): def test_un_cambio_en_staging_toca_un_procedimiento(base): - base.correr("catalogos", "cargar") + base.run("catalogs", "load") antes = plata_de(base) cambiar_staging(base) - segunda = base.correr("cargar")["cargar"] + segunda = base.run("load")["load"] assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 1, antes[0] - 1) assert plata_de(base) == antes @@ -134,9 +134,9 @@ def test_un_cambio_en_staging_toca_un_procedimiento(base): def test_las_vistas_se_construyen_y_se_pueden_repetir(base): - primera = base.correr("vistas")["vistas"] + primera = base.run("views")["views"] - assert base.correr("vistas")["vistas"] == primera + assert base.run("views")["views"] == primera # Only `v_persona`: the published numbers are answered on request, so the publication views aren't built. assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"] @@ -166,9 +166,9 @@ observables = pytest.mark.parametrize("proyecto", ["cacu", "cama"]) @observables def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla("2024-06-01")) + base.run("load", "registry", parameters=con_regla("2024-06-01")) - cuantos = base.correr("observar", corte=CORTE)["observar"] + cuantos = base.run("observe", cutoff=CORTE)["observe"] periodos = base.dominio.periodo_observacion_repository.list() assert cuantos == len(periodos) == base.dominio.persona_repository.count() @@ -178,9 +178,9 @@ def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla): @observables def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla()) + base.run("load", "registry", parameters=con_regla()) - base.correr("observar") + base.run("observe") carga = ultima_carga(base) assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == { @@ -189,10 +189,10 @@ def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_re @observables def test_observar_se_puede_repetir_sin_duplicar(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla()) + base.run("load", "registry", parameters=con_regla()) - primera = base.correr("observar", corte=date(2025, 6, 30))["observar"] - segunda = base.correr("observar", corte=CORTE)["observar"] + primera = base.run("observe", cutoff=date(2025, 6, 30))["observe"] + segunda = base.run("observe", cutoff=CORTE)["observe"] assert primera == segunda == base.dominio.periodo_observacion_repository.count() assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE} @@ -200,37 +200,37 @@ def test_observar_se_puede_repetir_sin_duplicar(base, con_regla): @observables def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base): - base.correr("cargar", "registro") + base.run("load", "registry") with pytest.raises(ParametroSinDefinir, match="inicio_datos"): - base.correr("observar", corte=CORTE) - assert base.correr("observar", corte=CORTE, permitir_sin_definir=True)["observar"] == ( + base.run("observe", cutoff=CORTE) + assert base.run("observe", cutoff=CORTE, allow_undecided=True)["observe"] == ( base.dominio.persona_repository.count()) @observables def test_sin_el_registro_observar_dice_que_falta(base): - base.correr("cargar") + base.run("load") with pytest.raises(KeyError, match="preparar_registro|registro"): - base.correr("observar", corte=CORTE) + base.run("observe", cutoff=CORTE) @observables def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla): - base.correr("cargar", "registro", parametros=con_regla("2024-06-01")) + base.run("load", "registry", parameters=con_regla("2024-06-01")) with pytest.raises(ValueError, match="anterior al inicio"): - base.correr("observar", corte=date(2024, 5, 31)) + base.run("observe", cutoff=date(2024, 5, 31)) assert base.dominio.periodo_observacion_repository.count() == 0 @observables def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla): - base.correr("registro", parametros=con_regla()) + base.run("registry", parameters=con_regla()) with pytest.raises(ObservacionSinCorte): - base.correr("observar") + base.run("observe") # --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA --- @@ -239,7 +239,7 @@ def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla): @pytest.mark.parametrize("proyecto", ["cacu"]) def test_verificar_plata_en_cacu_cuenta_los_valores_fuera_de_catalogo_del_fixture(base): - conteos = base.correr("catalogos", "cargar", "verificar_plata")["verificar_plata"] + conteos = base.run("catalogs", "load", "check_silver")["check_silver"] # I-MD16 (textos del fixture fuera del catálogo) e I-MD18 (especialidades que el alias no reconoce): en la # plata, una observación de código sin `valor_id` y con su `valor_fuente`. diff --git a/tests/test_orquestacion_regla_repositorios.py b/tests/test_orquestacion_regla_repositorios.py index f13c068..048a27d 100644 --- a/tests/test_orquestacion_regla_repositorios.py +++ b/tests/test_orquestacion_regla_repositorios.py @@ -1,7 +1,7 @@ """La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`. -Las subclases viven en `persistance/aristas/` y Persistance las instancia con su -fábrica de sesión (ADR-MD-005). Solo `conexion.py` nombra a `persistance.db`: cambia a +Las subclases viven en `persistance/edges/` y Persistance las instancia con su +fábrica de sesión (ADR-MD-005). Solo `connection.py` nombra a `persistance.db`: cambia a qué base apunta Persistance (`_DATABASE_URL` en memoria); no es un paso. """ @@ -10,10 +10,10 @@ from pathlib import Path import pytest -from webapi.orquestacion.repositorios import repositorios_de +from webapi.orchestration.repositories import repositories_of -PAQUETE = Path(__file__).parents[1] / "webapi" / "orquestacion" -EXENTOS = {"conexion.py"} +PAQUETE = Path(__file__).parents[1] / "webapi" / "orchestration" +EXENTOS = {"connection.py"} PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db") @@ -25,6 +25,6 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo): @pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)]) def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes): - repos = repositorios_de(proyecto) - assert (repos.oro.cohorte is not None) == con_cohortes - assert repos.oro.calculo.model.__tablename__ == "measure_report" + repos = repositories_of(proyecto) + assert (repos.gold.cohorts is not None) == con_cohortes + assert repos.gold.calculation.model.__tablename__ == "measure_report" diff --git a/tests/test_orquestacion_riesgos.py b/tests/test_orquestacion_riesgos.py index 5cb1a4c..9d3f8a3 100644 --- a/tests/test_orquestacion_riesgos.py +++ b/tests/test_orquestacion_riesgos.py @@ -1,4 +1,4 @@ -"""El paso `estimar` y la orden `confirmar-riesgos` (ADR-MD-008), con un estimador de prueba. +"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba. El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow. """ @@ -8,7 +8,7 @@ from dataclasses import dataclass import pytest from sqlalchemy import text -from webapi.orquestacion.__main__ import confirmar_riesgos, main +from webapi.orchestration.__main__ import confirm_risks, main URL = "cacu/cohorte_vigilancia" @@ -43,7 +43,7 @@ class EstimadorFijo: @pytest.fixture def cacu(base): - base.correr("catalogos", "cargar", "modelos", "cohortes", permitir_sin_definir=True) + base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True) return base @@ -56,7 +56,7 @@ def cuenta(base, sql): def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu): estimador = EstimadorFijo() - (lote_id, nuevo) = cacu.correr("estimar", estimadores={URL: estimador})["estimar"][URL] + (lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL] miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1") assert nuevo and miembros > 0 @@ -68,23 +68,23 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu): @pytest.mark.parametrize("proyecto", ["cacu"]) def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu): - (primero, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] + (primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] - assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False) - assert cacu.correr("estimar")["estimar"] == {} + assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False) + assert cacu.run("estimate")["estimate"] == {} assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1 @pytest.mark.parametrize("proyecto", ["cacu"]) def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys): - (lote_id, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] + (lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}") - main(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "revisado"]) + main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"]) assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros - assert confirmar_riesgos("cacu", lote_id, "error de captura", anular=True) == miembros + assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros diff --git a/tests/test_orquestacion_timeline.py b/tests/test_orquestacion_timeline.py index 8d07c93..eda31fa 100644 --- a/tests/test_orquestacion_timeline.py +++ b/tests/test_orquestacion_timeline.py @@ -1,9 +1,9 @@ -"""What this module covers: the timeline `repositorios_de` wires into `ctx.repos.plata` is dbt's view +"""What this module covers: the timeline `repositories_of` wires into `ctx.repos.silver` is dbt's view `cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them. Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created -(`catalogos`, `cargar`, `modelos`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on +(`catalogs`, `load`, `event_models`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time). """ @@ -28,7 +28,7 @@ def proyecto(): def loaded(base): if not os.environ.get("DBT_MANIFEST"): pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") - base.correr("catalogos", "cargar", "modelos") + base.run("catalogs", "load", "event_models") return base @@ -47,7 +47,7 @@ def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows """Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or the view stops giving one of the kit's rows.""" - rows = loaded.ctx.repos.plata.timeline.read(until=CORTE) + rows = loaded.ctx.repos.silver.timeline.read(until=CORTE) assert as_kit(rows) == kit_rows assert {row["tipo"] for row in rows} & INFERRED assert all(isinstance(row["fecha"], date) for row in rows) @@ -56,7 +56,7 @@ def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows): """Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied.""" patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2] - rows = loaded.ctx.repos.plata.timeline.read(patients=patients, until=CORTE) + rows = loaded.ctx.repos.silver.timeline.read(patients=patients, until=CORTE) assert {row["pac_id"] for row in rows} == set(patients) assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients] @@ -64,7 +64,7 @@ def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows): def test_known_until_cuts_at_what_was_loaded(loaded): """Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known, after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text.""" - timeline = loaded.ctx.repos.plata.timeline + timeline = loaded.ctx.repos.silver.timeline everything = timeline.read(until=CORTE) known = {row["conocida_en"] for row in everything} assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known) diff --git a/tests/test_patient_risk.py b/tests/test_patient_risk.py index 661e629..e6757ce 100644 --- a/tests/test_patient_risk.py +++ b/tests/test_patient_risk.py @@ -47,11 +47,11 @@ def seeded(client): CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)]) session.commit() build_id = build.armado_id - batch, _ = cacu.cohorte_repository.guardar_lote( + 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.cohorte_repository.cambiar_estado(batch, "final", "revisado") + cacu.cohort_repository.change_state(batch, "final", "revisado") return scored, unscored, outside diff --git a/tests/test_reportes.py b/tests/test_reportes.py index 93078f8..ebf0949 100644 --- a/tests/test_reportes.py +++ b/tests/test_reportes.py @@ -97,15 +97,15 @@ def test_report_endpoints(client): def test_indicators_recompute_from_imported_rows(client): - from webapi.indicadores_vivos import ColaDeRecalculo + from webapi.recomputation import RecomputationQueue - cola = ColaDeRecalculo() + cola = RecomputationQueue() assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True - assert cola.atender() == ["cacu"] + assert cola.serve() == ["cacu"] estado = client.get("/reportes/indicadores").get_json()["cacu"] assert estado["estado"] == "ok", estado assert estado["pendiente"] is False - assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "modelos"} + assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"} assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == { "IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE", "CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"} diff --git a/tests/test_seguimiento.py b/tests/test_seguimiento.py index ce8e417..110ca6e 100644 --- a/tests/test_seguimiento.py +++ b/tests/test_seguimiento.py @@ -60,9 +60,9 @@ def test_una_pagina_de_mas_da_404(client): assert "error" in response.get_json() -def test_en_dev_esta_obsoleta(): - """Fija: `en_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso.""" - from webapi.seguimiento import en_dev +def test_in_dev_esta_obsoleta(): + """Fija: `in_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso.""" + from webapi.follow_up import in_dev with pytest.warns(DeprecationWarning): - en_dev() + in_dev() diff --git a/webapi/__init__.py b/webapi/__init__.py index 4eca115..3b78629 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -9,8 +9,8 @@ from webapi.blueprints.cacu import cacu_bp from webapi.blueprints.data import data_bp from webapi.blueprints.governance import governance_bp from webapi.blueprints.imports import imports_bp -from webapi.blueprints.reportes import reportes_bp -from webapi.seguimiento import blueprint_de_seguimiento +from webapi.blueprints.reports import reports_bp +from webapi.follow_up import follow_up_blueprint class IsoJSONProvider(DefaultJSONProvider): @@ -72,7 +72,7 @@ def create_app() -> Flask: app.register_blueprint(imports_bp, url_prefix="/imports") app.register_blueprint(data_bp, url_prefix="/data") app.register_blueprint(governance_bp, url_prefix="/governance") - app.register_blueprint(reportes_bp, url_prefix="/reportes") + app.register_blueprint(reports_bp, url_prefix="/reportes") # The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest. if os.environ.get("DBT_MANIFEST"): from importlib import import_module @@ -90,7 +90,7 @@ def create_app() -> Flask: from webapi.patient_risk import patient_risk_blueprint - app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu") + app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu") return app diff --git a/webapi/blueprints/imports.py b/webapi/blueprints/imports.py index 29f6098..e3ded7c 100644 --- a/webapi/blueprints/imports.py +++ b/webapi/blueprints/imports.py @@ -28,7 +28,7 @@ from webapi.imports.services.import_service import ( serialize_errors, validate_source, ) -from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo +from webapi.recomputation import DOMAINS, RecomputationQueue from webapi.imports.services.introspection_service import ( detect_pdf, document_report, @@ -403,9 +403,9 @@ def commit(): finally: import_audit.record(audit) recalculating = False - if audit.domain in DOMINIOS and any(r.created or r.updated for r in results): + if audit.domain in DOMAINS and any(r.created or r.updated for r in results): try: - ColaDeRecalculo().solicitar(audit.domain) + RecomputationQueue().request_run(audit.domain) recalculating = True except OSError: # The rows are already saved; failing here would invite a duplicate retry. diff --git a/webapi/blueprints/reportes.py b/webapi/blueprints/reports.py similarity index 72% rename from webapi/blueprints/reportes.py rename to webapi/blueprints/reports.py index e1ee8a0..74a587a 100644 --- a/webapi/blueprints/reportes.py +++ b/webapi/blueprints/reports.py @@ -3,13 +3,13 @@ indicator recomputation. Nothing here returns row-level data.""" from flask import Blueprint, Response, jsonify, request from webapi.imports import audit as import_audit -from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo +from webapi.recomputation import DOMAINS, RecomputationQueue -reportes_bp = Blueprint("reportes", __name__) +reports_bp = Blueprint("reportes", __name__) -@reportes_bp.get("/importaciones") -def importaciones(): +@reports_bp.get("/importaciones") +def import_log(): """Totals per target over every logged attempt, plus the latest attempts (`?limite=50`, newest first; `?dominio=cacu` to filter).""" records = import_audit.default_sink().read() @@ -23,8 +23,8 @@ def importaciones(): return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]}) -@reportes_bp.get("/importaciones/descarga") -def importaciones_descarga(): +@reports_bp.get("/importaciones/descarga") +def import_log_download(): """The raw log, one JSON object per line.""" sink = import_audit.default_sink() body = sink.path.read_bytes() if sink.path.exists() else b"" @@ -35,15 +35,15 @@ def importaciones_descarga(): ) -@reportes_bp.get("/indicadores") -def indicadores_estado(): +@reports_bp.get("/indicadores") +def recomputation_status(): """Per domain: state of the last recomputation and whether another is pending.""" - return jsonify(ColaDeRecalculo().estado()) + return jsonify(RecomputationQueue().status()) -@reportes_bp.post("/indicadores//recalcular") -def indicadores_recalcular(dominio: str): - if dominio not in DOMINIOS: +@reports_bp.post("/indicadores//recalcular") +def recompute(dominio: str): + if dominio not in DOMAINS: return jsonify({"error": f"dominio desconocido: {dominio}"}), 404 - ColaDeRecalculo().solicitar(dominio) + RecomputationQueue().request_run(dominio) return jsonify({"pendiente": True}), 202 diff --git a/webapi/seguimiento.py b/webapi/follow_up.py similarity index 86% rename from webapi/seguimiento.py rename to webapi/follow_up.py index 17144c5..eb1985c 100644 --- a/webapi/seguimiento.py +++ b/webapi/follow_up.py @@ -19,28 +19,28 @@ from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seg from sqlmodel import Session FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") -SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno +DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno -def en_dev() -> bool: +def in_dev() -> bool: """Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará.""" - warnings.warn("en_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2) + warnings.warn("in_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2) return bool(os.environ.get("DEV_REVISION")) -def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint: +def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint: """El blueprint de la lista, para registrarlo con `url_prefix="/cacu"`.""" blueprint = Blueprint("cacu_seguimiento", __name__) @blueprint.get("/seguimiento") def get_seguimiento(): try: - pedido = _pedido(request.args) + pedido = _requested(request.args) except ValueError as error: return jsonify({"error": str(error)}), 400 sesion = get_session() try: - cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido) + cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido) except PedidoInvalido as error: return jsonify({"error": str(error)}), 400 except PaginaFuera as error: @@ -52,7 +52,7 @@ def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint: return blueprint -def _pedido(args) -> dict: +def _requested(args) -> dict: """Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito.""" pedido = {} if corte := args.get("corte"): diff --git a/webapi/imports/audit.py b/webapi/imports/audit.py index 7525f2d..63246e7 100644 --- a/webapi/imports/audit.py +++ b/webapi/imports/audit.py @@ -1,6 +1,6 @@ """Aggregate log of every import attempt (validations and commits). -Each attempt becomes one JSON line in `importaciones.jsonl` under +Each attempt becomes one JSON line in `import_log.jsonl` under `WEBAPI_REPORT_DIR`. A record only carries counts, field names, source column names and value *shapes* ("9999-99-99" for a date in an unexpected format): never a row, a file name, a connection string or an identifier. diff --git a/webapi/orchestration/__init__.py b/webapi/orchestration/__init__.py new file mode 100644 index 0000000..ca609c7 --- /dev/null +++ b/webapi/orchestration/__init__.py @@ -0,0 +1,37 @@ +"""Each domain's cycle (CaCu, CaMa): from the staging the import leaves to the silver tables, the reference tables, the +publication catalog and the views dbt compiled, which the measures are answered over. [Hamilton](https://hamilton.apache.org/) +runs it. + +Each step is a function of `cycle.py`. It takes the `Context` and, as parameters, the steps that must run before it; +Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by +Persistance's repositories (`ctx.repos`), so each one can run on its own. + + migrate -> catalogs, registry, definitions + catalogs -> load, check_silver + load -> views, event_models, observe, check_silver + registry -> observe + event_models -> cohorts (only where there are cohorts: CaCu) + cohorts -> estimate + + uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026 + uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models + uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica" + +The `indicadores` service (`webapi.recomputation`) runs the same cycle, without `migrate`, each time an import writes +data. + +Module | What it does +------------------|------------- +`cycle.py` | The steps +`runner.py` | `run(ctx, only=...)`: builds Hamilton's driver and runs the steps asked, in order +`context.py` | The `Context`: project, years, cut-off, rules file and repositories +`repositories.py` | `repositories_of(project)`: Persistance's repositories, by layer +`project.py` | A project's period types and cohort definitions +`connection.py` | Points Persistance at another database in the same process (tests) +`semantic_layer.py` | dbt's views a project's measures read, and the publication catalog +""" + +from webapi.orchestration.context import Context +from webapi.orchestration.runner import Step, run, steps_of + +__all__ = ["Context", "Step", "run", "steps_of"] diff --git a/webapi/orchestration/__main__.py b/webapi/orchestration/__main__.py new file mode 100644 index 0000000..b6dca89 --- /dev/null +++ b/webapi/orchestration/__main__.py @@ -0,0 +1,63 @@ +"""La línea de comandos de la orquestación. + + uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026 [--cutoff 2026-01-01] [--allow-undecided] + uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models + uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica" [--void] + +La base es la de `_DATABASE_URL`, como en Persistance. +""" + +import argparse +import logging +from datetime import date +from pathlib import Path + +from webapi.orchestration.context import Context +from webapi.orchestration.runner import run + +PROJECTS = ("cacu", "cama") + + +def main(argv: list[str] | None = None) -> None: + lector = argparse.ArgumentParser(prog="orchestration", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ordenes = lector.add_subparsers(dest="orden", required=True) + c = ordenes.add_parser("cycle", help="corre los pasos del proyecto en orden") + c.add_argument("project", choices=PROJECTS) + c.add_argument("--from", dest="year_from", type=int, required=True, help="primer año de periodos") + c.add_argument("--to", dest="year_to", type=int, required=True, help="último año de periodos") + c.add_argument("--cutoff", type=date.fromisoformat, default=None) + c.add_argument("--allow-undecided", action="store_true") + c.add_argument("--parameters", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)") + c.add_argument("--only", nargs="+", default=None, help="solo estos pasos") + r = ordenes.add_parser("confirm-risks", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)") + r.add_argument("project", choices=PROJECTS) + r.add_argument("lote_id", type=int) + r.add_argument("--reason", required=True, help="por qué se confirma o se anula; queda en cada evaluación") + r.add_argument("--void", action="store_true", help="anular (entered-in-error) en vez de confirmar") + args = lector.parse_args(argv) + + if args.orden == "confirm-risks": + cambiadas = confirm_risks(args.project, args.lote_id, args.reason, void=args.void) + print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}") + return + logging.basicConfig(level=logging.INFO, format="%(message)s") + ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters) + for paso in run(ctx, only=args.only): + print(f"{paso.name:20} {paso.seconds:6.1f} s") + + +def confirm_risks(project: str, lote_id: int, reason: str, *, void: bool = False) -> int: + """Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva. + + No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008). + """ + from persistance.edges.gold import ERROR, FINAL + + from webapi.orchestration.repositories import repositories_of + + return repositories_of(project).gold.cohorts.change_state(lote_id, ERROR if void else FINAL, reason) + + +if __name__ == "__main__": + main() diff --git a/webapi/orquestacion/conexion.py b/webapi/orchestration/connection.py similarity index 92% rename from webapi/orquestacion/conexion.py rename to webapi/orchestration/connection.py index ba1d205..99af46b 100644 --- a/webapi/orquestacion/conexion.py +++ b/webapi/orchestration/connection.py @@ -10,7 +10,7 @@ from persistance.settings import settings from persistance import db -def apuntar(proyecto: str, url: str) -> None: +def point_to(proyecto: str, url: str) -> None: motor = getattr(db, f"get_{proyecto}_engine") if motor.cache_info().currsize: motor().dispose() diff --git a/webapi/orquestacion/contexto.py b/webapi/orchestration/context.py similarity index 67% rename from webapi/orquestacion/contexto.py rename to webapi/orchestration/context.py index 37e2dac..0eab721 100644 --- a/webapi/orquestacion/contexto.py +++ b/webapi/orchestration/context.py @@ -8,36 +8,36 @@ from pathlib import Path from typing import Any -def manifiesto_de_dbt() -> Path | None: +def dbt_manifest_path() -> Path | None: """The deployment's dbt manifest, from `DBT_MANIFEST`.""" ruta = os.environ.get("DBT_MANIFEST") return Path(ruta) if ruta else None @dataclass(frozen=True) -class Contexto: +class Context: """Lo que recibe un paso: el proyecto y las opciones del ciclo. `anio_inicio` y `anio_fin` son los años de los periodos que se registran y calculan. `corte` es la fecha hasta la que llegan los datos; sin ella, cada paso del kit toma la de la última carga. `permitir_sin_definir` deja correr con parámetros que nadie ha decidido: hay que pedirlo a propósito, como en - el kit. `parametros` es el archivo de parámetros que carga `registro`; sin + el kit. `parametros` es el archivo de parámetros que carga `registry`; sin él, el `parametros.toml` del kit. `repos` es todo lo que el paso usa - para tocar la base: nunca abre una sesión por su cuenta (`repositorios.py`). + para tocar la base: nunca abre una sesión por su cuenta (`repositories.py`). """ - proyecto: str - anio_inicio: int - anio_fin: int - corte: date | None = None - permitir_sin_definir: bool = False - parametros: Path | None = None + project: str + year_from: int + year_to: int + cutoff: date | None = None + allow_undecided: bool = False + parameters: Path | None = None # The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle - # creates their event models (`modelos`) and seeds the publication catalog (`definiciones`). - dbt_manifest: Path | None = field(default_factory=manifiesto_de_dbt) - # Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimar(columnas, filas)`, `procedencia()` - # y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimar` no hace nada. - estimadores: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False) + # creates their event models (`event_models`) and seeds the publication catalog (`definitions`). + dbt_manifest: Path | None = field(default_factory=dbt_manifest_path) + # Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()` + # y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada. + estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False) # Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan. repos: Any = field(default=None, compare=False, repr=False) diff --git a/webapi/orquestacion/ciclo.py b/webapi/orchestration/cycle.py similarity index 56% rename from webapi/orquestacion/ciclo.py rename to webapi/orchestration/cycle.py index 3ac515f..2fe7003 100644 --- a/webapi/orquestacion/ciclo.py +++ b/webapi/orchestration/cycle.py @@ -1,12 +1,12 @@ """Los pasos del ciclo de un proyecto, como funciones de Hamilton. -Cada paso recibe el `Contexto` y, como parámetros, los pasos que tienen que +Cada paso recibe el `Context` y, como parámetros, los pasos que tienen que correr antes; de esos nombres sale el grafo. Los pasos no se pasan datos entre sí: todo va por la base, a través de `ctx.repos`, así que cada uno se puede correr solo (`ejecutor.correr(ctx, solo=[...])`). El kit calcula (funciones puras, o funciones de una sesión) y los repositorios -de `persistance.aristas` escriben, cada operación en una sesión (ADR-MD-005). +de `persistance.edges` escriben, cada operación en una sesión (ADR-MD-005). Bronce lo escribe la ingesta, fuera del ciclo. """ @@ -36,24 +36,24 @@ from indicadores_kit.registry.parametros import ( ) from indicadores_kit.registry.periodos import periodos_de_tipos from indicadores_kit.tablas import tablas_de -from persistance.aristas.plata import guardar_carga_en +from persistance.edges.silver import save_load_in from sqlmodel import SQLModel, func, select -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.semantic_layer import catalog_layers, event_views -from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo +from webapi.orchestration.context import Context +from webapi.orchestration.semantic_layer import catalog_layers, event_views +from webapi.orchestration.project import cohort_definitions, period_types -registro_de_eventos = logging.getLogger(__name__) +log = logging.getLogger(__name__) -def migrar(ctx: Contexto) -> str: +def migrate(ctx: Context) -> str: """`alembic upgrade head` del dominio, con el `alembic.ini` de Persistance.""" from alembic import command from alembic.config import Config import persistance - ini = Path(persistance.__file__).parent / ctx.proyecto / "alembic.ini" + ini = Path(persistance.__file__).parent / ctx.project / "alembic.ini" raiz = logging.getLogger() manejadores, nivel = raiz.handlers[:], raiz.level estado = [(r, r.disabled) for r in logging.root.manager.loggerDict.values() if isinstance(r, logging.Logger)] @@ -65,144 +65,144 @@ def migrar(ctx: Contexto) -> str: return "head" -def catalogos(migrar: str, ctx: Contexto) -> dict[str, int]: +def catalogs(migrate: str, ctx: Context) -> dict[str, int]: """`core/catalogos/.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra.""" - catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.proyecto), tablas=tablas_de(ctx.proyecto)) - return ctx.repos.plata.catalogos.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores) + catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project)) + return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores) -def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel: +def load(catalogs: dict[str, int], ctx: Context) -> SQLModel: """`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c). - Incremental por la llave lógica de cada procedimiento (`guardar_carga_en`): repetir no cambia nada. + Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada. """ - tablas, staging = tablas_de(ctx.proyecto), tablas_de_staging(ctx.proyecto) + tablas, staging = tablas_de(ctx.project), tablas_de_staging(ctx.project) def leer(sesion): filas = {modelo.__tablename__: list(sesion.exec(select(modelo))) for modelo in staging} - return carga_desde_staging(filas, proyecto=ctx.proyecto) + return carga_desde_staging(filas, proyecto=ctx.project) def escribir(sesion, datos): - return guardar_carga_en(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento, + return save_load_in(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento, observacion=tablas.Observacion, fuente=datos.fuente, personas=datos.personas, plata=datos.plata) - return ctx.repos.materializador.materializar(leer, escribir) + return ctx.repos.materializer.materialize(leer, escribir) -def vistas(cargar: SQLModel, ctx: Contexto) -> int: +def views(load: SQLModel, ctx: Context) -> int: """`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base.""" - return len(ctx.repos.plata.vistas.construir(ddl_de_v_persona(tablas_de(ctx.proyecto).Persona))) + return len(ctx.repos.silver.views.build_all(ddl_de_v_persona(tablas_de(ctx.project).Persona))) -def registro(migrar: str, ctx: Contexto) -> list[str]: - """`parametros.toml` (o `ctx.parametros`) -> `def_parametro` (se reemplaza), los periodos que falten en +def registry(migrate: str, ctx: Context) -> list[str]: + """`parametros.toml` (o `ctx.parameters`) -> `def_parametro` (se reemplaza), los periodos que falten en `dim_periodo` y las tablas de apoyo `dim_fecha` y `dim_grupo_edad` (se reemplazan; I-MD27). El archivo se lee y valida antes de escribir. Los periodos no se reemplazan: los reportes guardados apuntan a ellos. `dim_fecha` va de `comun.dim_fecha.desde` al fin - de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `.grupos_edad`, si el + de `ctx.year_to` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `.grupos_edad`, si el proyecto los tiene (TEA no). """ - tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto, _manifest(ctx)) - ruta = ctx.parametros or RUTA_PARAMETROS + tablas, tipos = tablas_de(ctx.project), period_types(ctx.project, _manifest(ctx)) + ruta = ctx.parameters or RUTA_PARAMETROS parametros = leer_parametros(ruta, tablas=tablas) - periodos = periodos_de_tipos(tipos, ctx.anio_inicio, ctx.anio_fin, tablas=tablas) + periodos = periodos_de_tipos(tipos, ctx.year_from, ctx.year_to, tablas=tablas) valores = valores_del_archivo(ruta) # Hasta el fin del último año del ciclo o del año del corte (por omisión, la última carga: hoy), el que sea mayor. - hasta = date(max(ctx.anio_fin, (ctx.corte or date.today()).year), 12, 31) + hasta = date(max(ctx.year_to, (ctx.cutoff or date.today()).year), 12, 31) desde = date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE]) - grupos = grupos_de_edad_de(ctx.proyecto, valores, tablas=tablas) - oro = ctx.repos.oro - oro.parametros.reemplazar(parametros) - oro.periodos.agregar_faltantes(periodos) - if oro.fechas is not None and not _cubre(oro.fechas, desde, hasta): - oro.fechas.reemplazar_en_bloque(filas_de_dim_fecha(valores, hasta, proyecto=ctx.proyecto)) - if oro.grupos_edad is not None and grupos is not None: - oro.grupos_edad.reemplazar(grupos) + grupos = grupos_de_edad_de(ctx.project, valores, tablas=tablas) + gold = ctx.repos.gold + gold.parameters.replace_all(parametros) + gold.periods.add_missing(periodos) + if gold.dates is not None and not _covers(gold.dates, desde, hasta): + gold.dates.replace_in_bulk(filas_de_dim_fecha(valores, hasta, proyecto=ctx.project)) + if gold.age_groups is not None and grupos is not None: + gold.age_groups.replace_all(grupos) return tipos -def _cubre(fechas, desde: date, hasta: date) -> bool: +def _covers(fechas, desde: date, hasta: date) -> bool: """`dim_fecha` ya es exactamente de `desde` a `hasta`: tiene los dos extremos y un día por fecha.""" return (fechas.get(desde) is not None and fechas.get(hasta) is not None and fechas.count() == (hasta - desde).days + 1) -def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]: +def definitions(migrate: str, ctx: Context) -> dict[str, int]: """The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest. It's synchronized: what a report's unit uses isn't deleted. """ - capas = catalog_layers(ctx.proyecto, _manifest(ctx)) - return {"definiciones": len(capas[0]), **ctx.repos.oro.publicacion.sincronizar(capas)} + capas = catalog_layers(ctx.project, _manifest(ctx)) + return {"definitions": len(capas[0]), **ctx.repos.gold.publication.sync(capas)} -def modelos(cargar: SQLModel, ctx: Contexto) -> int: +def event_models(load: SQLModel, ctx: Context) -> int: """The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base.""" - return len(ctx.repos.plata.vistas.construir(event_views(_manifest(ctx), ctx.proyecto))) + return len(ctx.repos.silver.views.build_all(event_views(_manifest(ctx), ctx.project))) -def _manifest(ctx: Contexto) -> Path: +def _manifest(ctx: Context) -> Path: if ctx.dbt_manifest is None: raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there") return ctx.dbt_manifest -def observar(cargar: SQLModel, registro: list[str], ctx: Contexto) -> int: +def observe(load: SQLModel, registry: list[str], ctx: Context) -> int: """`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente.""" - return ctx.repos.plata.observacion.observar(partial( - periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte, - permitir_sin_definir=ctx.permitir_sin_definir, + return ctx.repos.silver.observation.observar(partial( + periodos_de_observacion, proyecto=ctx.project, corte=ctx.cutoff, + permitir_sin_definir=ctx.allow_undecided, )) -def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], ctx: Contexto) -> dict[str, int]: +def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict[str, int]: """Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro.""" - conteos = ctx.repos.plata.vinculos.verificar(partial(calidad_de_la_plata, tablas=tablas_de(ctx.proyecto))) + conteos = ctx.repos.silver.links.check(partial(calidad_de_la_plata, tablas=tablas_de(ctx.project))) for nombre, n in conteos.items(): if n: - registro_de_eventos.warning("%s, plata de dos tablas: %d %s.", ctx.proyecto, n, nombre.replace("_", " ")) + log.warning("%s, plata de dos tablas: %d %s.", ctx.project, n, nombre.replace("_", " ")) return conteos -@config.when(con_cohortes=True) -def cohortes(modelos: int, ctx: Contexto) -> dict[str, tuple[int, bool]]: +@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 (`modelos` creates it), the same the models and the measures' strata read. + Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read. """ - tablas = tablas_de(ctx.proyecto) - tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES - inicio, fin = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1) + tablas = tablas_de(ctx.project) + tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES + inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1) def armado(definicion, sesion): - corte = ctx.corte or _fecha_de_ultima_carga(sesion, tablas) + corte = ctx.cutoff or _last_load_date(sesion, tablas) return armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, - linea=ctx.repos.plata.timeline.query) + linea=ctx.repos.silver.timeline.query) armados = {} - for ruta in definiciones_de_cohorte(ctx.proyecto): + for ruta in cohort_definitions(ctx.project): definicion = leer_definicion(ruta) - armados[definicion.url] = ctx.repos.oro.cohorte.armar(partial(armado, definicion)) + armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion)) return armados -@config.when(con_cohortes=True) -def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, tuple[int, bool]]: +@config.when(with_cohorts=True) +def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]: """El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008). Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador - (`ctx.estimadores[url]`: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como - un lote `preliminary` (`CohorteRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. + (`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como + un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden - `confirmar-riesgos`, no este paso. + `confirm-risks`, no este paso. """ - tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES + tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES lotes = {} - for ruta in definiciones_de_cohorte(ctx.proyecto): + for ruta in cohort_definitions(ctx.project): definicion = leer_definicion(ruta) - estimador = ctx.estimadores.get(definicion.url) + estimador = ctx.estimators.get(definicion.url) if estimador is None: continue @@ -211,17 +211,17 @@ def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, t return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion, cohortes=tablas_cohorte) - armado_id, ancho = ctx.repos.oro.cohorte.leer(marco) + armado_id, ancho = ctx.repos.gold.cohorts.read(marco) if armado_id is None: continue riesgos = [tuple(r) for r in estimador.estimar(*ancho)] - lotes[definicion.url] = ctx.repos.oro.cohorte.guardar_lote( + lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch( armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos ) return lotes -def _fecha_de_ultima_carga(sesion, tablas) -> date | None: +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): diff --git a/webapi/orquestacion/proyecto.py b/webapi/orchestration/project.py similarity index 86% rename from webapi/orquestacion/proyecto.py rename to webapi/orchestration/project.py index 5cab24e..8daf180 100644 --- a/webapi/orquestacion/proyecto.py +++ b/webapi/orchestration/project.py @@ -6,13 +6,13 @@ from pathlib import Path from indicadores_kit.oro.cohortes.definicion import RAIZ -def tipos_de_periodo(proyecto: str, manifest: Path) -> list[str]: +def period_types(proyecto: str, manifest: Path) -> list[str]: """The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest.""" metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", []) if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")}) -def definiciones_de_cohorte(proyecto: str) -> list[Path]: +def cohort_definitions(proyecto: str) -> list[Path]: """Los TOML de cohortes que el ciclo arma (`/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h).""" return sorted((RAIZ / proyecto / "cohortes").glob("*.toml")) diff --git a/webapi/orchestration/repositories.py b/webapi/orchestration/repositories.py new file mode 100644 index 0000000..8a1b7c7 --- /dev/null +++ b/webapi/orchestration/repositories.py @@ -0,0 +1,95 @@ +"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro. + +Las subclases viven en `persistance/edges//` y se +instancian en `persistance//__init__.py` con la fábrica de sesión del +dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión. +""" + +from dataclasses import dataclass +from importlib import import_module + +from persistance.edges.bronze import StagingRepository +from persistance.edges.gold import ( + CalculationRepository, + CohortRepository, + PublicationRepository, + ReferenceRepository, +) +from persistance.edges.silver import ( + LoadRepository, + CatalogRepository, + ObservationRepository, + TimelineRepository, + LinksRepository, + ViewsRepository, +) +from persistance.materializer import Materializer + + +@dataclass(frozen=True) +class Bronze: + """Lo que deja la ingesta. Solo se lee.""" + + staging: StagingRepository + + +@dataclass(frozen=True) +class Silver: + """Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata.""" + + catalogs: CatalogRepository + loads: LoadRepository + views: ViewsRepository + observation: ObservationRepository + links: LinksRepository + timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it + + +@dataclass(frozen=True) +class Gold: + """El registro (parámetros, periodos, definiciones), los reportes y las cohortes.""" + + parameters: ReferenceRepository + periods: ReferenceRepository + calculation: CalculationRepository + publication: PublicationRepository # el catálogo de publicación de §6f (T-19b) + cohorts: CohortRepository | None # donde hay tablas de cohortes (los tres desde MD-12) + dates: ReferenceRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27) + age_groups: ReferenceRepository | None = None # `dim_grupo_edad`, de `.grupos_edad` (I-MD27) + + +@dataclass(frozen=True) +class Repositories: + """Todo lo que un paso usa para tocar la base de su proyecto, por capa.""" + + bronze: Bronze + silver: Silver + gold: Gold + # Una sesión para leer y escribir en el mismo paso (`load`). + materializer: Materializer | None = None + + +def repositories_of(proyecto: str) -> Repositories: + dominio = import_module(f"persistance.{proyecto}") + return Repositories( + bronze=Bronze(staging=dominio.staging_repository), + silver=Silver( + catalogs=dominio.catalog_repository, + loads=dominio.carga_repository, + views=dominio.views_repository, + observation=dominio.observation_period_repository, + links=dominio.links_repository, + timeline=dominio.timeline_repository, + ), + materializer=dominio.materializer, + gold=Gold( + parameters=dominio.def_parametro_repository, + periods=dominio.dim_periodo_repository, + calculation=dominio.calculation_repository, + publication=dominio.publication_repository, + cohorts=getattr(dominio, "cohort_repository", None), + dates=getattr(dominio, "dim_fecha_repository", None), + age_groups=getattr(dominio, "dim_grupo_edad_repository", None), + ), + ) + diff --git a/webapi/orquestacion/ejecutor.py b/webapi/orchestration/runner.py similarity index 54% rename from webapi/orquestacion/ejecutor.py rename to webapi/orchestration/runner.py index 40a664f..fd3c19c 100644 --- a/webapi/orquestacion/ejecutor.py +++ b/webapi/orchestration/runner.py @@ -1,9 +1,9 @@ -"""Corre los pasos de un proyecto (`ciclo.py`) con Hamilton. +"""Corre los pasos de un proyecto (`cycle.py`) con Hamilton. Si un paso falla, los anteriores quedan hechos (cada operación de un repositorio es su propia transacción) y se puede volver a correr: los pasos no duplican. Si el contexto no trae repositorios, se le ponen los de Persistance -para el proyecto (`repositorios_de`). +para el proyecto (`repositories_of`). """ import logging @@ -16,28 +16,28 @@ from hamilton import driver from hamilton.execution.graph_functions import topologically_sort_nodes from hamilton.lifecycle import NodeExecutionHook -from webapi.orquestacion import ciclo -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.proyecto import definiciones_de_cohorte -from webapi.orquestacion.repositorios import repositorios_de +from webapi.orchestration import cycle +from webapi.orchestration.context import Context +from webapi.orchestration.project import cohort_definitions +from webapi.orchestration.repositories import repositories_of -registro = logging.getLogger(__name__) +log = logging.getLogger(__name__) @dataclass(frozen=True) -class Paso: +class Step: """Lo que dejó un paso: su resumen y cuánto tardó.""" - nombre: str - resumen: Any - segundos: float + name: str + summary: Any + seconds: float -class _Bitacora(NodeExecutionHook): +class _Logbook(NodeExecutionHook): """Anota cada paso que corre, en el orden en que corre.""" def __init__(self): - self.pasos: list[Paso] = [] + self.pasos: list[Step] = [] self._inicio = 0.0 def run_before_node_execution(self, **_): @@ -45,44 +45,44 @@ class _Bitacora(NodeExecutionHook): def run_after_node_execution(self, *, node_name: str, result: Any, success: bool, **_): if success: - self.pasos.append(Paso(node_name, result, time.monotonic() - self._inicio)) - registro.info("%s: %s en %.1f s", node_name, _corto(result), self.pasos[-1].segundos) + self.pasos.append(Step(node_name, result, time.monotonic() - self._inicio)) + log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds) def _driver(proyecto: str, *adaptadores) -> driver.Driver: return (driver.Builder() - .with_modules(ciclo) - .with_config({"con_cohortes": bool(definiciones_de_cohorte(proyecto))}) + .with_modules(cycle) + .with_config({"with_cohorts": bool(cohort_definitions(proyecto))}) .with_adapters(*adaptadores) .build()) -def _en_orden(dr: driver.Driver) -> list[str]: +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 pasos_de(proyecto: str) -> list[str]: - """Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, solo donde hay definiciones).""" - return _en_orden(_driver(proyecto)) +def steps_of(proyecto: str) -> 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)) -def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]: - """Corre el ciclo del proyecto en el orden de sus dependencias. `solo`: los pasos a correr; los demás no corren. +def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]: + """Corre el ciclo del proyecto en el orden de sus dependencias. `only`: los pasos a correr; los demás no corren. Los pasos que no corren se le dan a Hamilton ya resueltos. Así entre dos pedidos puede no quedar dependencia - (`cargar` y `calcular` sin `vistas`), por eso se le piden en el orden del grafo completo. + (`load` y `compute` sin `views`), por eso se le piden en el orden del grafo completo. """ if ctx.repos is None: - ctx = replace(ctx, repos=repositorios_de(ctx.proyecto)) - bitacora = _Bitacora() - dr = _driver(ctx.proyecto, bitacora) - todos = _en_orden(dr) - pedidos = [p for p in todos if solo is None or p in solo] + ctx = replace(ctx, repos=repositories_of(ctx.project)) + bitacora = _Logbook() + dr = _driver(ctx.project, 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}) return bitacora.pasos -def _corto(resumen: Any) -> str: +def _short(resumen: Any) -> str: if isinstance(resumen, dict): return f"{len(resumen)} elementos" return str(resumen) diff --git a/webapi/orquestacion/semantic_layer.py b/webapi/orchestration/semantic_layer.py similarity index 100% rename from webapi/orquestacion/semantic_layer.py rename to webapi/orchestration/semantic_layer.py diff --git a/webapi/orquestacion/__init__.py b/webapi/orquestacion/__init__.py deleted file mode 100644 index c365484..0000000 --- a/webapi/orquestacion/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -"""El ciclo de indicadores de cada proyecto (CaCu, CaMa, TEA): del staging que deja -la ingesta a los reportes que publica el tablero. Lo corre -[Hamilton](https://hamilton.apache.org/). - -Cada paso es una función de `ciclo.py`. Recibe el `Contexto` y, como parámetros, -los pasos que deben correr antes; Hamilton arma el grafo con esos nombres. Los -pasos no se pasan datos: todo va por la base, a través de los repositorios de -Persistance (`ctx.repos`), así que cada uno se puede correr solo. El cálculo es -del kit (`indicadores_kit`); aquí solo se decide qué se lee, a qué repositorio -se le pasa y en qué orden. - - migrar -> catalogos, registro, definiciones - catalogos -> cargar - cargar -> vistas, cohortes - vistas + registro + definiciones -> calcular - calcular -> observar, verificar_plata - cohortes -> estimar (solo donde hay cohortes: hoy, CaCu) - - uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026 - uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular - uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica" - -El servicio `indicadores` (`webapi.indicadores_vivos`) corre este mismo ciclo, -sin `migrar`, cada vez que una importación escribe datos. - -Módulo | Qué hace ----------------|--------- -`ciclo.py` | Los pasos -`ejecutor.py` | `correr(ctx, solo=...)`: arma el driver de Hamilton y corre los pasos pedidos en orden -`contexto.py` | El `Contexto`: proyecto, años, corte, parámetros y repositorios -`repositorios.py` | `repositorios_de(proyecto)`: los repositorios de Persistance, por capa -`proyecto.py` | Tipos de periodo y definiciones de cohorte de un proyecto -`conexion.py` | Apunta Persistance a otra base en el mismo proceso (pruebas) -""" - -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.ejecutor import Paso, correr, pasos_de - -__all__ = ["Contexto", "Paso", "correr", "pasos_de"] diff --git a/webapi/orquestacion/__main__.py b/webapi/orquestacion/__main__.py deleted file mode 100644 index f970967..0000000 --- a/webapi/orquestacion/__main__.py +++ /dev/null @@ -1,63 +0,0 @@ -"""La línea de comandos de la orquestación. - - uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026 [--corte 2026-01-01] [--permitir-sin-definir] - uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular - uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica" [--anular] - -La base es la de `_DATABASE_URL`, como en Persistance. -""" - -import argparse -import logging -from datetime import date -from pathlib import Path - -from webapi.orquestacion.contexto import Contexto -from webapi.orquestacion.ejecutor import correr - -PROYECTOS = ("cacu", "cama") - - -def main(argv: list[str] | None = None) -> None: - lector = argparse.ArgumentParser(prog="orquestacion", description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ordenes = lector.add_subparsers(dest="orden", required=True) - c = ordenes.add_parser("ciclo", help="corre los pasos del proyecto en orden") - c.add_argument("proyecto", choices=PROYECTOS) - c.add_argument("--desde", type=int, required=True, help="primer año de periodos") - c.add_argument("--hasta", type=int, required=True, help="último año de periodos") - c.add_argument("--corte", type=date.fromisoformat, default=None) - c.add_argument("--permitir-sin-definir", action="store_true") - c.add_argument("--parametros", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)") - c.add_argument("--solo", nargs="+", default=None, help="solo estos pasos") - r = ordenes.add_parser("confirmar-riesgos", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)") - r.add_argument("proyecto", choices=PROYECTOS) - r.add_argument("lote_id", type=int) - r.add_argument("--motivo", required=True, help="por qué se confirma o se anula; queda en cada evaluación") - r.add_argument("--anular", action="store_true", help="anular (entered-in-error) en vez de confirmar") - args = lector.parse_args(argv) - - if args.orden == "confirmar-riesgos": - cambiadas = confirmar_riesgos(args.proyecto, args.lote_id, args.motivo, anular=args.anular) - print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.anular else 'confirmadas'}") - return - logging.basicConfig(level=logging.INFO, format="%(message)s") - ctx = Contexto(args.proyecto, args.desde, args.hasta, args.corte, args.permitir_sin_definir, args.parametros) - for paso in correr(ctx, solo=args.solo): - print(f"{paso.nombre:20} {paso.segundos:6.1f} s") - - -def confirmar_riesgos(proyecto: str, lote_id: int, motivo: str, *, anular: bool = False) -> int: - """Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva. - - No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008). - """ - from persistance.aristas.oro import ERROR, FINAL - - from webapi.orquestacion.repositorios import repositorios_de - - return repositorios_de(proyecto).oro.cohorte.cambiar_estado(lote_id, ERROR if anular else FINAL, motivo) - - -if __name__ == "__main__": - main() diff --git a/webapi/orquestacion/repositorios.py b/webapi/orquestacion/repositorios.py deleted file mode 100644 index 68f87e6..0000000 --- a/webapi/orquestacion/repositorios.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro. - -Las subclases viven en `persistance/aristas//` y se -instancian en `persistance//__init__.py` con la fábrica de sesión del -dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión. -""" - -from dataclasses import dataclass -from importlib import import_module - -from persistance.aristas.bronce import StagingRepository -from persistance.aristas.oro import ( - CalculoRepository, - CohorteRepository, - PublicacionRepository, - RegistroRepository, -) -from persistance.aristas.plata import ( - CargaRepository, - CatalogoRepository, - ObservacionRepository, - TimelineRepository, - VinculosRepository, - VistasRepository, -) -from persistance.materializador import Materializador - - -@dataclass(frozen=True) -class Bronce: - """Lo que deja la ingesta. Solo se lee.""" - - staging: StagingRepository - - -@dataclass(frozen=True) -class Plata: - """Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata.""" - - catalogos: CatalogoRepository - carga: CargaRepository - vistas: VistasRepository - observacion: ObservacionRepository - vinculos: VinculosRepository - timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it - - -@dataclass(frozen=True) -class Oro: - """El registro (parámetros, periodos, definiciones), los reportes y las cohortes.""" - - parametros: RegistroRepository - periodos: RegistroRepository - calculo: CalculoRepository - publicacion: PublicacionRepository # el catálogo de publicación de §6f (T-19b) - cohorte: CohorteRepository | None # donde hay tablas de cohortes (los tres desde MD-12) - fechas: RegistroRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27) - grupos_edad: RegistroRepository | None = None # `dim_grupo_edad`, de `.grupos_edad` (I-MD27) - - -@dataclass(frozen=True) -class Repositorios: - """Todo lo que un paso usa para tocar la base de su proyecto, por capa.""" - - bronce: Bronce - plata: Plata - oro: Oro - # Una sesión para leer y escribir en el mismo paso (`cargar`). - materializador: Materializador | None = None - - -def repositorios_de(proyecto: str) -> Repositorios: - dominio = import_module(f"persistance.{proyecto}") - return Repositorios( - bronce=Bronce(staging=dominio.staging_repository), - plata=Plata( - catalogos=dominio.catalogo_repository, - carga=dominio.carga_repository, - vistas=dominio.vistas_repository, - observacion=dominio.observar_repository, - vinculos=dominio.vinculos_repository, - timeline=dominio.timeline_repository, - ), - materializador=dominio.materializador, - oro=Oro( - parametros=dominio.def_parametro_repository, - periodos=dominio.dim_periodo_repository, - calculo=dominio.calculo_repository, - publicacion=dominio.publicacion_repository, - cohorte=getattr(dominio, "cohorte_repository", None), - fechas=getattr(dominio, "dim_fecha_repository", None), - grupos_edad=getattr(dominio, "dim_grupo_edad_repository", None), - ), - ) - diff --git a/webapi/patient_risk.py b/webapi/patient_risk.py index 4aa4854..c276b19 100644 --- a/webapi/patient_risk.py +++ b/webapi/patient_risk.py @@ -24,8 +24,8 @@ def patient_risk_blueprint(repositories) -> Blueprint: """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.cohorte_repository.membership(pac_id, COHORT_URL) - risk = repositories.cohorte_repository.current_risk(pac_id) + 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 diff --git a/webapi/indicadores_vivos.py b/webapi/recomputation.py similarity index 71% rename from webapi/indicadores_vivos.py rename to webapi/recomputation.py index 0b38ccc..77f4b40 100644 --- a/webapi/indicadores_vivos.py +++ b/webapi/recomputation.py @@ -1,9 +1,9 @@ """Recomputes a domain's indicators after its staging tables change. -A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`), +A successful import asks for a recomputation (`RecomputationQueue.solicitar`), which only drops a marker file. A separate process (`python -m -webapi.indicadores_vivos`, the `indicadores` compose service) picks the -markers up and runs that domain's cycle (`webapi.orquestacion.correr`): catalogs -> +webapi.recomputation`, the `indicadores` compose service) picks the +markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs -> staging to facts -> views -> registry -> definitions -> reports. Requests that arrive while a domain is running are folded into one more run. @@ -26,7 +26,7 @@ from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message -DOMINIOS = ("cacu", "cama") # the domains whose measures the cycle computes +DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) @@ -41,7 +41,7 @@ def _short(value: Any) -> str: return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…" -class ColaDeRecalculo: +class RecomputationQueue: """Marker-file queue and status of the indicator recomputations.""" def __init__(self, base: Path | None = None): @@ -55,18 +55,18 @@ class ColaDeRecalculo: def _status_path(self) -> Path: return self.base / "estado.json" - def solicitar(self, dominio: str) -> None: - if dominio not in DOMINIOS: + def request_run(self, dominio: str) -> None: + if dominio not in DOMAINS: raise ValueError(f"dominio desconocido: {dominio!r}") self._pending.mkdir(parents=True, exist_ok=True) (self._pending / dominio).write_text(_now(), encoding="utf-8") - def pendientes(self) -> list[str]: + def pending(self) -> list[str]: if not self._pending.exists(): return [] - return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS) + return sorted(p.name for p in self._pending.iterdir() if p.name in DOMAINS) - def tomar(self, dominio: str) -> bool: + def take(self, dominio: str) -> bool: """Consumes the marker; a request made from now on queues one more run.""" try: (self._pending / dominio).unlink() @@ -74,15 +74,15 @@ class ColaDeRecalculo: except FileNotFoundError: return False - def estado(self) -> dict[str, Any]: + def status(self) -> dict[str, Any]: try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} - pending = set(self.pendientes()) - return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS} + pending = set(self.pending()) + return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMAINS} - def _guardar_estado(self, dominio: str, entrada: dict[str, Any]) -> None: + def _save_status(self, dominio: str, entrada: dict[str, Any]) -> None: self.base.mkdir(parents=True, exist_ok=True) lock = self.base / ".estado.lock" with open(lock, "w") as handle: @@ -96,58 +96,58 @@ class ColaDeRecalculo: tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8") tmp.replace(self._status_path) - def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: - """Runs the domain's graph (without `migrar`: the API migrates on startup).""" - from webapi.orquestacion import Contexto, correr, pasos_de + def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: + """Runs the domain's graph (without `migrate`: the API migrates on startup).""" + from webapi.orchestration import Context, run, steps_of desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5)) hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year)) inicio = _now() started = time.monotonic() - self._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) + self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: - ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True) - pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"]) + ctx = Context(dominio, desde, hasta, allow_undecided=True) + pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) entrada.update( estado="ok", - pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos], + pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos], ) except Exception as exc: # the worker must survive a failing domain log.exception("recálculo de %s falló", dominio) entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}) entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2)) - self._guardar_estado(dominio, entrada) + self._save_status(dominio, entrada) try: JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada}) except OSError: pass return entrada - def atender(self) -> list[str]: + def serve(self) -> list[str]: """Runs every pending domain once; returns the ones it ran.""" ran = [] - for dominio in self.pendientes(): - if self.tomar(dominio): - self.correr(dominio) + for dominio in self.pending(): + if self.take(dominio): + self.run(dominio) ran.append(dominio) return ran def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") - cola = ColaDeRecalculo() + cola = RecomputationQueue() interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1": - for dominio in DOMINIOS: - cola.solicitar(dominio) + for dominio in DOMAINS: + cola.request_run(dominio) stop = threading.Event() signal.signal(signal.SIGTERM, lambda *_: stop.set()) signal.signal(signal.SIGINT, lambda *_: stop.set()) log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base) while True: - for dominio in cola.atender(): - log.info("%s: %s", dominio, cola.estado()[dominio].get("estado")) + for dominio in cola.serve(): + log.info("%s: %s", dominio, cola.status()[dominio].get("estado")) if stop.wait(interval): break -- 2.53.0 From 4fc822d5c7d7b857760e8938a659ac7fd13b170f Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 10/24] The kit's silver load, reference tables, table maps and follow-up list move into the WebApi; the kit is no longer a dependency --- Dockerfile | 3 +- README.md | 5 +- pyproject.toml | 2 - tests/conftest.py | 4 +- tests/staging/__init__.py | 1 + tests/staging/cacu.py | 187 +++++ tests/staging/cama.py | 171 ++++ tests/test_metrics_on_request.py | 6 +- tests/test_orquestacion_ciclo.py | 2 +- tests/test_orquestacion_oro.py | 10 +- tests/test_orquestacion_plata.py | 10 +- tests/test_seguimiento.py | 2 +- uv.lock | 787 +----------------- webapi/__init__.py | 2 +- webapi/follow_up/__init__.py | 7 + webapi/follow_up/estratos.toml | 53 ++ webapi/follow_up/functions.py | 100 +++ webapi/follow_up/listing.py | 296 +++++++ webapi/follow_up/pivot.py | 110 +++ webapi/{follow_up.py => follow_up/routes.py} | 4 +- webapi/follow_up/silver.py | 99 +++ webapi/follow_up/status.py | 281 +++++++ webapi/follow_up/view.py | 26 + webapi/orchestration/cycle.py | 42 +- webapi/orchestration/project.py | 9 +- webapi/orchestration/reference/__init__.py | 0 webapi/orchestration/reference/age_groups.py | 61 ++ webapi/orchestration/reference/catalogs.py | 136 +++ webapi/orchestration/reference/dates.py | 35 + .../orchestration/reference/parametros.toml | 701 ++++++++++++++++ webapi/orchestration/reference/periods.py | 154 ++++ webapi/orchestration/reference/rules.py | 101 +++ webapi/orchestration/reference/support.py | 38 + webapi/orchestration/silver/__init__.py | 10 + webapi/orchestration/silver/cacu.py | 69 ++ webapi/orchestration/silver/cama.py | 46 + webapi/orchestration/silver/loads.py | 47 ++ .../silver/observation_periods.py | 97 +++ .../orchestration/silver/orders_and_notes.py | 73 ++ webapi/orchestration/silver/persons.py | 30 + webapi/orchestration/silver/procedures.py | 257 ++++++ webapi/orchestration/silver/quality.py | 43 + webapi/orchestration/silver/values.py | 44 + webapi/orchestration/silver/views.py | 72 ++ webapi/orchestration/tables/__init__.py | 87 ++ webapi/orchestration/tables/cacu.py | 77 ++ webapi/orchestration/tables/cama.py | 77 ++ 47 files changed, 3643 insertions(+), 831 deletions(-) create mode 100644 tests/staging/__init__.py create mode 100644 tests/staging/cacu.py create mode 100644 tests/staging/cama.py create mode 100644 webapi/follow_up/__init__.py create mode 100644 webapi/follow_up/estratos.toml create mode 100644 webapi/follow_up/functions.py create mode 100644 webapi/follow_up/listing.py create mode 100644 webapi/follow_up/pivot.py rename webapi/{follow_up.py => follow_up/routes.py} (93%) create mode 100644 webapi/follow_up/silver.py create mode 100644 webapi/follow_up/status.py create mode 100644 webapi/follow_up/view.py create mode 100644 webapi/orchestration/reference/__init__.py create mode 100644 webapi/orchestration/reference/age_groups.py create mode 100644 webapi/orchestration/reference/catalogs.py create mode 100644 webapi/orchestration/reference/dates.py create mode 100644 webapi/orchestration/reference/parametros.toml create mode 100644 webapi/orchestration/reference/periods.py create mode 100644 webapi/orchestration/reference/rules.py create mode 100644 webapi/orchestration/reference/support.py create mode 100644 webapi/orchestration/silver/__init__.py create mode 100644 webapi/orchestration/silver/cacu.py create mode 100644 webapi/orchestration/silver/cama.py create mode 100644 webapi/orchestration/silver/loads.py create mode 100644 webapi/orchestration/silver/observation_periods.py create mode 100644 webapi/orchestration/silver/orders_and_notes.py create mode 100644 webapi/orchestration/silver/persons.py create mode 100644 webapi/orchestration/silver/procedures.py create mode 100644 webapi/orchestration/silver/quality.py create mode 100644 webapi/orchestration/silver/values.py create mode 100644 webapi/orchestration/silver/views.py create mode 100644 webapi/orchestration/tables/__init__.py create mode 100644 webapi/orchestration/tables/cacu.py create mode 100644 webapi/orchestration/tables/cama.py diff --git a/Dockerfile b/Dockerfile index 9df8966..71d909d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build context is the repo root (see docker-compose.yml) so the sibling -# packages Core/, Persistance/, Extraction/, models/ and indicadores_kit/ +# packages Core/, Persistance/, Extraction/ and models/ # can be copied. FROM python:3.12-slim @@ -15,7 +15,6 @@ COPY Core/ Core/ COPY Persistance/ Persistance/ COPY Extraction/ Extraction/ COPY models/ models/ -COPY indicadores_kit/ indicadores_kit/ COPY WebApi/ WebApi/ # One environment for the API, the migrations and the indicator cycle. The SQL diff --git a/README.md b/README.md index dcc30cb..b241ab2 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ API REST de ISSSTELEON en Flask. Importa datos clínicos de varias fuentes a las bases de CaCu, CaMa y TEA, publica los indicadores ya calculados, guarda una bitácora agregada de cada importación y expone la gobernanza de modelos y de OCR. Usa `Persistance` para las bases, `Extraction` para documentos y -EEG, `indicadores_kit` para leer los indicadores y `orquestacion` para -recalcularlos. +EEG y `models` para las cohortes. Los indicadores se definen en dbt (`Transformation`) y se +responden bajo pedido (`//indicadores`); `orchestration` carga la plata, las tablas de +referencia y las vistas de dbt. ## Estructura diff --git a/pyproject.toml b/pyproject.toml index 34bd4b0..b501ebf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,6 @@ dependencies = [ "persistance", "models[notebooks]", "extraction", - "indicadores-kit", "apache-hamilton>=1.90", "pandas>=2.0", "openpyxl>=3.1", @@ -34,7 +33,6 @@ sql-drivers = [ persistance = { path = "../Persistance", editable = true } models = { path = "../models", editable = true } extraction = { path = "../Extraction", editable = true } -indicadores-kit = { path = "../indicadores_kit", editable = true } [build-system] requires = ["hatchling"] diff --git a/tests/conftest.py b/tests/conftest.py index 5dd6327..aeb86b2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,7 +19,7 @@ import pytest from sqlalchemy import create_engine from sqlmodel import Session -from indicadores_kit.registry.parametros import RUTA_PARAMETROS +from webapi.orchestration.reference.rules import RUTA_PARAMETROS from webapi.orchestration import Context, run from webapi.orchestration.connection import point_to from webapi.orchestration.repositories import repositories_of @@ -66,7 +66,7 @@ def base_de(proyecto: str, carpeta, datos=None) -> Base: run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: - (datos or import_module(f"indicadores_kit.{proyecto}.fixtures").insertar)(sesion) + (datos or import_module(f"staging.{proyecto}").insertar)(sesion) sesion.commit() return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor) diff --git a/tests/staging/__init__.py b/tests/staging/__init__.py new file mode 100644 index 0000000..ccb6a7a --- /dev/null +++ b/tests/staging/__init__.py @@ -0,0 +1 @@ +"""Synthetic staging rows for the tests, one module per domain: written by hand, never real data.""" diff --git a/tests/staging/cacu.py b/tests/staging/cacu.py new file mode 100644 index 0000000..e21430a --- /dev/null +++ b/tests/staging/cacu.py @@ -0,0 +1,187 @@ +"""Filas sintéticas del staging de CaCu, escritas a mano. Nunca datos reales. + +Seis pacientes y nueve citologías en dos semestres de 2025. Los textos de +calidad son provisionales: los valores reales están sin confirmar. + +Pacientes tamizadas: 4 en 2025-S1 y 4 en 2025-S2; de ellas, con muestra +insatisfactoria, 2 y 1. Lo que da cada indicador va abajo (`ESPERADO_*`). + +Casos que ejercita: H-003 tiene dos citologías en S1 y cuenta una vez; +H-004 tiene una el 1 de julio, que ya es S2; H-001 aparece en los dos +semestres. + +Resultados (v0.5.0, T-4): seis citologías tienen reporte y cuatro, VPH; +las dos insatisfactorias de H-002 y H-006 no tienen reporte, y la última +de H-001 todavía no. Tres biopsias, cada una con la citología que la +originó: dos reportadas y una pendiente. Los textos de resultado también +son provisionales. + +Cinco notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico +(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`). + +Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio. +""" + +from datetime import date + +from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente +from sqlmodel import Session, select + +SATISFACTORIO = "SATISFACTORIO" +INSATISFACTORIO = "INSATISFACTORIO" + +PACIENTES = ("H-001", "H-002", "H-003", "H-004", "H-005", "H-006") + +# (pac_id_hospital, fecha de toma, calidad del espécimen) +CITOLOGIAS = ( + ("H-001", date(2025, 2, 10), SATISFACTORIO), + ("H-002", date(2025, 3, 5), INSATISFACTORIO), + ("H-003", date(2025, 1, 20), INSATISFACTORIO), + ("H-003", date(2025, 4, 15), SATISFACTORIO), + ("H-004", date(2025, 5, 30), SATISFACTORIO), + ("H-004", date(2025, 7, 1), SATISFACTORIO), + ("H-005", date(2025, 8, 12), SATISFACTORIO), + ("H-006", date(2025, 9, 1), INSATISFACTORIO), + ("H-001", date(2025, 10, 2), SATISFACTORIO), +) + +# Índice en CITOLOGIAS -> (fecha de reporte, células escamosas, VPH, genotipo 16, genotipo 18). +RESULTADOS = { + 0: (date(2025, 2, 20), "NEGATIVO", None, None, None), + 2: (date(2025, 2, 1), "ASC-US", "POSITIVO", 1, 0), + 3: (date(2025, 4, 25), "LIEBG", "POSITIVO", 0, 0), + 4: (date(2025, 6, 9), "NEGATIVO", None, None, None), + 5: (date(2025, 7, 11), "LIEAG", "POSITIVO", 0, 1), + 6: (date(2025, 8, 22), "NEGATIVO", "NEGATIVO", None, None), +} + +# (índice de la citología que la originó, fecha de solicitud, fecha de reporte, grado CIN) +BIOPSIAS = ( + (3, date(2025, 5, 1), date(2025, 5, 20), "CIN1"), + (5, date(2025, 7, 15), date(2025, 8, 1), "CIN2"), + (6, date(2025, 9, 1), None, None), +) + +# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital). +COLPOSCOPIA, ONCOLOGIA, FAMILIAR = "CLINICA DE MUJER Y COLPOSCOPIA", "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR" +NOTAS = ( + ("H-004", date(2025, 8, 10), "D06.9", COLPOSCOPIA), # 72 días de su toma de mayo y 40 de la de julio + ("H-003", date(2024, 12, 1), "C53.9", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo + ("H-001", date(2025, 3, 1), "N87.1", FAMILIAR), # displasia, pero de medicina familiar: no resuelve + ("H-002", date(2025, 9, 15), "C53", ONCOLOGIA), # a 194 días de su toma: fuera del horizonte + ("H-005", date(2026, 1, 20), "c539", COLPOSCOPIA), # 161 días de su toma, pero después del corte de fin de año +) + +# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital). +# La segunda no es de tamizaje; la especialidad de la tercera no está en el catálogo de Core +# y queda sin reconocer; la cuarta está pedida y todavía no tiene citología. +ORDENES = ( + (50001, "H-001", date(2025, 2, 3), "MEDICINA FAMILIAR"), + (50002, "H-003", date(2025, 4, 10), "CLINICA DE MUJER Y COLPOSCOPIA"), + (50003, "H-004", date(2025, 6, 25), "Dermatología"), + (50004, "H-005", date(2025, 12, 1), "MEDICINA FAMILIAR"), +) + +# Índice en CITOLOGIAS -> número de su orden. Las demás citologías no traen número; la de +# H-005 trae uno que no existe entre las órdenes. +ORDEN_DE_CITOLOGIA = {0: 50001, 3: 50002, 5: 50003, 6: 59999} + +# periodo -> (denominador, numerador) de IND1, con la lista de `cacu.citologia_anomala` +# (ASC-US, ASC-H, LIEBG, LIEAG, CIS). En S1 solo H-003 (su ASC-US y su LIEBG; cuenta una +# vez); en S2 solo H-004 (su LIEAG del 1 de julio). +ESPERADO_IND1 = {"2025-S1": (4, 1), "2025-S2": (4, 1)} + +# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CACU_EU_TIEMPO_REPORTE, +# con horizonte de 60 días. Días de toma a resultado: S1 10, 12, 10, 10 (la toma del 5 de +# marzo no tiene resultado y a fin de año ya pasó el horizonte: cuenta en la inicial y no en +# n); S2 10, 10. A mediados de octubre las tomas de septiembre y octubre sin resultado siguen +# dentro del horizonte: no se miden. A mediados de agosto el resultado del 22 todavía no existe. +ESPERADO_CACU_TIEMPO = { + ("2025-S1", "2025-12-31"): (5, 4, 10.0, 10.0, 10.5), + ("2025-S2", "2025-12-31"): (4, 2, 10.0, 10.0, 10.0), + ("2025-S2", "2025-10-15"): (2, 2, 10.0, 10.0, 10.0), + ("2025-S2", "2025-08-15"): (1, 1, 10.0, 10.0, 10.0), +} + +# periodo -> (denominador, numerador) de CACU_EU13, con la lista de arranque de +# `cacu.deteccion_grados` (LIEAG, CIS, CARCINOMA). Los grados de las biopsias de +# este fixture (CIN1, CIN2) son textos provisionales que no están en esa lista: +# el numerador es cero. El distinto de cero se prueba con filas escritas a mano +# en `cacu/familias/eu13/casos.toml`. +ESPERADO_CACU_EU13 = {"2025-S1": (4, 0), "2025-S2": (4, 0)} + +# periodo -> {categoría: pacientes} de CACU_EU7 (solo las que tienen alguna). En S1, H-003 +# cuenta con el LIEBG de abril (su ASC-US de enero es de una muestra insatisfactoria y, +# además, anterior) y H-002 no tiene resultado; en S2, H-006 no tiene resultado y la de +# octubre de H-001 todavía no. «NEGATIVO» es un texto provisional de este fixture: no está +# en el catálogo (que usa NORMAL, como Core) y sale después de SIN_DATO. +ESPERADO_CACU_EU7 = { + "2025-S1": {"NEGATIVO": 2, "LIEBG": 1, "SIN_DATO": 1}, + "2025-S2": {"NEGATIVO": 1, "LIEAG": 1, "SIN_DATO": 2}, +} + + +def insertar(sesion: Session) -> None: + """Inserta pacientes, órdenes, citologías y biopsias. `pac_id` se resuelve por `pac_id_hospital`.""" + pacientes = { + hospital: Paciente( + pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1) + ) + for hospital in PACIENTES + } + sesion.add_all(pacientes.values()) + sesion.flush() + sesion.add_all( + OrdenesEstudio( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=numero, + ord_tipo_estudio="SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA", + ord_fecha=fecha, + ord_especialidad=especialidad, + ) + for numero, hospital, fecha, especialidad in ORDENES + ) + citologias = [] + for indice, (hospital, toma, calidad) in enumerate(CITOLOGIAS): + reporte, escamosas, vph, genotipo_16, genotipo_18 = RESULTADOS.get(indice, (None,) * 5) + citologias.append( + CitologiaCervical( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=ORDEN_DE_CITOLOGIA.get(indice), + cit_fecha_toma=toma, + cit_calidad_especimen=calidad, + cit_fecha_reporte=reporte, + cit_celulas_escamosas=escamosas, + cit_vph_resultado=vph, + cit_vph_genotipo_16=genotipo_16, + cit_vph_genotipo_18=genotipo_18, + ) + ) + sesion.add_all(citologias) + sesion.flush() + for indice, solicitud, reporte, grado in BIOPSIAS: + citologia = citologias[indice] + sesion.add( + BiopsiaCervical( + pac_id=citologia.pac_id, + pac_id_hospital=citologia.pac_id_hospital, + cit_id=citologia.cit_id, + bx_fecha_solicitud=solicitud, + bx_fecha_reporte=reporte, + bx_cin_grado=grado, + ) + ) + sesion.add_all( + NotaMedica( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + nm_id_hospital=f"NM-{numero:03d}", + nm_fecha=fecha, + nm_cie_codigo=cie, + nm_especialidad=especialidad, + ) + for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1) + ) + sesion.commit() diff --git a/tests/staging/cama.py b/tests/staging/cama.py new file mode 100644 index 0000000..1b56465 --- /dev/null +++ b/tests/staging/cama.py @@ -0,0 +1,171 @@ +"""Filas sintéticas del staging de CaMa, escritas a mano. Nunca datos reales. + +Seis pacientes y nueve mastografías en dos semestres de 2025. Los textos +de calidad son provisionales: los valores reales están sin confirmar. + +Mastografías: 5 en 2025-S1 y 4 en 2025-S2; de ellas, satisfactorias, 4 y 2. +Lo que da cada indicador va abajo (`ESPERADO_*`). + +Casos que ejercita: H-001 tiene dos mastografías en S1 y cuentan las dos; +una del 1 de julio ya es S2; una de S2 no tiene calidad y cuenta en el +denominador pero no en el numerador. + +Resultados (v0.5.0, T-4): cada mastografía trae su BI-RADS; tiene fecha +de reporte una semana después de la toma, salvo la que no tiene calidad +ni BI-RADS y la última, todavía sin reporte. + +Tres biopsias, cada una con la mastografía que la originó: dos con +reporte y grado, y una solicitada que todavía no lo tiene. + +Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico +(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`). + +H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`: +lo único común entre los dos sistemas es `pac_id_hospital`. + +Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio. +""" + +from datetime import date, timedelta + +from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente +from sqlmodel import Session, select + +SATISFACTORIO = "SATISFACTORIO" +INSATISFACTORIO = "INSATISFACTORIO" + +PACIENTES = ("H-101", "H-102", "H-001", "H-003", "H-103", "H-104") + +# (pac_id_hospital, fecha de toma, calidad de imagen, BI-RADS) +MASTOGRAFIAS = ( + ("H-101", date(2025, 1, 15), SATISFACTORIO, "B1"), + ("H-102", date(2025, 2, 20), SATISFACTORIO, "B2"), + ("H-001", date(2025, 3, 10), INSATISFACTORIO, "B0"), + ("H-001", date(2025, 4, 2), SATISFACTORIO, "B1"), + ("H-003", date(2025, 6, 30), SATISFACTORIO, "B4A"), + ("H-103", date(2025, 7, 1), SATISFACTORIO, "B1"), + ("H-103", date(2025, 9, 9), None, None), + ("H-104", date(2025, 11, 11), INSATISFACTORIO, "B0"), + ("H-102", date(2025, 12, 31), SATISFACTORIO, "B2"), +) + +# (índice de la mastografía que la originó, fecha de solicitud, fecha de reporte, grado histológico) +BIOPSIAS = ( + (2, date(2025, 3, 20), date(2025, 4, 5), "BENIGNO"), + (4, date(2025, 7, 10), date(2025, 7, 28), "CARCINOMA_INVASOR"), + (7, date(2025, 11, 20), None, None), +) + +# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital). +# La de H-003 llega con minúscula y punto; la de H-104 no tiene fecha y la de H-101 es de +# medicina familiar, que no resuelve la toma. +ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR" +NOTAS = ( + ("H-003", date(2025, 8, 4), "c50.4", ONCOLOGIA), # 35 días de su B4A del 30 de junio + ("H-001", date(2025, 3, 1), "D05.1", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo + ("H-102", date(2025, 9, 30), "C50.9", ONCOLOGIA), # a 222 días de su toma de febrero: fuera del horizonte + ("H-103", date(2025, 7, 20), "C50.9", ONCOLOGIA), # 19 días de su toma del 1 de julio + ("H-101", date(2025, 1, 15), "Z12.3", FAMILIAR), # normal, pero de medicina familiar: no resuelve + ("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta +) + +# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital). +# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía. +ORDENES = ( + (60001, "H-101", date(2025, 1, 10), "MEDICINA FAMILIAR"), + (60002, "H-003", date(2025, 6, 20), "CIRUGIA ONCOLOGICA"), + (60003, "H-104", date(2025, 12, 5), "MEDICINA FAMILIAR"), +) + +# Índice en MASTOGRAFIAS -> número de su orden. Las demás no traen número; la de H-102 trae +# uno que no existe entre las órdenes. +ORDEN_DE_MASTOGRAFIA = {0: 60001, 4: 60002, 1: 69999} + +# periodo -> {categoría: pacientes} de CAMA_BIRADS (solo las que tienen alguna). +# H-001 tiene B0 y B1 en S1: cuenta en B0, la más grave. H-103 tiene B1 y una toma sin +# reporte: cuenta en B1. H-102 tiene en S2 solo una toma sin reporte: SIN_DATO. +ESPERADO_CAMA_BIRADS = { + "2025-S1": {"B0": 1, "B1": 1, "B2": 1, "B4A": 1}, + "2025-S2": {"B0": 1, "B1": 1, "SIN_DATO": 1}, +} + +# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CAMA_EU38A, con +# horizonte de 60 días. Todo reporte llega siete días después de la toma. A fin de año la +# toma del 9 de septiembre ya pasó el horizonte sin reporte (cuenta en la inicial y no en n) +# y la del 31 de diciembre sigue en observación. El 15 de septiembre ninguna toma de S2 +# posterior a julio tiene reporte ni ha vencido: solo se mide la del 1 de julio. +ESPERADO_CAMA_EU38A = { + ("2025-S1", "2025-12-31"): (5, 5, 7.0, 7.0, 7.0), + ("2025-S2", "2025-12-31"): (3, 2, 7.0, 7.0, 7.0), + ("2025-S2", "2025-09-15"): (1, 1, 7.0, 7.0, 7.0), +} + +# periodo -> (denominador, numerador) de CAMA_CONFIRMACION_BIRADS45, con la lista de arranque de +# `cama.birads_sospecha` (B4 con o sin subcategoría, B5). La única mastografía de sospecha es la B4A de H-003 del 30 de +# junio, y su biopsia se reportó el 28 de julio: cuenta en S1, el semestre de la mastografía. +# Las otras dos biopsias salen de mastografías B0, que no están en la lista. En S2 no hay +# ninguna de sospecha: sin denominador, el reporte sale suprimido y no se compara. +ESPERADO_CAMA_CONFIRMACION_BIRADS45 = {"2025-S1": (1, 1)} + + +def insertar(sesion: Session) -> None: + """Inserta pacientes, órdenes, mastografías, biopsias y notas. `pac_id` se resuelve por `pac_id_hospital`.""" + pacientes = { + hospital: Paciente( + pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1975, 1, 1) + ) + for hospital in PACIENTES + } + sesion.add_all(pacientes.values()) + sesion.flush() + sesion.add_all( + OrdenesEstudio( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=numero, + ord_tipo_estudio="MASTOGRAFIA", + ord_fecha=fecha, + ord_especialidad=especialidad, + ) + for numero, hospital, fecha, especialidad in ORDENES + ) + mastografias = [] + for indice, (hospital, toma, calidad, birads) in enumerate(MASTOGRAFIAS): + sin_reporte = birads is None or indice == len(MASTOGRAFIAS) - 1 + mastografias.append( + Mastografia( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + ord_numero_hospital=ORDEN_DE_MASTOGRAFIA.get(indice), + mast_fecha_toma=toma, + mast_calidad_imagen=calidad, + mast_birads=birads, + mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7), + ) + ) + sesion.add_all(mastografias) + sesion.flush() + for indice, solicitud, reporte, grado in BIOPSIAS: + mastografia = mastografias[indice] + sesion.add( + BiopsiaMama( + pac_id=mastografia.pac_id, + pac_id_hospital=mastografia.pac_id_hospital, + mast_id=mastografia.mast_id, + bx_fecha_solicitud=solicitud, + bx_fecha_reporte=reporte, + bx_grado_histologico=grado, + ) + ) + sesion.add_all( + NotaMedica( + pac_id=pacientes[hospital].pac_id, + pac_id_hospital=hospital, + nm_id_hospital=f"NM-{numero:03d}", + nm_fecha=fecha, + nm_cie_codigo=cie, + nm_especialidad=especialidad, + ) + for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1) + ) + sesion.commit() diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py index ea6f3e0..ee03ccc 100644 --- a/tests/test_metrics_on_request.py +++ b/tests/test_metrics_on_request.py @@ -330,9 +330,9 @@ def kit_status(base, reference: str) -> dict[str, str]: """What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules.""" import tomllib - from indicadores_kit.cacu.seguimiento import estatus_al, reglas_de - from indicadores_kit.registry.parametros import RUTA_PARAMETROS - from indicadores_kit.serving.seguimiento import leer_estrato + from webapi.follow_up.status import estatus_al, reglas_de + from webapi.orchestration.reference.rules import RUTA_PARAMETROS + from webapi.follow_up.listing import leer_estrato from sqlalchemy import bindparam rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8")) diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 8ec5f4a..63cde16 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -39,7 +39,7 @@ def bases(request, tmp_path_factory): run(ctx, only=["migrate"]) motor = create_engine(url) with Session(motor) as sesion: - import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion) + import_module(f"staging.{proyecto}").insertar(sesion) sesion.commit() pasos = run(ctx) return proyecto, ctx, motor, None, pasos diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 7bfe6ab..9da68bd 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -8,11 +8,11 @@ from datetime import date import pytest -from indicadores_kit.plata.carga import tablas_de_staging -from indicadores_kit.registry.edades import grupos_de_cortes -from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo -from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.tablas import tablas_de +from webapi.orchestration.silver.loads import tablas_de_staging +from webapi.orchestration.reference.age_groups import grupos_de_cortes +from webapi.orchestration.reference.rules import RUTA_PARAMETROS, valores_del_archivo +from webapi.orchestration.reference.periods import periodos_de_tipos +from webapi.orchestration.tables import tablas_de from webapi.orchestration.project import period_types from conftest import ANIO diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 96d743b..57d5940 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -10,15 +10,15 @@ from datetime import date import pytest from conftest import base_de -from indicadores_kit.plata.carga import tablas_de_staging -from indicadores_kit.plata.periodo_observacion import ( +from webapi.orchestration.silver.loads import tablas_de_staging +from webapi.orchestration.silver.observation_periods import ( TIPO_EXTRACCION, ObservacionSinCorte, clave_de_inicio, ) -from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.registry.parametros import RUTA_PARAMETROS, ParametroSinDefinir -from indicadores_kit.tablas import tablas_de +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.reference.rules import RUTA_PARAMETROS, ParametroSinDefinir +from webapi.orchestration.tables import tablas_de from sqlalchemy import inspect, text from sqlmodel import select diff --git a/tests/test_seguimiento.py b/tests/test_seguimiento.py index 110ca6e..016237a 100644 --- a/tests/test_seguimiento.py +++ b/tests/test_seguimiento.py @@ -62,7 +62,7 @@ def test_una_pagina_de_mas_da_404(client): def test_in_dev_esta_obsoleta(): """Fija: `in_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso.""" - from webapi.follow_up import in_dev + from webapi.follow_up.routes import in_dev with pytest.warns(DeprecationWarning): in_dev() diff --git a/uv.lock b/uv.lock index 932d80a..64d1d40 100644 --- a/uv.lock +++ b/uv.lock @@ -1,15 +1,15 @@ version = 1 -revision = 2 +revision = 3 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version < '3.13' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version < '3.13' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.13' and sys_platform == 'win32'", + "python_full_version < '3.13' and sys_platform == 'emscripten'", "python_full_version < '3.13' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] @@ -236,24 +236,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fe/ec/c672e72dd66b633fb65e6011bc7c30c128e090364f8497660b7869e10123/apache_hamilton-1.90.0-py3-none-any.whl", hash = "sha256:95e356f7cb23e1a10d44fd0cf5efd3fb36a077b4ccb673950c92005bfdec2ff7", size = 475199, upload-time = "2026-04-25T18:45:17.514Z" }, ] -[[package]] -name = "appnope" -version = "1.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/11/f7/a82489c2b6ebe32d3e2831895ae19c77861f0eadf3bb16034484d965dbb2/appnope-1.0.0.tar.gz", hash = "sha256:685db59cb6043c3c2e528adc0b3bce3a5f8d09bcf7492c6ea650d1b7421f3c49", size = 5454, upload-time = "2026-08-20T21:36:13.748Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/46/c7/6b687cb0f83d2a51017d47953f2ee430ffad6fec2a8ebc964e0718a33eb1/appnope-1.0.0-py3-none-any.whl", hash = "sha256:6fe0c04218aab65c54c4ff81638cdbf848d89f5653b74d68638a137f200dd16e", size = 4158, upload-time = "2026-08-20T21:36:12.444Z" }, -] - -[[package]] -name = "asttokens" -version = "3.0.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" }, -] - [[package]] name = "attrs" version = "26.1.0" @@ -263,36 +245,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] -[[package]] -name = "beautifulsoup4" -version = "4.15.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "soupsieve" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/88/c6/92fcd42f1ba33e1184263f25bfabf3d27c383410470f169e4b8163bf9c17/beautifulsoup4-4.15.0-py3-none-any.whl", hash = "sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9", size = 109924, upload-time = "2026-06-07T16:44:21.566Z" }, -] - -[[package]] -name = "bleach" -version = "6.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "webencodings" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/48/3c/e12ac860709702bd5ebeb9b56a4fe334f1001246ee1b8f2b7ee28912df7d/bleach-6.4.0.tar.gz", hash = "sha256:4202482733d85cedd04e59fcb2f89f4e4c7c385a78d3c3c23c30446843a37452", size = 204857, upload-time = "2026-06-05T13:01:13.734Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/9d/40b6267367182187139a4000b82a3b287d84d745bccd808e75d916920e9d/bleach-6.4.0-py3-none-any.whl", hash = "sha256:4b6b6a54fff2e69a3dde9d21cc6301220bee3c3cb792187d11403fd795031081", size = 165109, upload-time = "2026-06-05T13:01:12.504Z" }, -] - -[package.optional-dependencies] -css = [ - { name = "tinycss2" }, -] - [[package]] name = "blinker" version = "1.9.0" @@ -563,15 +515,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] -[[package]] -name = "comm" -version = "0.2.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/4c/13/7d740c5849255756bc17888787313b61fd38a0a8304fc4f073dfc46122aa/comm-0.2.3.tar.gz", hash = "sha256:2dc8048c10962d55d7ad693be1e7045d891b7ce8d999c97963a5e3e99c055971", size = 6319, upload-time = "2025-07-25T14:02:04.452Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" }, -] - [[package]] name = "contourpy" version = "1.4.0" @@ -745,31 +688,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/c1/631160994379b7baa4605c2a4ffa6bca374b3ef73213e43b2dfcbd6c2bb9/databricks_sdk-0.156.0-py3-none-any.whl", hash = "sha256:1aa5e0cabfc5626a886c9fa42bc1ce14a6166e8167ef34026dcc41f3c99e2a5a", size = 1112276, upload-time = "2026-10-22T04:33:33.024Z" }, ] -[[package]] -name = "debugpy" -version = "1.8.22" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/44/9d/3cb6693342acf96802dba89934a5b8da43c201d764ebd1f2c0514a3d42bd/debugpy-1.8.22.tar.gz", hash = "sha256:e489c7268e1c7b41e13b438d9c533d2a7af73fb59bf8cd30fead8286c1c39c4e", size = 1710877, upload-time = "2026-09-15T21:44:02.578Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/73/21/5c7f5c66eaeee57c9dadb0bbff22efddc8d99cdbd3d036c806175f1828cc/debugpy-1.8.22-cp312-cp312-macosx_15_0_universal2.whl", hash = "sha256:4ad076f4f66cb8acb79e4384d48b1ea60a0b1957aa0b1112d4887ea3a4df60e0", size = 2499375, upload-time = "2026-09-15T21:44:18.478Z" }, - { url = "https://files.pythonhosted.org/packages/7e/ec/7389798843643ea5bc6a08480ba1b855377c70e2ed90189c0a03594e401e/debugpy-1.8.22-cp312-cp312-manylinux_2_34_x86_64.whl", hash = "sha256:8a697acec45dbc70d17fb5d9f4f61989fc294d273c69de487fd10cb35fdd75eb", size = 4000941, upload-time = "2026-09-15T21:44:20.245Z" }, - { url = "https://files.pythonhosted.org/packages/20/f4/64ce7a2499550929e08654360b270409eeda3e321b7c27027d9c919aa36b/debugpy-1.8.22-cp312-cp312-win32.whl", hash = "sha256:12bc7f368182b517cf26c76a2393fff65354e365fa1552b6241e66edff17997b", size = 5359040, upload-time = "2026-09-15T21:44:22.218Z" }, - { url = "https://files.pythonhosted.org/packages/4b/fe/e7d3b72874cdd327bda295d1995a01e426857ae9cbaaba74fd997bc3afbc/debugpy-1.8.22-cp312-cp312-win_amd64.whl", hash = "sha256:371a4ba4a5975eb958393903f3254cf983da7b1c7c178b3f987ee427f42515e3", size = 5398304, upload-time = "2026-09-15T21:44:24.119Z" }, - { url = "https://files.pythonhosted.org/packages/6b/f4/fee6d40f5865aa84e1100c9df1a0f2cf8991776b61f11f433ff277df4415/debugpy-1.8.22-cp313-cp313-macosx_15_0_universal2.whl", hash = "sha256:c21dd7e1ec22556bb41dc3bf6b86c603e440ec889c4acb27d7206354b2106c54", size = 2493531, upload-time = "2026-09-15T21:44:25.835Z" }, - { url = "https://files.pythonhosted.org/packages/bc/4f/8df91270afbf61fc5ab202951f28451194a7eb093704b26da11cb0ecd308/debugpy-1.8.22-cp313-cp313-manylinux_2_34_x86_64.whl", hash = "sha256:c1ffb9953708b648ecf6acd2e5ad2c002bf68785ed618197dd4463a2a7226f39", size = 3994351, upload-time = "2026-09-15T21:44:27.31Z" }, - { url = "https://files.pythonhosted.org/packages/4f/11/2e34a4f21d6155b0c58003fd6fca9819df7d6fe7d7acd83b146b648a57ee/debugpy-1.8.22-cp313-cp313-win32.whl", hash = "sha256:ba810a66b437e3c43ca0ce0892404f010338286263ca8e5108442d76a9485337", size = 5359071, upload-time = "2026-09-15T21:44:29.064Z" }, - { url = "https://files.pythonhosted.org/packages/d0/f5/c2b3e8260388d7b76bc4e5a3a29648a0ca47dca6a2721d6549ff2d944eee/debugpy-1.8.22-cp313-cp313-win_amd64.whl", hash = "sha256:f49b1d6cecf326b63c06d7f517e4a6642777f758c58cb799e7bc5a6dd74721c2", size = 5400362, upload-time = "2026-09-15T21:44:30.857Z" }, - { url = "https://files.pythonhosted.org/packages/ea/95/d97240bb68b86db8d0a07602be068aae9e50f17063d696a4c6f619975311/debugpy-1.8.22-cp314-cp314-macosx_15_0_universal2.whl", hash = "sha256:e6744ac1850c73c2ba7b29a126cf9ab74efd1831190720e8fee17ef5389c8f5d", size = 2493148, upload-time = "2026-09-15T21:44:32.518Z" }, - { url = "https://files.pythonhosted.org/packages/70/9e/994fe1fb23dd4a5a8d059a0dc95da4b0821907200a61c2d5a4fdc21b6cf8/debugpy-1.8.22-cp314-cp314-manylinux_2_34_x86_64.whl", hash = "sha256:0c1104233340196e5cbf5514e7dfdbb98968e730cfd7fdd6f3d72a082be838a9", size = 3961025, upload-time = "2026-09-15T21:44:34.387Z" }, - { url = "https://files.pythonhosted.org/packages/37/e0/66319918883cf6dd6dea3805210c3cafd9e65dfaa6f8b852482cff10a026/debugpy-1.8.22-cp314-cp314-win32.whl", hash = "sha256:feea785c7bbeb8cfd5b01a63f9061c899dc468c8be81671141a29305774fa294", size = 5359408, upload-time = "2026-09-15T21:44:36.128Z" }, - { url = "https://files.pythonhosted.org/packages/94/53/5b4d91f7fffb9393ac907133201d1da0c070d57e463ee8e2ec1db3cb63b6/debugpy-1.8.22-cp314-cp314-win_amd64.whl", hash = "sha256:d593a330297332ec435f3965c448b6d500e03f33675cf2063178bc76377a788e", size = 5397429, upload-time = "2026-09-15T21:44:38.429Z" }, - { url = "https://files.pythonhosted.org/packages/24/71/580df4aed96c9b23c9cbb049907d8ac1347050afdb8f450df20649d51578/debugpy-1.8.22-cp315-cp315-macosx_15_0_universal2.whl", hash = "sha256:a9eca6ab09a61534e923064400081e016f7e1d8430cc6e8b7a9cecd2f59e2b07", size = 2493380, upload-time = "2026-09-15T21:44:40.074Z" }, - { url = "https://files.pythonhosted.org/packages/b0/10/a323945b0966e560c40fe48470d2847bfc7692a8f550d7086e9a28f5b623/debugpy-1.8.22-cp315-cp315-manylinux_2_34_x86_64.whl", hash = "sha256:b7dbde1fb822d100802d505b2aed6d0813b1a0a2015d495cb8798b2215d5d1e5", size = 3975456, upload-time = "2026-09-15T21:44:41.623Z" }, - { url = "https://files.pythonhosted.org/packages/ef/f9/4383635281999c3eaa44bf327de523ba42240b35eb87c1130adac4a829c6/debugpy-1.8.22-cp315-cp315-win32.whl", hash = "sha256:225d063f81708c2546999e7edfac0198b2d5c2f144797dc64858f867948633e0", size = 5359469, upload-time = "2026-09-15T21:44:43.234Z" }, - { url = "https://files.pythonhosted.org/packages/7b/14/4fe9f46a9c825c8cbc6dc4aebc2a885b0bceb37ce2a37699c170482e7a40/debugpy-1.8.22-cp315-cp315-win_amd64.whl", hash = "sha256:b17a4896520f1c6da09ce76ec8215df0b85b0b6f3617526a4c65c2315340875a", size = 5397869, upload-time = "2026-09-15T21:44:44.783Z" }, - { url = "https://files.pythonhosted.org/packages/56/3d/c7dc9f35bc9e22cdb53679f844bee40fd5cff871862f60595869a433400d/debugpy-1.8.22-py2.py3-none-any.whl", hash = "sha256:a9e9d3550e15ca479c59333e90845029190531f0cacfedab3b815a57bd913947", size = 5374857, upload-time = "2026-09-15T21:44:54.454Z" }, -] - [[package]] name = "decorator" version = "5.3.1" @@ -779,15 +697,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/05/7f/798705f5296a58ca505d600456748d1be48078eac8a7050d8a98bc9edb89/decorator-5.3.1-py3-none-any.whl", hash = "sha256:f47fe6fdbd2edd623ecfe36875d37aba411624e2670dd395dddae1358689bb3c", size = 10365, upload-time = "2026-05-18T06:03:26.517Z" }, ] -[[package]] -name = "defusedxml" -version = "0.7.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" }, -] - [[package]] name = "docker" version = "7.2.0" @@ -811,15 +720,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" }, ] -[[package]] -name = "executing" -version = "2.3.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/52/92/8a611141e42930c0f194f7504063ab87dfe970cf1a5af28e7703df448734/executing-2.3.0.tar.gz", hash = "sha256:15919cb5d667e5cb4e099511971d00d659573fff2dd5c4e6cd8b71636c7858d2", size = 1338003, upload-time = "2026-10-10T14:06:04.64Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4d/dd/8bc67e7d5ffc1d88aa5af511189dfb76dc4e1e5b808fab186146ef2663e5/executing-2.3.0-py3-none-any.whl", hash = "sha256:736e859c9f8701f11fcf516856f26f562e04776387824b43a35a1dfe21c84122", size = 29393, upload-time = "2026-10-10T14:06:02.777Z" }, -] - [[package]] name = "extraction" version = "0.1.0" @@ -868,15 +768,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/2a/101012d82931d9de3855384e1667e49c0e07a0048e3868f9fec1697293a9/fastapi-0.161.1-py3-none-any.whl", hash = "sha256:a1363080cf9aeedecd99f4e1a23669d7e77542227f6536f4d7bbd59f07ecaa94", size = 149049, upload-time = "2026-10-22T22:22:06.139Z" }, ] -[[package]] -name = "fastjsonschema" -version = "2.22.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1c/80/cc3c531dd70c8ffa1045aecf33c97c5581cc8fd0e824b3ecb2c1881550c1/fastjsonschema-2.22.3.tar.gz", hash = "sha256:8330c91b027dcf941efcb7b1f0998515ff95d177ea15bbabdfe8671965620901", size = 388854, upload-time = "2026-11-01T21:11:34.389Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d7/0d/6caab33488dc9d26440c24221fa610c7c8b83c30715ab45d31f0e004308e/fastjsonschema-2.22.3-py3-none-any.whl", hash = "sha256:f670b443830b75aca3f00b75949efa20f4b2a80302ec7a21505c28dd54cffd43", size = 28442, upload-time = "2026-11-01T21:11:29.306Z" }, -] - [[package]] name = "flask" version = "3.1.3" @@ -1135,9 +1026,7 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/72/18/3fc6d951466ae9a2a688edcddde3b2e388da0a8244e0caf7117bbeb0eb95/greenlet-3.5.6-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:a5876d0a60355af98d535c47f6cd6eb0f8a432396dab26845d380b92f8412422", size = 295668, upload-time = "2026-09-14T14:22:33.241Z" }, { url = "https://files.pythonhosted.org/packages/27/89/366d2af5061eeefa5012f510d95a99c8620dcc457609838db4d538820318/greenlet-3.5.6-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e85880b538e59a59f55117b81f208a6660ad5ac328aad9305f812d9b8bc67a0f", size = 611700, upload-time = "2026-09-14T15:12:01.962Z" }, { url = "https://files.pythonhosted.org/packages/54/1c/07f133f865fd58ae593dd2bbec3144acaee9b04ffe2eb48c6e121747ceef/greenlet-3.5.6-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f0ba7c2a329d650628f4c8572fd1db29f0a59dd70a3e3e0710dcf18a35cce9d8", size = 624223, upload-time = "2026-09-14T15:20:42.459Z" }, - { url = "https://files.pythonhosted.org/packages/a7/f2/844dc823ff2752ad049caa6b59d57e4572f9c445934b02d3518f4c67197c/greenlet-3.5.6-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee7d9da3bf493909cf811a3f038840cb34fab5ae2956b8a263919f6e289ab188", size = 629529, upload-time = "2026-09-14T15:25:06.354Z" }, { url = "https://files.pythonhosted.org/packages/66/6a/1594f3869c57c149abdb380492529e04d4c0229b5e4d79572c5bd0aaa673/greenlet-3.5.6-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:975736b002ed080d124cf81a79cb7e05cb26d6b3f5c7a7b651c0fcce70353aa1", size = 621404, upload-time = "2026-09-14T14:35:59.027Z" }, - { url = "https://files.pythonhosted.org/packages/c0/42/b1f8dbc89a53b9e77859fc1ad1627d106fc361daa3ea4bdf43a91ebb4338/greenlet-3.5.6-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:71890d5247020c25c21a6b65202782bfc281d4e6e244842419d30e3492bb6dcc", size = 432385, upload-time = "2026-09-14T15:28:37.369Z" }, { url = "https://files.pythonhosted.org/packages/a2/f5/33e5c9e48178b9259fd000f8f45caa4a65036f65d3d0c06a602f570f025d/greenlet-3.5.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0616b8f878098c5681fd8f0dc92d887551717402342a70f0abcbfea5f5ad8a44", size = 1584998, upload-time = "2026-09-14T15:10:06.653Z" }, { url = "https://files.pythonhosted.org/packages/ef/31/9b4e140bc24d0ad7927ebd651f5608b0acc2334d061748c3b6ad19085cfa/greenlet-3.5.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3dbb4596a6a4e5d47121a33ff20533a81e60f302d9e67b69909a8bc21a43f0a7", size = 1647568, upload-time = "2026-09-14T14:35:49.787Z" }, { url = "https://files.pythonhosted.org/packages/c3/71/d79f1791f824f8ff15c2978746640467ae932a2365e0201069f7f272395f/greenlet-3.5.6-cp312-cp312-win_amd64.whl", hash = "sha256:7ac4abb3877c43af320392c664774eef6fa2cc063c79a55fc02d844a3cbe7395", size = 324203, upload-time = "2026-09-14T14:22:54.504Z" }, @@ -1145,9 +1034,7 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/a1/e720a38852366c589e1a46cf570b886507ad2cf591050c203365638baab0/greenlet-3.5.6-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:f96f0e30b5a95c7631b12bfe214cbc90ec8fe8cfa36920596c10514a65743519", size = 294627, upload-time = "2026-09-14T14:24:40.102Z" }, { url = "https://files.pythonhosted.org/packages/eb/c3/58187858df41354a11e6a55b421e7af9059798abdab3a384cc51b8567c38/greenlet-3.5.6-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c75116c9de79949de23006e2d9b35ee82874c594fcf5c0311b439acaa14b8441", size = 614356, upload-time = "2026-09-14T15:12:03.399Z" }, { url = "https://files.pythonhosted.org/packages/ce/b9/3a7e67d5f05c9760b1ad411fa52264bd69cc08e22a2ebfb4018b90628ced/greenlet-3.5.6-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cad5782f93f7f738b62c6527b6f32a60694d924029f299a8b524758cfa53d815", size = 626756, upload-time = "2026-09-14T15:20:44.269Z" }, - { url = "https://files.pythonhosted.org/packages/c6/7c/40400455f5b5a65bb83e94fde66d1be9e5ec518638113f8083ace746c309/greenlet-3.5.6-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a93ee7c6e8fd0f8a83525a51bd777be57ee17787e91d805bd8d6faf9dcada18e", size = 632632, upload-time = "2026-09-14T15:25:07.813Z" }, { url = "https://files.pythonhosted.org/packages/85/cb/ab0c123c514ed4e94c0dc9ee2e86362633e6b998cfc05de7fc9ac2eb9690/greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f98e8215e172f567ce80eeaed9107fb4d32b6c44f26983d9b8334658136a205a", size = 623779, upload-time = "2026-09-14T14:36:01.104Z" }, - { url = "https://files.pythonhosted.org/packages/f9/67/1f35cff30a6c51c3f23b63d4afcc7313ab4f97490ba3676fa78178984b27/greenlet-3.5.6-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:7f731ebac68ea06d628658295cb2d217b10186329fcf9a3b6a149045059bf92e", size = 434933, upload-time = "2026-09-14T15:28:38.858Z" }, { url = "https://files.pythonhosted.org/packages/a5/26/fda8a5a06e7073333ccb038133c5893b9e0c4fe29d5992a17e83c241bc6e/greenlet-3.5.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df19e2d0b1620039af5102563fbd96e8938c7f5c3f5828528d641d9fc585525e", size = 1584930, upload-time = "2026-09-14T15:10:08.234Z" }, { url = "https://files.pythonhosted.org/packages/2f/37/50f8813163148d6234e08b23dcad6a9e37f01d148c8ec976e4c44ea2d918/greenlet-3.5.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:06c0e933290fba8ffe53ead4ae1b8044b0e9754b75cebf381aa2bc3e50d82fac", size = 1647590, upload-time = "2026-09-14T14:35:51.173Z" }, { url = "https://files.pythonhosted.org/packages/86/da/b7669b09586365654083a62bd0724cf06cb74bd5085a15cdd161271f992f/greenlet-3.5.6-cp313-cp313-win_amd64.whl", hash = "sha256:5b602b4201b965a8354d74e232364a66ff243dd142e350d035f46169bb36e13d", size = 324086, upload-time = "2026-09-14T14:23:48.428Z" }, @@ -1155,9 +1042,7 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/66/c0/d254544ae2b8bdd311aef000fafc02828c2771b17d994b3075620ea7cc6e/greenlet-3.5.6-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46", size = 295221, upload-time = "2026-09-14T14:25:11.583Z" }, { url = "https://files.pythonhosted.org/packages/18/18/eb54be16b9cc3971e09ca5b73334e1b8c804a4630d9addaaf218a4fe300f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb", size = 660992, upload-time = "2026-09-14T15:12:04.876Z" }, { url = "https://files.pythonhosted.org/packages/8f/b4/e193efe65671dcf294bc51fcc59efb52d154adf8612c4ea016da0d2c486c/greenlet-3.5.6-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b", size = 673428, upload-time = "2026-09-14T15:20:45.756Z" }, - { url = "https://files.pythonhosted.org/packages/fd/21/631bb45fafde1dca782152377c0676d182ec924820064047f533a3627b28/greenlet-3.5.6-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b", size = 677688, upload-time = "2026-09-14T15:25:09.279Z" }, { url = "https://files.pythonhosted.org/packages/45/ac/28fa7a9e50f2859466214c4ac584d776db52c1604ad4dd158960a5af2a1f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88", size = 670773, upload-time = "2026-09-14T14:36:02.577Z" }, - { url = "https://files.pythonhosted.org/packages/40/30/2b0a73e68e1e18e30b601d0d183cfdfc2beca4de5a6843c630f0fc9fb90c/greenlet-3.5.6-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77", size = 480475, upload-time = "2026-09-14T15:28:40.741Z" }, { url = "https://files.pythonhosted.org/packages/c3/cd/fb7d6cdd86ff3427c1494854f0e35437eba05142be91f530f6da75e09e19/greenlet-3.5.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02", size = 1631900, upload-time = "2026-09-14T15:10:09.745Z" }, { url = "https://files.pythonhosted.org/packages/f6/40/143bdbb20a516628cb15074ae52ed17d850b450292609c7a6fccac6dbece/greenlet-3.5.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424", size = 1693740, upload-time = "2026-09-14T14:35:52.959Z" }, { url = "https://files.pythonhosted.org/packages/c9/9e/019642432e6ae283301df1361227d47610709d2dc69a38f95edef266d713/greenlet-3.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a", size = 327473, upload-time = "2026-09-14T14:28:12.948Z" }, @@ -1165,18 +1050,14 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/7e/7a205688a5b3074933b18a906608d46d106e9a79d776bdab5a4abf4b4feb/greenlet-3.5.6-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951", size = 305352, upload-time = "2026-09-14T14:21:31.962Z" }, { url = "https://files.pythonhosted.org/packages/78/cb/9c4a57a9d9dd0256e20b8f7f4f06554c2c92badebf0ab73ce344321b78b9/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49", size = 672671, upload-time = "2026-09-14T15:12:06.347Z" }, { url = "https://files.pythonhosted.org/packages/97/52/c6729681ebbd298f4decd28746815acc8a0b0a0fde21d2df33776fd4d042/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b", size = 679489, upload-time = "2026-09-14T15:20:47.291Z" }, - { url = "https://files.pythonhosted.org/packages/71/76/3c11c21e0716b1f1dc7c1a4b3d690abb1d3b448c69a9d32049fecb64010a/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d", size = 681303, upload-time = "2026-09-14T15:25:11.088Z" }, { url = "https://files.pythonhosted.org/packages/58/c5/2b6c721ba8b8963da42d5a0f57f25b8aaeb1fe9bdd156875e57f3be648a2/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc", size = 676608, upload-time = "2026-09-14T14:36:03.959Z" }, - { url = "https://files.pythonhosted.org/packages/3f/26/3ae402202452cd5941bbbd483e5a74297e2397e7aa3182c2a5e3ab7d5666/greenlet-3.5.6-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81", size = 510112, upload-time = "2026-09-14T15:28:42.112Z" }, { url = "https://files.pythonhosted.org/packages/b2/04/0d018e0d05bcdde19a0fcb907834155f1fc853a9bedd3f3f5e6acadcae19/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961", size = 1641479, upload-time = "2026-09-14T15:10:11.216Z" }, { url = "https://files.pythonhosted.org/packages/59/bb/f02ef9073919158f6403fe3701d4ed4403d646720e7201dfc6e9d264bac3/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404", size = 1698758, upload-time = "2026-09-14T14:35:54.336Z" }, { url = "https://files.pythonhosted.org/packages/08/a5/1f48fe647473a2dcccfd1839b2ff2c78eb57009be776b4da071e901c9bff/greenlet-3.5.6-cp314-cp314t-win_amd64.whl", hash = "sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16", size = 331574, upload-time = "2026-09-14T14:27:18.451Z" }, { url = "https://files.pythonhosted.org/packages/cd/72/3882855a75838faeb54a58aeef4fd77d20b2a86d4bad570c70d41b565dcf/greenlet-3.5.6-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:3ac3494c381dab876cad7d0b22f3a722f3e0c8deb3a65b9e7f35ad7f58b8fcb3", size = 295926, upload-time = "2026-09-14T14:27:21.16Z" }, { url = "https://files.pythonhosted.org/packages/10/1f/be4d957d8a9b90bcbe8db206548a42134d96222d43e5ed3fc4708fb6e24b/greenlet-3.5.6-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:602024dae6d77e161f4b89491b62ca1d4f19949d79d47b2db057e476d21179d6", size = 666910, upload-time = "2026-09-14T15:12:07.901Z" }, { url = "https://files.pythonhosted.org/packages/a1/af/60d62571a7d6de961e4ce7625d6c2faf359345659fc782d2cdf517c34577/greenlet-3.5.6-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f8e63209c3e1e828ee6a457529b4a6d8b05d050fe0ae03a7ae49e967c5d312e0", size = 677415, upload-time = "2026-09-14T15:20:48.817Z" }, - { url = "https://files.pythonhosted.org/packages/f5/41/b3114c97c10e796010f00a30f51c81470072bca4b53e396ccca87484fcf7/greenlet-3.5.6-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9133d68624b1f2e89ec2f554d56aea8a5b0d7168cd9320200ba58d4d794845a4", size = 681337, upload-time = "2026-09-14T15:25:12.812Z" }, { url = "https://files.pythonhosted.org/packages/fb/16/ac9e547b611539aaed1870eb1d6ddc57abdd5924b3a99bb9b5f0b44176b8/greenlet-3.5.6-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccadce0130fd813ec86ebfe969a6c58b42acc1d0fe55a47525375b740e07b605", size = 675927, upload-time = "2026-09-14T14:36:05.34Z" }, - { url = "https://files.pythonhosted.org/packages/48/1b/d41861c2fa00968e39e467a495ca8db9ce9b6310a5d9b57561b3d0dc48fa/greenlet-3.5.6-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:5adcbbfe78bdc242c71740a02e0991cc1b2f34d33c8bb15ca45eee8fd1140942", size = 487339, upload-time = "2026-09-14T15:28:43.497Z" }, { url = "https://files.pythonhosted.org/packages/c4/b1/b7ba08d6431121741f1d30be0d5d292e76873325179a63586cd9217b62f6/greenlet-3.5.6-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9297fb9c39b9a2c039dbcd306c410bd6906b95244dec3bba4318d36c718c164c", size = 1637236, upload-time = "2026-09-14T15:10:12.442Z" }, { url = "https://files.pythonhosted.org/packages/af/c5/3b1cbc68f0c082022fc8717f7fe4b8b13b8d583c52352be37f4e9f55bcd2/greenlet-3.5.6-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b374e79ffa7511afc11773aef40a4ccea6191fba1c856ea2f9c56738dca69d7a", size = 1698526, upload-time = "2026-09-14T14:35:56.039Z" }, { url = "https://files.pythonhosted.org/packages/de/56/12941ed2711400451c89d544e10f831800a2770f19dd55eac8f0f7f2003b/greenlet-3.5.6-cp315-cp315-win_amd64.whl", hash = "sha256:7969bffa322c097bd46ae595ada6a931cefda613f18ba64587e9cff4cb320756", size = 327739, upload-time = "2026-09-14T14:23:55.768Z" }, @@ -1184,9 +1065,7 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/16/c2/86cfc5555a98e12b86966ddbd24fd39af32f71f2f785c6595b7feb2db156/greenlet-3.5.6-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:de3de000d459402cda015068fd135aa50c0bf6f2477a80d4da1e646f123b4e78", size = 306244, upload-time = "2026-09-14T14:27:57.565Z" }, { url = "https://files.pythonhosted.org/packages/14/6d/83ffc9d05a75a80ab3a7595dbb1d9604e5d4fc2996d73a8ae2dbd1284900/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45663c01a4de48b9a64a2ee1509d92d1dfd3afb02b2ccfc9333029d11aef996a", size = 676578, upload-time = "2026-09-14T15:12:09.468Z" }, { url = "https://files.pythonhosted.org/packages/5d/d6/c2cf684810e5caded075970aaadea654ecb58b8382b9aecf1d231b936894/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3deccbb57a481e3a408fe61cdfd5c13e0678fc0a30fdd09597917ca87b4be877", size = 684203, upload-time = "2026-09-14T15:20:50.261Z" }, - { url = "https://files.pythonhosted.org/packages/f2/d1/039c353d5593a97a89699e989324c9bc86af499e6c6152fe0180f5742204/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:63aff70fe5aac59c72215f42ec39fcb59ff46774fa966e717f8ecb6ee2273577", size = 686023, upload-time = "2026-09-14T15:25:14.528Z" }, { url = "https://files.pythonhosted.org/packages/62/19/00e1bee5d2af890dc8f400b54d0b0f9b489965f92bc12b407ff72cc6f469/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:311018b46472fb26ee85870847fb89eb64cc8aaddb617400789d87076f7cfeec", size = 681253, upload-time = "2026-09-14T14:36:06.742Z" }, - { url = "https://files.pythonhosted.org/packages/8a/62/97ceb8e0b2ea96046cdf8e95b042715020ebb12d83ea0690db80a8f03d23/greenlet-3.5.6-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:520648db8fb92eef7b3e6013f5a6f901cdf0d6685f639c2f7a245879f865bef7", size = 517058, upload-time = "2026-09-14T15:28:44.924Z" }, { url = "https://files.pythonhosted.org/packages/89/58/c9275fd0ca195d1d3402931bcce8cfcc74726ff76efb1883d229e6e1a3d7/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:7f924a5a9d5890649566f2f6682e0d8ad8ca23028bacffbbac36dbd7fd680176", size = 1645988, upload-time = "2026-09-14T15:10:13.758Z" }, { url = "https://files.pythonhosted.org/packages/e0/36/b35747582fa4f1a5453f8f3002405dbac788e450cec7674dc2d204b6ccb5/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:de9923832f2d8c1a5ecd8d7260465a6ca5a86888a0d129e3bd5cf0406d2fc5bf", size = 1702383, upload-time = "2026-09-14T14:35:58.143Z" }, { url = "https://files.pythonhosted.org/packages/ed/69/6ec22ac9351e474d2a134d0ff9400dc80362d1c20f0721088ffffdfc205b/greenlet-3.5.6-cp315-cp315t-win_amd64.whl", hash = "sha256:2ab5f42ac6c238eb71770715e6e909ad9a1a92b6c681ccb64cd5a0f07edb953f", size = 331845, upload-time = "2026-09-14T14:27:41.723Z" }, @@ -1241,34 +1120,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/55/ecca97ae19075f1fac62def77731e7f535e6c1fb8f92ff08160c5e6dade8/importlib_metadata-9.0.1-py3-none-any.whl", hash = "sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0", size = 27920, upload-time = "2026-08-28T15:30:33.433Z" }, ] -[[package]] -name = "indicadores-kit" -version = "0.8.0" -source = { editable = "../indicadores_kit" } -dependencies = [ - { name = "core" }, - { name = "pandas" }, - { name = "pandera" }, - { name = "persistance" }, - { name = "plotly" }, - { name = "sqlalchemy-utils" }, - { name = "sqlmodel" }, -] - -[package.metadata] -requires-dist = [ - { name = "core", editable = "../Core" }, - { name = "pandas", specifier = "==3.0.6" }, - { name = "pandera", specifier = "==0.33.1" }, - { name = "persistance", editable = "../Persistance" }, - { name = "plotly", specifier = "==7.1.0" }, - { name = "sqlalchemy-utils", specifier = "==0.42.1" }, - { name = "sqlmodel", specifier = "==0.0.47" }, -] - -[package.metadata.requires-dev] -dev = [{ name = "pytest", specifier = "==9.1.1" }] - [[package]] name = "iniconfig" version = "2.3.0" @@ -1278,62 +1129,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] -[[package]] -name = "ipykernel" -version = "7.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "appnope", marker = "sys_platform == 'darwin'" }, - { name = "comm" }, - { name = "debugpy" }, - { name = "ipython" }, - { name = "jupyter-client" }, - { name = "jupyter-core" }, - { name = "matplotlib-inline" }, - { name = "nest-asyncio2" }, - { name = "packaging" }, - { name = "pyzmq" }, - { name = "tornado" }, - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7a/05/e5499c8b762387d83926bf0389e8fff888c9bf6e7af30566a8527bc12f4a/ipykernel-7.4.0.tar.gz", hash = "sha256:4330114d22b9b33575b2c7c68753fc8faabbbcfbc60b0cdff9f14dd4ce63742f", size = 192731, upload-time = "2026-09-29T16:33:11.468Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a5/f8/8b5c10c7f36ab5a3b5c4703669e5b14e44e98782b58e535dd30670e8799a/ipykernel-7.4.0-py3-none-any.whl", hash = "sha256:a6757f790ddc5a6006b813d82da1a9dbb65b3a00f2b6607df776418c6566ec1c", size = 123184, upload-time = "2026-09-29T16:33:09.612Z" }, -] - -[[package]] -name = "ipython" -version = "9.18.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "ipython-pygments-lexers" }, - { name = "jedi" }, - { name = "matplotlib-inline" }, - { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit" }, - { name = "psutil", marker = "sys_platform != 'android' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, - { name = "pygments" }, - { name = "stack-data" }, - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/38/04/0d945c72d5b77527273ecb4c66aa2436de7a3b3bbe3da345bf053232b886/ipython-9.18.1.tar.gz", hash = "sha256:6319c0f5372c196397899479e6db1783dd7937abae06815d1317e8d5d51aaaaf", size = 4437314, upload-time = "2026-11-02T09:19:55.55Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bb/1c/91da4a1c541b75e97eb99d09c6a9b0534de55bb4a466669d1170e39b915c/ipython-9.18.1-py3-none-any.whl", hash = "sha256:997ce9140d374531a61069c70c0f9ef299d6dd3559ea0f94b8af589726e3c1d5", size = 649819, upload-time = "2026-11-02T09:19:53.32Z" }, -] - -[[package]] -name = "ipython-pygments-lexers" -version = "1.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pygments" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" }, -] - [[package]] name = "itsdangerous" version = "2.2.0" @@ -1343,18 +1138,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, ] -[[package]] -name = "jedi" -version = "0.20.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "parso" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/a4/4692ecd7fa700ac1066b1c1f6cadef60aa2e01e5e364710235137d823e0a/jedi-0.20.1.tar.gz", hash = "sha256:2f71208c3f9c1bca057c0e90d3f272aba44ace88fc4067d7587e9e069331b7e5", size = 3121738, upload-time = "2026-10-12T17:42:24.361Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/be/c7/71eb0d51cdcbb63b857c931aa4e9218b078b5d9f8ecd383b234f28fe7b0f/jedi-0.20.1-py2.py3-none-any.whl", hash = "sha256:0fb16d86c4a4c73c37ba518c77419975e30fcc620658a8d14fbb5720cdd34142", size = 4885980, upload-time = "2026-10-12T17:42:21.585Z" }, -] - [[package]] name = "jinja2" version = "3.1.6" @@ -1379,72 +1162,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, ] -[[package]] -name = "jsonschema" -version = "4.26.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "jsonschema-specifications" }, - { name = "referencing" }, - { name = "rpds-py" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, -] - -[[package]] -name = "jsonschema-specifications" -version = "2025.9.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "referencing" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, -] - -[[package]] -name = "jupyter-client" -version = "8.10.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "jupyter-core" }, - { name = "python-dateutil" }, - { name = "pyzmq" }, - { name = "tornado" }, - { name = "traitlets" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c5/2a/906772148a06e48885039e0250c340b770a55bbf37b08d6ee0449df369c3/jupyter_client-8.10.0.tar.gz", hash = "sha256:9f7116294dca55f1785be880057d44544db9b1567718d92cb33c58886afb9497", size = 360653, upload-time = "2026-08-28T12:17:10.854Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/88/7c548de1f6c2ade7c931a3282da73f9274fa6a1531091be682f89c85efb9/jupyter_client-8.10.0-py3-none-any.whl", hash = "sha256:5f73f24f22fa25192cfff6b23c051932a2473a797b05734aff495b392103e14e", size = 110184, upload-time = "2026-08-28T12:17:09.028Z" }, -] - -[[package]] -name = "jupyter-core" -version = "5.9.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "platformdirs" }, - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/02/49/9d1284d0dc65e2c757b74c6687b6d319b02f822ad039e5c512df9194d9dd/jupyter_core-5.9.1.tar.gz", hash = "sha256:4d09aaff303b9566c3ce657f580bd089ff5c91f5f89cf7d8846c3cdf465b5508", size = 89814, upload-time = "2025-10-16T19:19:18.444Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/e7/80988e32bf6f73919a113473a604f5a8f09094de312b9d52b79c2df7612b/jupyter_core-5.9.1-py3-none-any.whl", hash = "sha256:ebf87fdc6073d142e114c72c9e29a9d7ca03fad818c5d300ce2adc1fb0743407", size = 29032, upload-time = "2025-10-16T19:19:16.783Z" }, -] - -[[package]] -name = "jupyterlab-pygments" -version = "0.3.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/90/51/9187be60d989df97f5f0aba133fa54e7300f17616e065d1ada7d7646b6d6/jupyterlab_pygments-0.3.0.tar.gz", hash = "sha256:721aca4d9029252b11cfa9d185e5b5af4d54772bb8072f9b7036f4170054d35d", size = 512900, upload-time = "2023-11-23T09:26:37.44Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/dd/ead9d8ea85bf202d90cc513b533f9c363121c7792674f78e0d8a854b63b4/jupyterlab_pygments-0.3.0-py3-none-any.whl", hash = "sha256:841a89020971da1d8693f1a99997aefc5dc424bb1b251fd6322462a1b8842780", size = 15884, upload-time = "2023-11-23T09:26:34.325Z" }, -] - [[package]] name = "kiwisolver" version = "1.5.1" @@ -1703,27 +1420,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/5a/9f440e7bec8b80d0af2a65d1165b2f4e718982dad785531f62255d9ff19b/matplotlib-3.11.2-cp315-cp315t-win_arm64.whl", hash = "sha256:d480038c83691532ed52ff3147db51fa902fc78cb2d8349993a1cdb684435bff", size = 9233946, upload-time = "2026-09-11T19:05:19.063Z" }, ] -[[package]] -name = "matplotlib-inline" -version = "0.2.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" }, -] - -[[package]] -name = "mistune" -version = "3.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/96/eb/749a4e69bf7396e751ae37444abe997eff2254e695a8095b84d1c89c1181/mistune-3.4.0.tar.gz", hash = "sha256:2eaf7952af928ca8d33b779762effc1da517b62c6ad85ec8ca957e3b07b9782a", size = 136772, upload-time = "2026-10-19T10:44:28.172Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/f7/021d590d52c1ac28e3290311776854c6a1c927fa3fb4b25ce74caf937a3d/mistune-3.4.0-py3-none-any.whl", hash = "sha256:d03cec4c8620f21517a996d82d14f3b59c30d79bda2cc6c56bd32b839f18ce6b", size = 70398, upload-time = "2026-10-19T10:44:26.751Z" }, -] - [[package]] name = "mlflow" version = "3.17.2" @@ -1841,34 +1537,23 @@ dependencies = [ { name = "scikit-learn" }, ] -[package.optional-dependencies] -notebooks = [ - { name = "ipykernel" }, - { name = "nbclient" }, - { name = "nbconvert" }, -] - [package.metadata] requires-dist = [ { name = "apache-hamilton", specifier = ">=1.90" }, { name = "extraction", editable = "../Extraction" }, - { name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" }, { name = "mlflow", specifier = ">=2.9" }, - { name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" }, - { name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" }, + { name = "onnx", marker = "extra == 'export'", specifier = ">=1.15" }, { name = "pandas", specifier = ">=2.0" }, { name = "pandera", specifier = ">=0.20" }, { name = "persistance", editable = "../Persistance" }, { name = "pyarrow", specifier = ">=15" }, { name = "scikit-learn", specifier = ">=1.4" }, ] -provides-extras = ["notebooks"] +provides-extras = ["export"] [package.metadata.requires-dev] dev = [ - { name = "ipykernel", specifier = ">=6.29" }, - { name = "nbclient", specifier = ">=0.10" }, - { name = "nbconvert", specifier = ">=7.16" }, + { name = "onnx", specifier = ">=1.15" }, { name = "pytest", specifier = ">=8.0.0" }, { name = "reportlab", specifier = ">=4.0" }, ] @@ -2029,70 +1714,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/89/5d4c86da1130d9059681e5b6cd7645df5c10279a6a079c5c37dcb2cc6f3f/narwhals-2.27.1-py3-none-any.whl", hash = "sha256:d057df13f5852b8e157596e82eb5e955fad267425df5e420e0ee9863da483b31", size = 483211, upload-time = "2026-10-10T06:52:16.32Z" }, ] -[[package]] -name = "nbclient" -version = "0.11.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "jupyter-client" }, - { name = "jupyter-core" }, - { name = "nbformat" }, - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/a5/b3bae4b590c0cbcada2c63a34f7580024e834a8ba213e949a2f906705787/nbclient-0.11.0.tar.gz", hash = "sha256:04a134a5b087f2c5887f228aca155db50169b8cd9334dee6942c8e927e56081a", size = 62535, upload-time = "2026-06-05T07:52:41.746Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/36/c9/94d73e5a01c5b926c3fa2496e97d7a8dc28ed5a77c0b2ed712f1a62e6694/nbclient-0.11.0-py3-none-any.whl", hash = "sha256:ef7fa0d59d6e1d41103933d8a445a18d5de860ca6b613b87b8574accdb3c2895", size = 25288, upload-time = "2026-06-05T07:52:40.115Z" }, -] - -[[package]] -name = "nbconvert" -version = "7.17.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "beautifulsoup4" }, - { name = "bleach", extra = ["css"] }, - { name = "defusedxml" }, - { name = "jinja2" }, - { name = "jupyter-core" }, - { name = "jupyterlab-pygments" }, - { name = "markupsafe" }, - { name = "mistune" }, - { name = "nbclient" }, - { name = "nbformat" }, - { name = "packaging" }, - { name = "pandocfilters" }, - { name = "pygments" }, - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/53/6a/252c7620305a9661205aed7a2a4b3592f5207bfca56ad11b7dea2c5ec2f6/nbconvert-7.17.2.tar.gz", hash = "sha256:344a218e8595117ce37396ed025d994f146d076226ebac59255a2fa085ab24d8", size = 865989, upload-time = "2026-10-12T09:11:19.583Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/81/fd/a8d457af68848a8e5c12dd1d84ff35c415db471af78280e0703db4efbb12/nbconvert-7.17.2-py3-none-any.whl", hash = "sha256:6a143c11c00bf831604da4b1be4347d36ea52367057eb920135d69bc2862fed2", size = 262094, upload-time = "2026-10-12T09:11:17.215Z" }, -] - -[[package]] -name = "nbformat" -version = "5.11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "fastjsonschema" }, - { name = "jsonschema" }, - { name = "jupyter-core" }, - { name = "traitlets" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/31/72/b3446efab8756e7df4b8ec587f8e611cb5a7249e4323db480802f1d3be04/nbformat-5.11.1.tar.gz", hash = "sha256:32d4521c68c6e7d5b29c76defaeed9f42ea733142b9b19f88277ce10390b9c4d", size = 147775, upload-time = "2026-08-17T08:10:51.942Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/69/ee613f74085ca7103f79cd08d579c4f3177d1d26e5d3d9528d2d6536a707/nbformat-5.11.1-py3-none-any.whl", hash = "sha256:cc6698fa75f4fab8755ead786317815f13a6fee3b53311c0abb1a8b51d52f7ec", size = 79849, upload-time = "2026-08-17T08:10:50.18Z" }, -] - -[[package]] -name = "nest-asyncio2" -version = "1.7.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/32/2c/70e3b6bb2189cfd260280b7e1042bd622949a258663f95e887fada4ac1e6/nest_asyncio2-1.7.4.tar.gz", hash = "sha256:995b1409d926ec55e0876ea39a69bffdd8852cf1db3652c177e8c8ffdbcaf3cc", size = 16891, upload-time = "2026-10-07T22:31:50.507Z" } -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 = "numpy" version = "2.5.3" @@ -2316,24 +1937,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/84/107a480f7aa34a6878fb4fb85cda66f37e8aaee769c5917e3eaa2d55222e/pandera-0.33.1-py3-none-any.whl", hash = "sha256:8283bc12f7c85f0b429107d71b55150205f7e5ca59d68117aff971273a3bd2d8", size = 501976, upload-time = "2026-09-01T15:56:05.944Z" }, ] -[[package]] -name = "pandocfilters" -version = "1.5.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/70/6f/3dd4940bbe001c06a65f88e36bad298bc7a0de5036115639926b0c5c0458/pandocfilters-1.5.1.tar.gz", hash = "sha256:002b4a555ee4ebc03f8b66307e287fa492e4a77b4ea14d3f934328297bb4939e", size = 8454, upload-time = "2024-01-18T20:08:13.726Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/af/4fbc8cab944db5d21b7e2a5b8e9211a03a79852b1157e2c102fcc61ac440/pandocfilters-1.5.1-py2.py3-none-any.whl", hash = "sha256:93be382804a9cdb0a7267585f157e5d1731bbe5545a85b268d6f5fe6232de2bc", size = 8663, upload-time = "2024-01-18T20:08:11.28Z" }, -] - -[[package]] -name = "parso" -version = "0.8.7" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, -] - [[package]] name = "pdfminer-six" version = "20260107" @@ -2390,18 +1993,6 @@ dev = [ { name = "pytest", specifier = ">=8.0.0" }, ] -[[package]] -name = "pexpect" -version = "4.9.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } -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 = "pillow" version = "12.3.0" @@ -2482,19 +2073,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" }, ] -[[package]] -name = "plotly" -version = "7.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "narwhals" }, - { name = "packaging" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/49/c3/72b369f5ed7701b04ab0ea3dcf83e9bbce71c0b3bc6f07f87568550d09ea/plotly-7.1.0.tar.gz", hash = "sha256:f860166a4a3d78c69cb1f4a15f28a5c8283eade98a282a698f3bb853a449ace5", size = 6689315, upload-time = "2026-09-15T19:21:21.75Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl", hash = "sha256:dbb7fa18afce40d0a8e80d1bf162eceb3faa0ce5a77fe741ad09a74cf78f53f3", size = 9692368, upload-time = "2026-09-15T19:21:18.331Z" }, -] - [[package]] name = "pluggy" version = "1.6.0" @@ -2530,18 +2108,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fe/be/2e6798ace5cc036f5d05d36b7b2fd85346f1a708c87060890b070d0ec607/prettytable-3.18.0-py3-none-any.whl", hash = "sha256:b3346e0e6f79180833aebaac088ae926340586cf6d7d991b9eb125b65f72313a", size = 37357, upload-time = "2026-06-22T16:07:48.595Z" }, ] -[[package]] -name = "prompt-toolkit" -version = "3.0.53" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "wcwidth" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, -] - [[package]] name = "propcache" version = "0.5.4" @@ -2668,34 +2234,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" }, ] -[[package]] -name = "psutil" -version = "7.2.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, - { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, - { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, - { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, - { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, - { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, - { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, - { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, - { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, - { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, - { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, - { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, - { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, - { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, - { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, - { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, - { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, - { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, - { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, - { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, -] - [[package]] name = "psycopg2-binary" version = "2.9.13" @@ -2748,24 +2286,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e8/30/3991c9fdcca90a5a1e55435292f4d74d176da2be15f3998f6858da3658cc/psycopg2_binary-2.9.13-cp315-cp315-win_amd64.whl", hash = "sha256:1752b9821f1377404d65ac43af03d59a1eccc57fb2c1eb8305f9a3fe8eb7a8ba", size = 2867246, upload-time = "2026-09-09T23:56:20.501Z" }, ] -[[package]] -name = "ptyprocess" -version = "0.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" }, -] - -[[package]] -name = "pure-eval" -version = "0.2.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/da/9f/abfd2959e9261dd5217ca8551d4de211ca6ab26fe9b72cf44731ff6c4442/pure_eval-0.2.4.tar.gz", hash = "sha256:260c2774686e651b79f8b8e7fc9d80b3599ea6a66334b47d5f4abb69fc2c0ea1", size = 20563, upload-time = "2026-09-10T21:41:22.836Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6d/18/83376915176eb058cb86470eb7396388a13350b09a8f233a79303bbcbc5b/pure_eval-0.2.4-py3-none-any.whl", hash = "sha256:96cae060a313cfaad51bb761278bfb0e62dc0248d9315a81173752dc546cd37a", size = 11893, upload-time = "2026-09-10T21:41:21.532Z" }, -] - [[package]] name = "pyarrow" version = "25.0.1" @@ -3157,60 +2677,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] -[[package]] -name = "pyzmq" -version = "27.3.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi", marker = "implementation_name == 'pypy'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e2/e1/ea46ab0d707219c098065a37d2add5b53d3b124241aa19429bcd0863e5b4/pyzmq-27.3.0.tar.gz", hash = "sha256:bbedb3d1d99babc625f1dd9d7438acefd442b36b75073fd6bc1ef7c0a4b96d56", size = 293249, upload-time = "2026-11-04T00:31:33.068Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/9e/6663ccc8c1af4e7db85de65921560a8058ad4ad4c40ebc49af4b1164f01a/pyzmq-27.3.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:15155fd8f308d3bd47f67a8f6cc809f9db90abbf63c514c384a17622e2cf080f", size = 1232964, upload-time = "2026-11-04T00:29:09.922Z" }, - { url = "https://files.pythonhosted.org/packages/b4/90/4fc65d7a48077f535705ac957c29a3c07fa54a1f8d2595ca2f5f1489b21c/pyzmq-27.3.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ad8b828407caee77ff3ab0bdb2984ee8d48922328b226e8fda7c84a71a55dbb4", size = 770405, upload-time = "2026-11-04T00:29:11.487Z" }, - { url = "https://files.pythonhosted.org/packages/2c/62/e4721d8b8b9de685323717489a408521067a786cabc2b73ccd91aa9b9077/pyzmq-27.3.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:858fe25231e0fd8612da142efde019faa5ef63fa150a821a27870e791b38c798", size = 855178, upload-time = "2026-11-04T00:29:13.042Z" }, - { url = "https://files.pythonhosted.org/packages/39/5f/8190ff273beb195d9c9b62a36d0d87bad79019e76ff4407cabe463bc650d/pyzmq-27.3.0-cp312-abi3-manylinux_2_28_i686.whl", hash = "sha256:8b174298b57d5c2397c74fbefd656101d477357035916881970ed5f53b7b904c", size = 919158, upload-time = "2026-11-04T00:29:14.854Z" }, - { url = "https://files.pythonhosted.org/packages/8f/66/ab116baad852235c82be3d8d83af7098a7165c48995a03f2b6e8d50297dc/pyzmq-27.3.0-cp312-abi3-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cffd75359342ef88c86c287c99b16b2b100795dab467fd5398bcedd87d49bce7", size = 813613, upload-time = "2026-11-04T00:29:17.239Z" }, - { url = "https://files.pythonhosted.org/packages/b3/55/5075ef84055eca159435e65f8d67591bfe06c562cf310792cd50a6aeb0c9/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:220095b4c11b0542ae5c0d67411331d3819753ee9ec0468e63a4ca6fd4ccf50f", size = 1762126, upload-time = "2026-11-04T00:29:18.994Z" }, - { url = "https://files.pythonhosted.org/packages/28/6f/e75d5e5aeda920dbcaaedcc413605379287b817578d00e47bfa89a8ea671/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:e9e12fe784529e12177937aee8c714b7aed8913a2429ee2567400c904d4d55b5", size = 2067522, upload-time = "2026-11-04T00:29:20.762Z" }, - { url = "https://files.pythonhosted.org/packages/9c/b4/0d91b1e5ea8d659c1014ef39acfda279f4768fc4043120e98b764a59f1c9/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d317685b83663fbd03ca8b5c34add7463e9bed094e3e1a69d2a895130b64ffaf", size = 1893864, upload-time = "2026-11-04T00:29:22.451Z" }, - { url = "https://files.pythonhosted.org/packages/2a/23/ed213d9dc6e48913a1f77090d1aed85bc4b1e5567ef74a86fd8fd473f423/pyzmq-27.3.0-cp312-abi3-win32.whl", hash = "sha256:07dd778d7cf242a1e131bfad6244f64df59441dda7ea639d037d0fdb22112b6c", size = 567172, upload-time = "2026-11-04T00:29:24.09Z" }, - { url = "https://files.pythonhosted.org/packages/fa/6d/23a02024011a494fb52bcfb179f10a3b230cff7b6fe0d5b8a3c775ce3b82/pyzmq-27.3.0-cp312-abi3-win_amd64.whl", hash = "sha256:3ea8e8fa5c097e68fef91d70b150fda96f307758103868018fc4deeb9c214122", size = 642389, upload-time = "2026-11-04T00:29:25.739Z" }, - { url = "https://files.pythonhosted.org/packages/e2/1b/410fc7ec4fc114b46da17ed0df3b88606f0624fbe172e184658d361b1dc1/pyzmq-27.3.0-cp312-abi3-win_arm64.whl", hash = "sha256:2187a5ca80691a5edb30690f02d9fb714e2c32d3dfdeb652e159ff5da2dd4283", size = 570810, upload-time = "2026-11-04T00:29:27.709Z" }, - { url = "https://files.pythonhosted.org/packages/d1/0f/81652a1066e994000cfec501f16137fa231e921675b63ee54c8cf4e30362/pyzmq-27.3.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:a418d35be0a0a2693bf1990d831a744ee2f012b8268b3e0c6cb28b06c2769d76", size = 1136520, upload-time = "2026-11-04T00:29:29.58Z" }, - { url = "https://files.pythonhosted.org/packages/ce/0e/a2e5cb7db327ce85f3c2d11f25be55aba1639f55dad8ea77e03458ec5dbf/pyzmq-27.3.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:e9012762d869d620dad3c83fb5ff8f4900490decddd98caf6ff80847176c4be0", size = 1181427, upload-time = "2026-11-04T00:29:31.178Z" }, - { url = "https://files.pythonhosted.org/packages/88/b8/8a80749971b1a42fc415c720a52deedd33d0ae72792544331fc76f306ded/pyzmq-27.3.0-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:fca5c2352c499e8355b581ddecfe52538984131b7efc052a30e2d32426baf637", size = 1143753, upload-time = "2026-11-04T00:29:32.923Z" }, - { url = "https://files.pythonhosted.org/packages/59/2d/196f50920da3137fd54b1636c36aba97b95d18d467bf097edca5f6ef5be8/pyzmq-27.3.0-cp314-cp314-android_24_x86_64.whl", hash = "sha256:91ac316f440aca4e6eaf3786f54b80f4ab433e5cc4e5e9b82eb44a27c5c987cd", size = 1182341, upload-time = "2026-11-04T00:29:35.073Z" }, - { url = "https://files.pythonhosted.org/packages/c7/3f/bf2a67da7cfac3c1f85c0130b8bd1fc48e96c1e66e8a50c71faea83979b3/pyzmq-27.3.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:d292cedc7250db240e9f41994cf3eefe2c7606c702ef5c56aab8d4f03870108c", size = 1271939, upload-time = "2026-11-04T00:29:36.803Z" }, - { url = "https://files.pythonhosted.org/packages/f6/43/2bfa60b57b3febd892d5760c811012b6850306962e3dd6a2f91b96cd5398/pyzmq-27.3.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:924f870055c05926887157485efe903c8f9668d0f3f19d56df7612bcb3d662cb", size = 779903, upload-time = "2026-11-04T00:29:38.52Z" }, - { url = "https://files.pythonhosted.org/packages/e3/72/4f88cd0d1da0e5db9a26a899e37f8b46d925f328f9bae590f86fc995074b/pyzmq-27.3.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6dac496cd8aacf185a634e5cc8930331db1627dd214a58ee4c27948ce4ae79af", size = 864708, upload-time = "2026-11-04T00:29:50.209Z" }, - { url = "https://files.pythonhosted.org/packages/79/5e/fce842845aad4135a2e1936f3cd1a418b4f49e2d45cd7b5576d6f836d95b/pyzmq-27.3.0-cp314-cp314t-manylinux_2_28_i686.whl", hash = "sha256:665b1a3d35a4ffe6cfa626191a5439108159d51d17bd9d44f1beb1690114adfc", size = 927234, upload-time = "2026-11-04T00:29:52.003Z" }, - { url = "https://files.pythonhosted.org/packages/e1/28/945736083a00750e101c4259312b5303aead36ef08539a0f0ad93a1cb899/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0fedab58520a5091ffa62547eb507bea44882ce72d49929fa9626061ae1b9a2c", size = 1771921, upload-time = "2026-11-04T00:29:53.677Z" }, - { url = "https://files.pythonhosted.org/packages/3d/30/2a584e845a51c0e5d6e13889fe659aa90912004fbb5bc4750491f558528c/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:1b9b9d11e2e775a81d0e8b5c6cb76a395ddaa7c6b6373f3b0d2c8f8146d95f4a", size = 2075396, upload-time = "2026-11-04T00:29:55.772Z" }, - { url = "https://files.pythonhosted.org/packages/4e/6b/93066f121c31b825c56c74dca01ea5c00847f8b44645ad990f92bd04d29c/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:169a522c4d166c3bc7b67ed827d3beda549a8e65c4015c9410687757fb39852f", size = 1903986, upload-time = "2026-11-04T00:29:57.741Z" }, - { url = "https://files.pythonhosted.org/packages/85/ae/ecc7c77cd6ea18ff7b2b07a2fd0db5c31c2204ecf9a774e80bd1250dc9d9/pyzmq-27.3.0-cp314-cp314t-win32.whl", hash = "sha256:0228fe121f05a8b638ef218dde7508477a8c46200a588f71ce7143d85987cdd7", size = 597206, upload-time = "2026-11-04T00:29:59.35Z" }, - { url = "https://files.pythonhosted.org/packages/7a/1d/0bee73e1e8ab1c26eecba13a4725dfbe0405b53f451a91671dd515effe00/pyzmq-27.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8a3d02fc710302a23c9a67b287bc13f2992067d398c3192b50eb0e30d44ed885", size = 685132, upload-time = "2026-11-04T00:30:01.144Z" }, - { url = "https://files.pythonhosted.org/packages/cd/23/13a768f9a8e66a999250abd216e50e1961a1cd4a8708749f656f5c0c2aea/pyzmq-27.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2b9f08778b608fe4f6250e2d132f41b4f99fa8d03051cf2809b1c0420def81b4", size = 595549, upload-time = "2026-11-04T00:30:02.693Z" }, - { url = "https://files.pythonhosted.org/packages/91/ac/674d5c512c196c3ff2c37b27ce87764e9e69c7591902ef48330ff0ebfc07/pyzmq-27.3.0-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:81fcd4e798f384a158b1790171a63541e66ccdee5a139a4dd0848a6e88dc7b9e", size = 1143291, upload-time = "2026-11-04T00:30:04.411Z" }, - { url = "https://files.pythonhosted.org/packages/c1/eb/6bf15cb88fb5d9f8fe6ee6b57185c110f862b6bc1ad02772767571bd3c5c/pyzmq-27.3.0-cp315-cp315-android_24_x86_64.whl", hash = "sha256:e9b87a6f40b62c7cd47691fc2ba4fdc28bef58f5fccf48eaf39940d183d2a16c", size = 1181899, upload-time = "2026-11-04T00:30:05.993Z" }, - { url = "https://files.pythonhosted.org/packages/2c/bc/e00cf032d751a709e12d71c3e2e265957bfb0097d8d071fae4f6a45e2d4c/pyzmq-27.3.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:23ddfe5d4d0c6ea529614c8999065d609a113f343c7e60dda9746d7dcb00d766", size = 1270101, upload-time = "2026-11-04T00:30:07.977Z" }, - { url = "https://files.pythonhosted.org/packages/20/aa/87ebb4664bb27fa53382d45f21f9f49d6194c0eb6737d7c2c5d5e921f1ee/pyzmq-27.3.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b437cf437fe737e17082625f470258f12e4bf5d56edfb88cb21d3aa4089fcef9", size = 779378, upload-time = "2026-11-04T00:30:10.504Z" }, - { url = "https://files.pythonhosted.org/packages/c1/85/e998ff27a29aca9b0f8529e32b0913420e75f8f990a54ad9434faa3d4c5e/pyzmq-27.3.0-cp315-cp315t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc2cc98f37a14a3c9baccc18173a9fca9c6d18ffb233bca7079e58b2e47ee7f8", size = 864317, upload-time = "2026-11-04T00:30:12.259Z" }, - { url = "https://files.pythonhosted.org/packages/d6/7a/6535a0b2fbde9554291caeb3c41b6452207ed7afeb910af830f48e6731f5/pyzmq-27.3.0-cp315-cp315t-manylinux_2_28_i686.whl", hash = "sha256:1a1e092726596141e8ad2cc7f542fd366ddd692b8a9e254d2972ac47b399b982", size = 926240, upload-time = "2026-11-04T00:30:13.862Z" }, - { url = "https://files.pythonhosted.org/packages/51/6f/0c3b1b621f17ebd3eaa2c974b11507dc88cef529ebdc72b42935d00e4a90/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:0c9c332883373eb85b72f4d912a9a4402ba7702709fa783d3c76ff2bd703a491", size = 1771499, upload-time = "2026-11-04T00:30:15.471Z" }, - { url = "https://files.pythonhosted.org/packages/e1/a5/b753eb9acc131fbb4da67c4c68037965f12f8782d1fd5e461e803e0a1dc1/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:1f724caa222b1ae3c48f7d25147c816c8bde56fb109c164a650f0502b9005ab6", size = 2074632, upload-time = "2026-11-04T00:30:17.149Z" }, - { url = "https://files.pythonhosted.org/packages/d1/ad/8bce8d0ff0f0cc0958bdfeebbde9ee319cbd025c949607ab2864df657ce6/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:129ca693e543940527e105144dcacdf9e0ec01d41421098e08893de8227aca58", size = 1903559, upload-time = "2026-11-04T00:30:19.142Z" }, - { url = "https://files.pythonhosted.org/packages/fd/25/e5b3e6a066b59840cdc0ea6de8244b1a50b5f237edc7b7adc0e085973708/pyzmq-27.3.0-cp315-cp315t-win32.whl", hash = "sha256:39b9ff1fbab854ccbc53da0e79cb6b78b61b470fb7c191b89aa034825ea9a883", size = 596443, upload-time = "2026-11-04T00:30:20.811Z" }, - { url = "https://files.pythonhosted.org/packages/3f/c8/20ecc504500aeaab0440a4c8487a3c1cd32f4ac38f3e92482f1671fcaeca/pyzmq-27.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:3b850eaa955ae7edb926fe266600e57da818255d1f6ee9c3d8049967aa4a22cc", size = 684767, upload-time = "2026-11-04T00:30:22.784Z" }, - { url = "https://files.pythonhosted.org/packages/e8/5d/33c528d9b7ee074d0807e3af1a23a3e50bfdbe28cbc178e99f0466c13648/pyzmq-27.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:f0b9d192b285a9d38e390e762011f2672432742a301859b6c8cb4fab5f10f687", size = 594143, upload-time = "2026-11-04T00:30:24.33Z" }, - { url = "https://files.pythonhosted.org/packages/53/53/6ea90b8bb4c77bcc4babd15ef6a63ed243cfd47920cb270da5f29438d11f/pyzmq-27.3.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:cff2031014f79b213818b6773253cbf330119c93de33ee1a635596f407da5c35", size = 689536, upload-time = "2026-11-04T00:31:12.423Z" }, - { url = "https://files.pythonhosted.org/packages/a1/9e/699898cdd86e4cd4bc20547b9f1bce24c58900f51e6a9d5fad03c2890407/pyzmq-27.3.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:18da98ce26045ef503b42a3f98fc2a2af0cdb2af87dc0594852fa5cea3795427", size = 632027, upload-time = "2026-11-04T00:31:14.338Z" }, - { url = "https://files.pythonhosted.org/packages/a6/59/5d6ccce5456cafbdf84c98141d3ddf6c073716eb7b958254349e047fad84/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13c7336a4112d3e09c5d78d17e17af1cd01da858ec1c5e3755b2d06339aa7d4f", size = 684300, upload-time = "2026-11-04T00:31:15.891Z" }, - { url = "https://files.pythonhosted.org/packages/b4/37/c4cf124d820495c5549b3f606b1292949c9e2053467309a7e1baaf0c3784/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e1358fabf41920d69cab170495b6e263680797ac5b80ace1b5cf1eb2d89642", size = 761485, upload-time = "2026-11-04T00:31:17.817Z" }, - { url = "https://files.pythonhosted.org/packages/a7/cf/caa0bd5f7a1b139b9240faf3b34586867656f682774364101572e8e84f80/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_28_i686.whl", hash = "sha256:cdb5efd4c23465573e928fb8429e40996ac0e1a4809365efe19e2753112b6ee1", size = 821382, upload-time = "2026-11-04T00:31:19.451Z" }, - { url = "https://files.pythonhosted.org/packages/8e/34/81fa1d9701024eb4f48949ba5f93da3a063ab997e0e0c9787ff37f11ecda/pyzmq-27.3.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:1b7ab96158dd50d7e6e430e6e4f744aaccee1df2e9d167ace9e7d2f3e3051712", size = 564187, upload-time = "2026-11-04T00:31:21.486Z" }, -] - [[package]] name = "rapidfuzz" version = "3.14.6" @@ -3301,20 +2767,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/04/a0b0e6324b6384d1ab40feb4d16400af3b3101d38cbd15957edd9d17cbe0/rapidfuzz-3.14.6-cp315-cp315t-win_arm64.whl", hash = "sha256:07c7aa0b1e4b9999a54f9e73317d6743ff85442c8ef7b7fbbe6b190fd37d9e75", size = 1243815, upload-time = "2026-08-30T21:45:31.187Z" }, ] -[[package]] -name = "referencing" -version = "0.37.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "rpds-py" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, -] - [[package]] name = "reportlab" version = "5.0.1" @@ -3343,114 +2795,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] -[[package]] -name = "rpds-py" -version = "2026.9.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/42/68/3bd46b8a5e01d3c2ebdf9c5e9497912e3fe0cde02bac21a7130ca866e403/rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12", size = 63948, upload-time = "2026-10-04T16:32:36.469Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5d/34/a828586ea3329fbb50895b50e9cf98ca3d924a9f41a0b26d443bff1b3794/rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af", size = 346822, upload-time = "2026-10-04T16:29:16.258Z" }, - { url = "https://files.pythonhosted.org/packages/90/81/ac6a0d064982251856ce009c9e1dd51a34110b3c055aa7d1aad18b4899a3/rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b", size = 341380, upload-time = "2026-10-04T16:29:17.706Z" }, - { url = "https://files.pythonhosted.org/packages/42/ff/bf7d54f362748fd6a49277b9d6531c394074110fedf50ad791ec59133fbb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a", size = 373053, upload-time = "2026-10-04T16:29:19.063Z" }, - { url = "https://files.pythonhosted.org/packages/60/de/74b0ccdbbd28687b9b5fdb34c1cabed88352182facaced9d6f5486b8b9ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07", size = 377742, upload-time = "2026-10-04T16:29:20.543Z" }, - { url = "https://files.pythonhosted.org/packages/c2/6d/b979775a3057b2a5c26d75ecbff60a20a24ef081db6dd76836fca3f20247/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69", size = 487289, upload-time = "2026-10-04T16:29:21.958Z" }, - { url = "https://files.pythonhosted.org/packages/1d/5d/7c34734ce3ece943d9d6ee0122a74a21bbc75b47acb5b7053c83f6efb1ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d", size = 390710, upload-time = "2026-10-04T16:29:23.378Z" }, - { url = "https://files.pythonhosted.org/packages/1d/6d/b26eb1e75395925b3a142ed351cbed2ec8212f5c9d937aee3df32c701baa/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab", size = 371261, upload-time = "2026-10-04T16:29:25.1Z" }, - { url = "https://files.pythonhosted.org/packages/7c/98/b2fdfe10301a9e27af21e634337fbba7baac0bc17fe44619a17c26bba2cb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e", size = 376075, upload-time = "2026-10-04T16:29:26.748Z" }, - { url = "https://files.pythonhosted.org/packages/c5/b1/c4b8d954e49c3c69cf8063c0c9e0919c99f3d2cecc46311606a1cbe835dc/rpds_py-2026.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237", size = 399358, upload-time = "2026-10-04T16:29:28.282Z" }, - { url = "https://files.pythonhosted.org/packages/b3/59/9559a7293c97dff0cbb293efffbd36644103883ecc27741af8ef90c84ca8/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3", size = 550267, upload-time = "2026-10-04T16:29:29.851Z" }, - { url = "https://files.pythonhosted.org/packages/6c/9d/6dc60e49511de4c8b00e74f9c1d43aed4d27f712cdb1ade92f2c199cbf64/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc", size = 614018, upload-time = "2026-10-04T16:29:31.54Z" }, - { url = "https://files.pythonhosted.org/packages/fb/bc/92a4ecf27301b886232a413360f6b348a81d55ffef654f2ebda5970ebc3d/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6", size = 578509, upload-time = "2026-10-04T16:29:33.01Z" }, - { url = "https://files.pythonhosted.org/packages/08/53/efb97f2e6589b7ab8394385a73870e0b2ab2a195281c117b21fd6d7d4855/rpds_py-2026.9.1-cp312-cp312-win32.whl", hash = "sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3", size = 205401, upload-time = "2026-10-04T16:29:34.451Z" }, - { url = "https://files.pythonhosted.org/packages/1c/84/1700cc748d0eaa747486e4e82882d2575224e6e9a3148df583058850c629/rpds_py-2026.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f", size = 222923, upload-time = "2026-10-04T16:29:35.709Z" }, - { url = "https://files.pythonhosted.org/packages/c3/89/0302215373c2f8b4408b0fdfee955368cc378a98ff59508d47a7e0dc2dbf/rpds_py-2026.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02", size = 218415, upload-time = "2026-10-04T16:29:37.263Z" }, - { url = "https://files.pythonhosted.org/packages/83/ea/ee88fd9e756ff93fb6b1182a47ec09504a242620e33ce1d20679efefe841/rpds_py-2026.9.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9", size = 346229, upload-time = "2026-10-04T16:29:38.82Z" }, - { url = "https://files.pythonhosted.org/packages/57/71/a097d6552f837500fc36e6b23d09cfb9890c3cc47531f9ca64e149799615/rpds_py-2026.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858", size = 340514, upload-time = "2026-10-04T16:29:40.405Z" }, - { url = "https://files.pythonhosted.org/packages/bd/b7/497e85768bf4e0d8ddbaa096a4cac31d1509251dee2728a8490aa367e0b5/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063", size = 372611, upload-time = "2026-10-04T16:29:41.778Z" }, - { url = "https://files.pythonhosted.org/packages/52/4b/74ab4108916250b6e198e0d3af05bc6835eb046315f22f7a0ceb49667c5a/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025", size = 377712, upload-time = "2026-10-04T16:29:43.242Z" }, - { url = "https://files.pythonhosted.org/packages/0c/8e/067e77d9d7b3cc793c9d909b7e97e7aadbbb1fb094093b6876902cc96d38/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5", size = 488106, upload-time = "2026-10-04T16:29:44.692Z" }, - { url = "https://files.pythonhosted.org/packages/3c/b4/c5aae6c2dde269bf955f6b7d35065c655a57e47750d9668052ad67e74dda/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0", size = 390795, upload-time = "2026-10-04T16:29:46.129Z" }, - { url = "https://files.pythonhosted.org/packages/a0/36/76fab39973ee11e7f9f357c55138197bb01c86f6502cb76487e3b4f42db0/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b", size = 370794, upload-time = "2026-10-04T16:29:47.603Z" }, - { url = "https://files.pythonhosted.org/packages/3d/fe/cd2a80e6d7b871937a60e935c5d507aa390d143f4ff3636f640b9733d5df/rpds_py-2026.9.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33", size = 375673, upload-time = "2026-10-04T16:29:49.223Z" }, - { url = "https://files.pythonhosted.org/packages/6c/18/7464a9953724e55a3b3206062fa0ffdeaa519584c6aabf65d3956d94f131/rpds_py-2026.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83", size = 398758, upload-time = "2026-10-04T16:29:50.601Z" }, - { url = "https://files.pythonhosted.org/packages/c0/86/1534b436700fd49ff411063b7c4d7e938adfabf90895b6cf1622d5a7d1f6/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c", size = 550370, upload-time = "2026-10-04T16:29:52.002Z" }, - { url = "https://files.pythonhosted.org/packages/57/1c/e1fa82a8a01e3c5820f3ba98a8b2673f642128eb368fa88871b01dd2c909/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36", size = 613106, upload-time = "2026-10-04T16:29:53.655Z" }, - { url = "https://files.pythonhosted.org/packages/29/55/b20b8c4c3dde8755bfcd5b08492a02d0cd2e26929aedf6199ca2a377d42a/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d", size = 578235, upload-time = "2026-10-04T16:29:55.157Z" }, - { url = "https://files.pythonhosted.org/packages/55/42/df3f7bbc3f7ab37a8a9db8d6c2ff2c985422899f1f7926afbf7ec3c0b8b4/rpds_py-2026.9.1-cp313-cp313-win32.whl", hash = "sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c", size = 205293, upload-time = "2026-10-04T16:29:56.669Z" }, - { url = "https://files.pythonhosted.org/packages/31/9c/ba5a9569d719bfdd6ce863df4133ac6a1658cf1b07cc3534c31db729fbbc/rpds_py-2026.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9", size = 222409, upload-time = "2026-10-04T16:29:58.049Z" }, - { url = "https://files.pythonhosted.org/packages/35/72/f28ca566f6c23c35bbf7445f65eb0364577b25a026305995e24f78b83d94/rpds_py-2026.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f", size = 217681, upload-time = "2026-10-04T16:29:59.449Z" }, - { url = "https://files.pythonhosted.org/packages/8a/f2/67b94be1532767803415c1c5a1fd88ea487643d74a673cec1ba140af77bb/rpds_py-2026.9.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b", size = 347178, upload-time = "2026-10-04T16:30:00.865Z" }, - { url = "https://files.pythonhosted.org/packages/04/37/b751de2b59b0197a1d92a5dd491de88e8a5e928c2e6562581974f1e85263/rpds_py-2026.9.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35", size = 341878, upload-time = "2026-10-04T16:30:02.564Z" }, - { url = "https://files.pythonhosted.org/packages/72/e2/5873bc4643c250db9e05d48dc0c93763d4aa68bc3b81164cb1af3b45b284/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0", size = 373963, upload-time = "2026-10-04T16:30:04.026Z" }, - { url = "https://files.pythonhosted.org/packages/51/03/5acf7632158247f3f6386ff0af3a1ee48167d575037e8d0920594b76d92b/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477", size = 377975, upload-time = "2026-10-04T16:30:05.555Z" }, - { url = "https://files.pythonhosted.org/packages/e6/00/63fda451b8bffa5808fc8bb311ee7c073b340974b09f273c7b2a145d3d62/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4", size = 490347, upload-time = "2026-10-04T16:30:07.156Z" }, - { url = "https://files.pythonhosted.org/packages/a1/ae/c093ffd070ba0fb02f76c565d06fecc65ad6e4afdbae78f7031076d3cdac/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef", size = 392962, upload-time = "2026-10-04T16:30:08.77Z" }, - { url = "https://files.pythonhosted.org/packages/22/9d/d08a1128ab199b2f0cf25bfeb0639bd05119fff4b7c47bec24ef9a8ec23f/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd", size = 371623, upload-time = "2026-10-04T16:30:10.501Z" }, - { url = "https://files.pythonhosted.org/packages/53/c7/4758ddcbb75609414bbccfcb11d612436f9b3ee821bd2f33f0f1604ee648/rpds_py-2026.9.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35", size = 376997, upload-time = "2026-10-04T16:30:12.124Z" }, - { url = "https://files.pythonhosted.org/packages/87/e4/947bd7f608ff60faf46dc9d389c3dffd0e3d767d78a0be19978448ef0ce7/rpds_py-2026.9.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86", size = 400169, upload-time = "2026-10-04T16:30:13.804Z" }, - { url = "https://files.pythonhosted.org/packages/4b/35/fe93e020a0543b5670472c18d7e6af3197c08da571240ce1965c84f85c0f/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e", size = 551615, upload-time = "2026-10-04T16:30:15.332Z" }, - { url = "https://files.pythonhosted.org/packages/0d/4f/5d2a0136bb03b2a56a39dc6ff92d58a6e3e53a2e17079238b86228882f16/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785", size = 614655, upload-time = "2026-10-04T16:30:16.92Z" }, - { url = "https://files.pythonhosted.org/packages/09/1c/3f1025aaf70d9bf7272cc41f8b64ee76b48bf01726248138430e16f23b38/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118", size = 579602, upload-time = "2026-10-04T16:30:18.555Z" }, - { url = "https://files.pythonhosted.org/packages/53/0d/5c72e6204f76610608706da32b6b7e11ef7e10317558a7bb15a122e008dc/rpds_py-2026.9.1-cp314-cp314-win32.whl", hash = "sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc", size = 206315, upload-time = "2026-10-04T16:30:20.05Z" }, - { url = "https://files.pythonhosted.org/packages/a4/0b/489d48abbcc7d70cf3fbf662d9d22abf1f4650761c0a9ae05260800800d3/rpds_py-2026.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c", size = 222852, upload-time = "2026-10-04T16:30:21.604Z" }, - { url = "https://files.pythonhosted.org/packages/91/16/bbb05a7e6a10cf79ba639be7f799d770ee15f64175cc61d081b218dd402a/rpds_py-2026.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31", size = 218709, upload-time = "2026-10-04T16:30:23.036Z" }, - { url = "https://files.pythonhosted.org/packages/22/ac/ac507a0a4ec478ca470440a09583db4be5259ba7670aeba0620822f1e57a/rpds_py-2026.9.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e", size = 349596, upload-time = "2026-10-04T16:30:24.558Z" }, - { url = "https://files.pythonhosted.org/packages/e9/f2/817a46b658d5070f477f722c298ee9a24525b0e4017347964146ef5fdd0e/rpds_py-2026.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96", size = 343114, upload-time = "2026-10-04T16:30:26.048Z" }, - { url = "https://files.pythonhosted.org/packages/6c/42/6ade976b13ac1b4cb3bf2eb603f1be2fe74df19a29988d4c2b386be59d6f/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445", size = 374197, upload-time = "2026-10-04T16:30:27.699Z" }, - { url = "https://files.pythonhosted.org/packages/d9/70/77cdf1d3f1a07faabe936016ae623aec7981f73108a8fe7a203ed2e21998/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69", size = 378025, upload-time = "2026-10-04T16:30:29.451Z" }, - { url = "https://files.pythonhosted.org/packages/3f/6b/18a44a3beaa9b7931acb04af7bd9539836477c630a794452d4826d6185d4/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495", size = 491969, upload-time = "2026-10-04T16:30:30.995Z" }, - { url = "https://files.pythonhosted.org/packages/73/27/fb39cfd6bddaf741b024f813890374578ff8ac1f1adc473659c048b03b05/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c", size = 393905, upload-time = "2026-10-04T16:30:32.628Z" }, - { url = "https://files.pythonhosted.org/packages/ed/71/0fa7bb77b57af0d710273964180d11b503f62b8a5c358eb2d8c3f62feff6/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e", size = 374569, upload-time = "2026-10-04T16:30:34.257Z" }, - { url = "https://files.pythonhosted.org/packages/54/22/f41cfac269af3b449513ef1bc3d7f32fde52abbbd2d01c7e76b47743acd9/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346", size = 377482, upload-time = "2026-10-04T16:30:35.997Z" }, - { url = "https://files.pythonhosted.org/packages/b4/fc/312b49006e7f8f9ca5f96647577b8aa6f3df30519c46bd448f5c425af0b2/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299", size = 400040, upload-time = "2026-10-04T16:30:37.76Z" }, - { url = "https://files.pythonhosted.org/packages/cf/a6/18cca7a878dc7fa95165a83343fd4d7b65643fd22e54e47340a451121d5c/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531", size = 551849, upload-time = "2026-10-04T16:30:39.443Z" }, - { url = "https://files.pythonhosted.org/packages/e4/6d/1f5685e20f39604691bdc3c05aaa6b8bd2f954e9e996477adf2376768e33/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb", size = 614842, upload-time = "2026-10-04T16:30:41.231Z" }, - { url = "https://files.pythonhosted.org/packages/c6/25/98652109fd9f7e10268dd4571aa52b81987001b806f37ef1a18260de714a/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa", size = 582606, upload-time = "2026-10-04T16:30:43.345Z" }, - { url = "https://files.pythonhosted.org/packages/19/03/11ca09099bab5f53373a80a334c424ec917c13d050760a59499d2af5171e/rpds_py-2026.9.1-cp314-cp314t-win32.whl", hash = "sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569", size = 203341, upload-time = "2026-10-04T16:30:44.954Z" }, - { url = "https://files.pythonhosted.org/packages/6f/8a/88909e3ffd9f47f5b58211473875d8c3c09079f0058c46fb72c55a702a26/rpds_py-2026.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e", size = 222843, upload-time = "2026-10-04T16:30:46.486Z" }, - { url = "https://files.pythonhosted.org/packages/f6/b7/a662f367d4896dd0a10cef2fc91f10b7f08af1c10858e287e019563f338d/rpds_py-2026.9.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9", size = 347463, upload-time = "2026-10-04T16:30:48.203Z" }, - { url = "https://files.pythonhosted.org/packages/ae/3f/ad45d03df4f84ebae5439577ee81f3999d182711e82235c8037b6528890e/rpds_py-2026.9.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25", size = 342051, upload-time = "2026-10-04T16:30:49.872Z" }, - { url = "https://files.pythonhosted.org/packages/7e/31/3dcd68c13d4bcc59c1f7eb33ac8e80698f06f3eb0d8a1e06419836071c20/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871", size = 374143, upload-time = "2026-10-04T16:30:51.508Z" }, - { url = "https://files.pythonhosted.org/packages/cf/0d/68c1f058a250fbd1380ebda9fc227cbf50117adf8ffe8161ef383ea79f68/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91", size = 378604, upload-time = "2026-10-04T16:30:53.206Z" }, - { url = "https://files.pythonhosted.org/packages/d7/d6/2d4c59b85397cb4800594fadf692688ccf5ce556adc930e7a5bf21061a5e/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f", size = 490790, upload-time = "2026-10-04T16:30:54.925Z" }, - { url = "https://files.pythonhosted.org/packages/da/04/7e05dc3aebaf52f4e026766bd668fdd09a9d0e23f64a14686b36b3501892/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d", size = 393146, upload-time = "2026-10-04T16:30:56.625Z" }, - { url = "https://files.pythonhosted.org/packages/57/ca/e2e9a0a46a74ed51a0498ba1fe10f4ea6b2d9a155f372a2f91e51f18cf10/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945", size = 372022, upload-time = "2026-10-04T16:30:58.295Z" }, - { url = "https://files.pythonhosted.org/packages/ba/cb/8f8774df5134e23424372838bcc5c7ed4127d723e1ff52f7bebd4dcb2563/rpds_py-2026.9.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297", size = 377092, upload-time = "2026-10-04T16:30:59.984Z" }, - { url = "https://files.pythonhosted.org/packages/90/02/8d7095d73bf9114219be40230baa5df00611e0a82ed9517779ff9c19f82b/rpds_py-2026.9.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0", size = 400830, upload-time = "2026-10-04T16:31:01.721Z" }, - { url = "https://files.pythonhosted.org/packages/ec/02/8206856f8f363cd042a8315dc86b3912f5dcb6d3c66bbb24b69c2bfb0775/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9", size = 551478, upload-time = "2026-10-04T16:31:03.472Z" }, - { url = "https://files.pythonhosted.org/packages/41/6b/36211f1bb1f0b0313f496d92f5905b74ea107f27cb16fa3355a82f04575e/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6", size = 615173, upload-time = "2026-10-04T16:31:05.281Z" }, - { url = "https://files.pythonhosted.org/packages/35/77/cda0c4a6f055446b692f0ed5692f73707cafd3dff82672ede31b1a9b59de/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7", size = 579653, upload-time = "2026-10-04T16:31:07.065Z" }, - { url = "https://files.pythonhosted.org/packages/74/ec/d8385f446240aed643b9e92a5055cff3015cc04a13c61f73b2883c478ed5/rpds_py-2026.9.1-cp315-cp315-win32.whl", hash = "sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429", size = 206498, upload-time = "2026-10-04T16:31:08.989Z" }, - { url = "https://files.pythonhosted.org/packages/6d/a5/71b5cd00e0521e3b6b81828baea368c62b6b700ebdd9554cd7d41ddf12fa/rpds_py-2026.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15", size = 223121, upload-time = "2026-10-04T16:31:10.84Z" }, - { url = "https://files.pythonhosted.org/packages/33/58/dba857c3bc8221b31b62eb170a3080f4f191de79f047200389b7ed1b06a7/rpds_py-2026.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009", size = 218741, upload-time = "2026-10-04T16:31:12.592Z" }, - { url = "https://files.pythonhosted.org/packages/5b/d0/320ab28ccc1415eeb509d68682b0014fb74690cd49f1c2d29a232475af50/rpds_py-2026.9.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0", size = 349719, upload-time = "2026-10-04T16:31:14.48Z" }, - { url = "https://files.pythonhosted.org/packages/56/88/f5b12f1358f443c08b7ce3cc8391d82d335f4872580e2e097847fd36087a/rpds_py-2026.9.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a", size = 343267, upload-time = "2026-10-04T16:31:16.827Z" }, - { url = "https://files.pythonhosted.org/packages/f7/0c/c765b0059d532acb3b9c45d781ccc22f15a96dbe443d00903f643ba9df10/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d", size = 374555, upload-time = "2026-10-04T16:31:18.931Z" }, - { url = "https://files.pythonhosted.org/packages/6b/8a/cafddfda77564a10cd21184640c3bffda6a2b8d20972fb5dedd5e0166328/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db", size = 378346, upload-time = "2026-10-04T16:31:20.75Z" }, - { url = "https://files.pythonhosted.org/packages/b9/01/5e626016eff72c183bf6c96539240cace15d402468647a453ec08415b2fc/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250", size = 492373, upload-time = "2026-10-04T16:31:22.614Z" }, - { url = "https://files.pythonhosted.org/packages/3b/9c/15a2469e9389242f46896b3f0a01d68caea8a5a35c011fcb05ef333aae73/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f", size = 394371, upload-time = "2026-10-04T16:31:24.768Z" }, - { url = "https://files.pythonhosted.org/packages/63/f5/c100ff77e1e6366e947c75969c258fdfc4b7bc5bbfe7351e62ffbf2a1228/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018", size = 375132, upload-time = "2026-10-04T16:31:26.588Z" }, - { url = "https://files.pythonhosted.org/packages/dd/f4/fe0269c9de253e99c81cabc12b8971a5feaa083debdaff1221e06264d9e3/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d", size = 377642, upload-time = "2026-10-04T16:31:28.677Z" }, - { url = "https://files.pythonhosted.org/packages/05/65/b34a7b257baccff8f4a24a722933166d4941d5ebdc9c3f4bc4ffcd5ce4f4/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b", size = 400855, upload-time = "2026-10-04T16:31:30.802Z" }, - { url = "https://files.pythonhosted.org/packages/98/32/844e54176b6071b90b38a564e6940bc6eb8f97b2890dc709c19db9dec0f4/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6", size = 552573, upload-time = "2026-10-04T16:31:32.709Z" }, - { url = "https://files.pythonhosted.org/packages/17/73/6041d20729dffbfdf155c02d65be58bc225a1c1fb548fd87c23ef306138f/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad", size = 615840, upload-time = "2026-10-04T16:31:34.565Z" }, - { url = "https://files.pythonhosted.org/packages/af/9e/418094adaee6b056ce199051b255448ed872829051e341b2294c80da0977/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903", size = 582764, upload-time = "2026-10-04T16:31:36.665Z" }, - { url = "https://files.pythonhosted.org/packages/3d/9b/1698ebf6b840ddfe8b472198abbed6ace35c6e398faeecd6c47dae742a4e/rpds_py-2026.9.1-cp315-cp315t-win32.whl", hash = "sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b", size = 203795, upload-time = "2026-10-04T16:31:38.53Z" }, - { url = "https://files.pythonhosted.org/packages/8a/e2/91f70d804c61f8eac39a417e82aa1024f655ab9e8bdd7393b196242bc41b/rpds_py-2026.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567", size = 223037, upload-time = "2026-10-04T16:31:40.468Z" }, - { url = "https://files.pythonhosted.org/packages/a3/90/a9ba81408369d34c1aca73319c15adc91ed45c1d21e9e8ee4832ffb7fe0b/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4", size = 381109, upload-time = "2026-10-04T16:32:08.994Z" }, - { url = "https://files.pythonhosted.org/packages/b3/44/5192a0bed94cec86bd2a5e1cc5a1bb8f7eec3aec907eacd2deb13e87e326/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759", size = 388222, upload-time = "2026-10-04T16:32:11.321Z" }, - { url = "https://files.pythonhosted.org/packages/92/cd/5356549711448f18b52f7a11ffbe90f1228774996fbf3c6cd1b18d22abaf/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb", size = 500384, upload-time = "2026-10-04T16:32:13.478Z" }, - { url = "https://files.pythonhosted.org/packages/7a/88/ddda9d28adfe33119c75b2e733d4ba7e326f41d7e1b1093951771768ca48/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82", size = 401661, upload-time = "2026-10-04T16:32:15.653Z" }, - { url = "https://files.pythonhosted.org/packages/32/c3/bb59ba16a6b4a57995d15b8c04c00f28df3b938c4dcdde48fbe0f73edb0c/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c", size = 380748, upload-time = "2026-10-04T16:32:17.727Z" }, - { url = "https://files.pythonhosted.org/packages/f5/b8/0580faa1c5a32ddc160130dd7ae54d2d007272a89a40a6b5db3e50f9f585/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14", size = 385731, upload-time = "2026-10-04T16:32:19.855Z" }, - { url = "https://files.pythonhosted.org/packages/bf/70/f73564642bbe3322c7eeef2c2f258cf040b71c41a430b532e59d04a1b838/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c", size = 412131, upload-time = "2026-10-04T16:32:22.285Z" }, - { url = "https://files.pythonhosted.org/packages/8c/5d/17fff2e1f8f68721a2afb5cb48f7e442c751bb6b4883157c5abaf618cd08/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68", size = 558193, upload-time = "2026-10-04T16:32:24.4Z" }, - { url = "https://files.pythonhosted.org/packages/2a/d0/869ab6fb08531f97aae4a780b4d61b4190d8aef48fe054ee28bcf7114466/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_i686.whl", hash = "sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da", size = 622448, upload-time = "2026-10-04T16:32:26.844Z" }, - { url = "https://files.pythonhosted.org/packages/ba/a5/9672e532fe02cd3b92c78cfd8743abca939d96853006c63835009a1ecb6f/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448", size = 591126, upload-time = "2026-10-04T16:32:29.274Z" }, - { url = "https://files.pythonhosted.org/packages/80/ef/3a9f8e4279c7920af561deed4cb7ebebed2794a8f608cf404d5eef14a105/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0", size = 357108, upload-time = "2026-10-04T16:32:31.641Z" }, - { 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-learn" version = "1.9.1" @@ -3607,15 +2951,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, ] -[[package]] -name = "soupsieve" -version = "4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/95/48/21a393ff731b8f928fa4f8176f9a7ceba2252ee60a5149f25b45c292aa5c/soupsieve-4.1.tar.gz", hash = "sha256:ca9abf7126667010d8f6e9b39bfc1bc3b23c8aed9bcb0f54a754dde969bb8aab", size = 161955, upload-time = "2026-11-10T01:59:50.399Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/88/73/6a2087c72975cfc07394623bca8d17654342ea4055ae368deafe5a81a542/soupsieve-4.1-py3-none-any.whl", hash = "sha256:e4d667b3974ce6e038e7390486b8093369854a1d345ffdd4c121dfc4a782e809", size = 52302, upload-time = "2026-11-10T01:59:48.571Z" }, -] - [[package]] name = "sqlalchemy" version = "2.0.54" @@ -3657,18 +2992,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/a1/bd5e3e99bc9c8863b51ac5b9b03008a7f2da8c6b59695992f5c654e1265b/sqlalchemy-2.0.54-py3-none-any.whl", hash = "sha256:7e33a631ab1474f8fe6b910bd1a07b7b8009c4c78cdd3fb18001b03e3bc2e1d2", size = 1958015, upload-time = "2026-09-15T22:24:22.95Z" }, ] -[[package]] -name = "sqlalchemy-utils" -version = "0.42.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "sqlalchemy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/7d/eb9565b6a49426552a5bf5c57e7c239c506dc0e4e5315aec6d1e8241dc7c/sqlalchemy_utils-0.42.1.tar.gz", hash = "sha256:881f9cd9e5044dc8f827bccb0425ce2e55490ce44fc0bb848c55cc8ee44cc02e", size = 130789, upload-time = "2025-12-13T03:14:13.591Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/25/7400c18c3ee97914cc99c90007795c00a4ec5b60c853b49db7ba24d11179/sqlalchemy_utils-0.42.1-py3-none-any.whl", hash = "sha256:243cfe1b3a1dae3c74118ae633f1d1e0ed8c787387bc33e556e37c990594ac80", size = 91761, upload-time = "2025-12-13T03:14:15.014Z" }, -] - [[package]] name = "sqlglot" version = "30.27.0" @@ -3701,20 +3024,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d9/50/f00935da0ec7cbf325f8dc4f772ae46fbc7b672dd62876e73f0a94adda57/sqlparse-0.6.0-py3-none-any.whl", hash = "sha256:b861c0288ce2fa56209a9a6412d2e066ac664b3873b89c26c9d8415e8e32996f", size = 50070, upload-time = "2026-08-13T19:16:04.062Z" }, ] -[[package]] -name = "stack-data" -version = "0.6.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "asttokens" }, - { name = "executing" }, - { name = "pure-eval" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" }, -] - [[package]] name = "starlette" version = "1.9.0" @@ -3737,68 +3046,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/43/3f/f88a53f60a472b46f4023f56d204dd7de33d34c5d2acbfa0d70a674e639e/threadpoolctl-3.7.0-py3-none-any.whl", hash = "sha256:cd8b60b5641b45c67bbf73c64c843235fc2d8a480c87389f52f5dbee893b86be", size = 26362, upload-time = "2026-09-15T15:46:19.168Z" }, ] -[[package]] -name = "tinycss2" -version = "1.5.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "webencodings" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/ae/2ca4913e5c0f09781d75482874c3a95db9105462a92ddd303c7d285d3df2/tinycss2-1.5.1.tar.gz", hash = "sha256:d339d2b616ba90ccce58da8495a78f46e55d4d25f9fd71dfd526f07e7d53f957", size = 88195, upload-time = "2025-11-23T10:29:10.082Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/60/45/c7b5c3168458db837e8ceab06dc77824e18202679d0463f0e8f002143a97/tinycss2-1.5.1-py3-none-any.whl", hash = "sha256:3415ba0f5839c062696996998176c4a3751d18b7edaaeeb658c9ce21ec150661", size = 28404, upload-time = "2025-11-23T10:29:08.676Z" }, -] - -[[package]] -name = "tornado" -version = "6.6.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/64/2b/8ff2b41620cbba0eeb0862fed21dcaa5a2ad36c6dd9bb465f9ff7a147be2/tornado-6.6.1.tar.gz", hash = "sha256:28e6311402af59c8b02e3fa0f5e7d8eb465b25081381803b127d97e6a4395d5a", size = 623388, upload-time = "2026-11-09T21:09:22.71Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/d3/ef3a4d38d1a72c52ad07483ed760dbb93027d28f19c3a2d98148abdd63e1/tornado-6.6.1-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:a8d3e6acde5a80d13b13b5e4c7c226ca682f31d0a62b6c33cea038714bc2de1b", size = 533249, upload-time = "2026-11-09T21:08:22.475Z" }, - { url = "https://files.pythonhosted.org/packages/38/4d/c65ea949a3cdc185f1afac8c337074d4f2d029b48293d2db4d2c3dea4849/tornado-6.6.1-cp311-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1b6ff57cc69b339f8feb9e7b567b0e0eacb16bfaf234159496623ef7a67ba640", size = 534470, upload-time = "2026-11-09T21:08:24.27Z" }, - { url = "https://files.pythonhosted.org/packages/03/ff/20911f85dd399b56761496e8138810e8608ea25f0912377f4205d52af853/tornado-6.6.1-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da6ce2da215810d56539fa6cac77d9e27f4d8139c6868c53436b2fe933f43c79", size = 535446, upload-time = "2026-11-09T21:08:25.625Z" }, - { url = "https://files.pythonhosted.org/packages/be/70/a4a159dd4f1fef39ff8eadae655b133a85722b39087a89e21ce463af9832/tornado-6.6.1-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8cd28b2cacbe63d53e28a38546a3492b488417eeb3f7ecf10954476fc2508882", size = 535664, upload-time = "2026-11-09T21:08:27.191Z" }, - { url = "https://files.pythonhosted.org/packages/ed/d5/db70d5d23d3b4eaea0b26b710f28d2ca387bb44e68ccfede60ba3bbc2096/tornado-6.6.1-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:25b2619274bca77d0eb7b4d96dcf2d1142bb9bf172ad6a7491a1e1f82e6e48fa", size = 534660, upload-time = "2026-11-09T21:08:28.78Z" }, - { url = "https://files.pythonhosted.org/packages/f7/f6/0528ee039266902e707edd9996ee3ce7364dc1baf08bed585d8e6fb3ccd0/tornado-6.6.1-cp311-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:77dd6e0c659fdc45824e0746988ac5c060c2a9fee9b8cbbcdb999b3f29d3cd10", size = 532834, upload-time = "2026-11-09T21:08:30.432Z" }, - { url = "https://files.pythonhosted.org/packages/a6/bb/b733df2d487a78283080663bd6d96955121b58b6d445d9cb832607da9786/tornado-6.6.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b62fded687e55acaf9e36c1230b006066a35b3f6df093ba1fd3b2ff592070e1d", size = 535289, upload-time = "2026-11-09T21:08:31.692Z" }, - { url = "https://files.pythonhosted.org/packages/a7/7c/c81cb83f2bbb5740fcba1eb83d794b6d6fab2063b16a475cc9039266091e/tornado-6.6.1-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:ecef88054d8a77878f61061ff67dfc5e1c17d1f7334890ab508b310e8e68ee46", size = 535382, upload-time = "2026-11-09T21:08:33.282Z" }, - { url = "https://files.pythonhosted.org/packages/8a/ae/c499da4cc8be1c1f31a5d8df2328f2aae091de2db13302ad5c20ed704ec4/tornado-6.6.1-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:ca95e762df1ca761f330e3f2a034c15ac144569844b52527a5a9eca9f524c0f1", size = 534534, upload-time = "2026-11-09T21:08:34.57Z" }, - { url = "https://files.pythonhosted.org/packages/61/7c/6b163c9e58ca9df0c941bda9ba2dcabbd87ecb81c5fa546f54eeac689232/tornado-6.6.1-cp311-abi3-musllinux_1_2_s390x.whl", hash = "sha256:8cae3d8f2585be01670da9fd5010c61724c51b61ecd4c06820e95874739daf7c", size = 534728, upload-time = "2026-11-09T21:08:35.828Z" }, - { url = "https://files.pythonhosted.org/packages/18/11/b5107ac6a278387635d73d283e7ab5a5c76fb8ccf402efa57006ea25852f/tornado-6.6.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6596f3e939962f13099ce8d1a96b83226e908ca369b193370a6efa84585a1601", size = 534676, upload-time = "2026-11-09T21:08:37.209Z" }, - { url = "https://files.pythonhosted.org/packages/65/df/0574c4479c565d9233def796afc9179fa840f41f8c240f740609f746da67/tornado-6.6.1-cp311-abi3-win32.whl", hash = "sha256:0f0f596a0dab6826aa21d103c7bc242e3fb7cfc99c5c3d44a35ba8c83abbdca4", size = 535565, upload-time = "2026-11-09T21:08:38.518Z" }, - { url = "https://files.pythonhosted.org/packages/36/57/35439a779582e3b19c98e799b6a41519fb3bdaa3a21b7a94ce4dd7b3b732/tornado-6.6.1-cp311-abi3-win_amd64.whl", hash = "sha256:5cb82ca38596e1350fceaf994f287847f82f7b8436380d36ba0937a03107d0ee", size = 535806, upload-time = "2026-11-09T21:08:39.892Z" }, - { url = "https://files.pythonhosted.org/packages/89/b8/2cb42845af01ea7e70ac23e6f6fe2f26b9b158bce186c6991c057c9abe1d/tornado-6.6.1-cp311-abi3-win_arm64.whl", hash = "sha256:58d2f47e7b54fded3407dbbbe4e59d29ca627f85bf6c0f21f0b151c6c7fc9c53", size = 535825, upload-time = "2026-11-09T21:08:41.339Z" }, - { url = "https://files.pythonhosted.org/packages/10/de/cfeae9e75c144ca22018ee3b858e343c1658d6edd2184f35d810ec1ef789/tornado-6.6.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ed0bc5a1a9f6346e7bdadc106fa2d4c6e79d71d8b2df4366260ab3baf36a8399", size = 533356, upload-time = "2026-11-09T21:08:42.603Z" }, - { url = "https://files.pythonhosted.org/packages/3d/d8/7812a729c797fb8c15748c9a69faeaaa13630075cf9b76ba9f7fbcfb7f42/tornado-6.6.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:54c80f9bed0bf1533ecf5a90dc59651645622d62b0bcffa2692d108a1f794917", size = 537511, upload-time = "2026-11-09T21:08:43.84Z" }, - { url = "https://files.pythonhosted.org/packages/70/47/ebef304487feea6d8efb6a7d2642964ecb1f5cc785f687628e1d7cac4326/tornado-6.6.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb67ba2cbf598e842f14684eab029a5a4ba7ab587e8c4e40940a77ed0596b31e", size = 538566, upload-time = "2026-11-09T21:08:45.203Z" }, - { url = "https://files.pythonhosted.org/packages/a3/6a/87532e6745c415eb2daa9bc1c9c89c69ce9e8255b1c0bde9938f3299440b/tornado-6.6.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d83bac141bd9360d8e995ec512097be19ead2e9213c3e7088510a036f3192b8d", size = 538793, upload-time = "2026-11-09T21:08:46.478Z" }, - { url = "https://files.pythonhosted.org/packages/e4/c7/26af60f71f7c32f19257bad58711500628f579edf1a2c3d8328ad15aae04/tornado-6.6.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:60aad449dbcebaa8d69bff50c6ba39858fab8d256e779a99bb30ebf6724b9b48", size = 537691, upload-time = "2026-11-09T21:08:47.975Z" }, - { url = "https://files.pythonhosted.org/packages/ba/9d/af233b8bf4311d3466099ab267eb595ec6f1655607d290dc7f706b6dbd6f/tornado-6.6.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b9ce0d6548bd73b1329075b247d3fdc61538922f558ee42059e08f5df53fc197", size = 535877, upload-time = "2026-11-09T21:08:49.76Z" }, - { url = "https://files.pythonhosted.org/packages/95/66/78e7583ce69f66e5177c65988a98373be2ab25c1d22405d274e037acbc58/tornado-6.6.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ce5a18654f5d56d11400ab5d87103660e14deceab41818a06a42acc8dbbe427d", size = 538295, upload-time = "2026-11-09T21:08:51.221Z" }, - { url = "https://files.pythonhosted.org/packages/a3/3a/ad336d4994547cf268a3bd6d10f6ef691e1e888fc776940c0bfe02e8d85c/tornado-6.6.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:3298fce72c35f836eab4c4db8b960104ff1ea718033a6b5e236f04efe3a1b6e1", size = 538349, upload-time = "2026-11-09T21:08:52.761Z" }, - { url = "https://files.pythonhosted.org/packages/cf/cf/563d24516afd266f6b3c3f1c7ac15ad39b8668966d2bccce917c169ab0c0/tornado-6.6.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:0223e827cedf4e35ebb035e57a0d9974563cd043e3a53f8bb72a859b6f53777e", size = 537469, upload-time = "2026-11-09T21:08:54.279Z" }, - { url = "https://files.pythonhosted.org/packages/c8/ea/1705ff4014c8bad5d7045022647156cfebd6c7014886da47e13512d27c08/tornado-6.6.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:533185c89be3ffb01656c9425da4ff42587a3af784b37d39fe762e8fce3b2dbe", size = 537624, upload-time = "2026-11-09T21:08:55.648Z" }, - { url = "https://files.pythonhosted.org/packages/50/5d/421168e62c8b80e3ef88f80d642e9a7e5b1d0c6e8cd136d99064f663951c/tornado-6.6.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fbaa022a49a27b65668592cf43b898ff3978cbe4e6926fdfe24dbef59053bd26", size = 537632, upload-time = "2026-11-09T21:08:57.797Z" }, - { url = "https://files.pythonhosted.org/packages/6a/b4/13b2f98a3141c152915fa3e69531a04bdc1cd7dd203f442136f3792a486f/tornado-6.6.1-cp314-cp314t-win32.whl", hash = "sha256:4bc6c60faf86162df25ba2ff5611d27b6ef8226de9d61c07a0fab53c169630a5", size = 535424, upload-time = "2026-11-09T21:08:59.145Z" }, - { url = "https://files.pythonhosted.org/packages/84/83/6d54c37b3e437ab0ff2bddd71249c6ea2a17051104dd2995cb4e181e95a7/tornado-6.6.1-cp314-cp314t-win_amd64.whl", hash = "sha256:71c16b382b22d3234913a3f74a1ea84bede197d11eb03871df17bb123088dfa5", size = 535715, upload-time = "2026-11-09T21:09:00.456Z" }, - { url = "https://files.pythonhosted.org/packages/d4/38/75419d8cd577b7c4f335f4c5e75f127af286545ad49047a73afffdf877fe/tornado-6.6.1-cp314-cp314t-win_arm64.whl", hash = "sha256:510c7261ed986ecd6f74edc1a13412759e7abc2e8be3a6c85e15f6c53e1f3c84", size = 535718, upload-time = "2026-11-09T21:09:01.783Z" }, - { url = "https://files.pythonhosted.org/packages/91/8b/96e460653f3e2ad83d70328414394132d73d5655047c692ce7b69ae2f6c0/tornado-6.6.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:01dc73e3697eb94d78c42e03931ab621da97d12fdfb6339e64ff5a934b220fcf", size = 533376, upload-time = "2026-11-09T21:09:03.097Z" }, - { url = "https://files.pythonhosted.org/packages/1a/1e/644bace0700e533235f01ffa68a7b5e3d6cc9eb7380e3929039d04b648b9/tornado-6.6.1-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:95bd4751357bef52aa655e236b9667ff054885de4b118e4ce9ba5c06e12ef5d0", size = 537696, upload-time = "2026-11-09T21:09:04.519Z" }, - { url = "https://files.pythonhosted.org/packages/e6/0a/afccc23d1ed71bcb1ce4a5b6e0f61f82c7a0b275f3b377ee7aee6680a565/tornado-6.6.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:29bce3190c2973fcd2171c95eeab8bf06d2f7a7eb107455ce3e4662c704aecdb", size = 538796, upload-time = "2026-11-09T21:09:05.956Z" }, - { url = "https://files.pythonhosted.org/packages/e5/24/69692f8ba851ed2738c2623eab592360d646f0a2e16b6deea16516aa8595/tornado-6.6.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b777fbe0bdb2c4dc764aadf5f70e9b23b2e536c339d61c799d3ea1b575a7c285", size = 538951, upload-time = "2026-11-09T21:09:07.298Z" }, - { url = "https://files.pythonhosted.org/packages/00/82/234306b41b33600a470da7e595b8064b85e2f509f64f5c1d39387c0abbb8/tornado-6.6.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:15443805d6b7aa11610cc6c5be7e71b4a93369aeb2ca5a13c2def53a3af5ba45", size = 537861, upload-time = "2026-11-09T21:09:08.857Z" }, - { url = "https://files.pythonhosted.org/packages/5b/87/6d13a60c320c0379cbfa4c2520b4ba076780c33e6a01ba3073fff74b71db/tornado-6.6.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b77ab23d1520c807d11e703e79b020d3bc3676a0f5ebc8531f46d3fac8aecb2f", size = 536178, upload-time = "2026-11-09T21:09:10.424Z" }, - { url = "https://files.pythonhosted.org/packages/96/c7/e27f2a21e05d7c5aa9886db7368436e6436880b85349072988b4f62422e3/tornado-6.6.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:872249311539281c1e8a5d8d6f27f478bf705a9bd931bf374b6b31b05177dfda", size = 538491, upload-time = "2026-11-09T21:09:11.968Z" }, - { url = "https://files.pythonhosted.org/packages/f3/c7/1f981336039c51d81ee6f895e3412178edc409bd709e38767365c55c0daa/tornado-6.6.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:08b808e8d3312c268f9fe1ffebfcfaaf342e7fe4ac40d219a7e1b58bac547d6f", size = 538491, upload-time = "2026-11-09T21:09:13.226Z" }, - { url = "https://files.pythonhosted.org/packages/5d/4f/7dafc65726778ac148b68c91920605892e84bf0ffcc02890aaf1a7d0ba8d/tornado-6.6.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:8d475f4053c693b5c1483eb4845824129b0b51c65712e736b3c2ea1c8f6080cd", size = 537775, upload-time = "2026-11-09T21:09:14.697Z" }, - { url = "https://files.pythonhosted.org/packages/a1/25/85c852307f9e49896b6dc5119f6a0131f5f6d97c478a687654c2c0c3f0f4/tornado-6.6.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:e923e75c9d641cdb8bbac60070a2dccdb684fc555af2bff48b0eaded0f88c2dc", size = 537798, upload-time = "2026-11-09T21:09:15.946Z" }, - { url = "https://files.pythonhosted.org/packages/60/43/a37ec29b0f98c3c639da495e1d547d6c44c69a6727b9864cf149bf346433/tornado-6.6.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a72f70b1aa630fa2106d39a025e2be75c272b7ec8233da94e2f407ea754cc32d", size = 537809, upload-time = "2026-11-09T21:09:17.265Z" }, - { url = "https://files.pythonhosted.org/packages/3b/d4/13973391071552e03acb308d93f6deb4fb535a769a6bbdafdb4cafcb2f91/tornado-6.6.1-cp315-cp315t-win32.whl", hash = "sha256:2fbfd2510b6163b189773155a8246c025cb260ccc7cd12ad18c36c54f5617bb9", size = 535422, upload-time = "2026-11-09T21:09:18.525Z" }, - { url = "https://files.pythonhosted.org/packages/19/94/c952b625904b63fdac5b747f2eeaca64ab5d36cdb8faff57effa57162d87/tornado-6.6.1-cp315-cp315t-win_amd64.whl", hash = "sha256:3c35091add5863feb9cf651851bb1b23592f1f9551b5dfed72837c83ea4e5b85", size = 535713, upload-time = "2026-11-09T21:09:20.061Z" }, - { url = "https://files.pythonhosted.org/packages/f8/62/8d0c0c42f3346f3f2455738d3bc689bbd8efba38abf7b90ab2b8294eae83/tornado-6.6.1-cp315-cp315t-win_arm64.whl", hash = "sha256:065bc741478b168df9baf754956a3010c04d1330bb45a84833d807c29e11b257", size = 535719, upload-time = "2026-11-09T21:09:21.317Z" }, -] - [[package]] name = "tqdm" version = "4.70.1" @@ -3811,15 +3058,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, ] -[[package]] -name = "traitlets" -version = "5.16.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" } -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 = "typeguard" version = "4.6.0" @@ -3952,8 +3190,7 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "indicadores-kit" }, - { name = "models", extra = ["notebooks"] }, + { name = "models" }, { name = "openpyxl" }, { name = "pandas" }, { name = "pdfplumber" }, @@ -3986,7 +3223,6 @@ requires-dist = [ { name = "flask", specifier = ">=3.0" }, { name = "flask-cors", specifier = ">=4.0" }, { name = "gunicorn", specifier = ">=23.0" }, - { name = "indicadores-kit", editable = "../indicadores_kit" }, { name = "models", extras = ["notebooks"], editable = "../models" }, { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2.0" }, @@ -4010,15 +3246,6 @@ dev = [ { name = "reportlab", specifier = ">=4.0" }, ] -[[package]] -name = "webencodings" -version = "0.6.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d5/a0/8fd707bcb776a7be556bad06a2ea5fb9bd519df78ef8e26f70ccf0f38bff/webencodings-0.6.1.tar.gz", hash = "sha256:565f9ad031c702dae404e27a099e3e09186a3ab1b9520f06d215502b651fd910", size = 15001, upload-time = "2026-08-15T14:22:57.549Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/c6/040cbc72480d789a5f40d63fb484d3106554c4dfa2d2b70ad5022057750f/webencodings-0.6.1-py3-none-any.whl", hash = "sha256:7fab6269c8bf237c657876b52058ccb182e861518d1c695c1a9aaa8c1c105d5b", size = 8745, upload-time = "2026-08-15T14:22:56.31Z" }, -] - [[package]] name = "werkzeug" version = "3.1.8" diff --git a/webapi/__init__.py b/webapi/__init__.py index 3b78629..9a68c32 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -10,7 +10,7 @@ from webapi.blueprints.data import data_bp from webapi.blueprints.governance import governance_bp from webapi.blueprints.imports import imports_bp from webapi.blueprints.reports import reports_bp -from webapi.follow_up import follow_up_blueprint +from webapi.follow_up.routes import follow_up_blueprint class IsoJSONProvider(DefaultJSONProvider): diff --git a/webapi/follow_up/__init__.py b/webapi/follow_up/__init__.py new file mode 100644 index 0000000..3de6541 --- /dev/null +++ b/webapi/follow_up/__init__.py @@ -0,0 +1,7 @@ +"""CaCu's follow-up list (`GET /cacu/seguimiento`): one row per patient, with her ASCCP status and her latest studies. + + routes.py the route: validates the request and answers + listing.py the list: who enters it, what each row shows + status.py the ASCCP status of each patient at a date + silver.py, pivot.py, view.py, functions.py the silver queries they read +""" diff --git a/webapi/follow_up/estratos.toml b/webapi/follow_up/estratos.toml new file mode 100644 index 0000000..f31bcbb --- /dev/null +++ b/webapi/follow_up/estratos.toml @@ -0,0 +1,53 @@ +# Los estratos que un indicador puede declarar en `extension.estratos`. +# Cada uno es una función de SQLAlchemy que devuelve una CTE con +# (unidad_id, estrato); el cálculo la cruza con las poblaciones sin +# tocarlas (mart/estratos.py). +# +# expression "modulo.del.kit:funcion" +# unidad la unidad de los indicadores a los que sirve (`basis`) +# fechas lo que el estrato cruza con dim_fecha, si lo lee +# parametros sus reglas: parámetro de la consulta -> clave de parametros.toml (la +# función las recibe resueltas y entran a la huella del reporte) +# valores sus valores con su etiqueta, en orden, si no salen de otra regla +# etiqueta cómo se llama en pantalla (la leyenda, el selector de filtros); sin ella, su nombre +# +# Sección `comun`: para todos los proyectos; ``: solo ese, y +# gana sobre `comun` si se llaman igual. + +[comun.grupo_edad] +etiqueta = "Grupo de edad" +expression = "comun.estratos.grupo_edad:estrato" +unidad = "paciente" +fechas = { hechos = ["v_persona.fecha_nacimiento"], parametros = ["periodo_inicio"] } + +# Estatus de seguimiento ASCCP de la paciente (T-24c): `cacu/seguimiento.py`. Sus reglas son de +# `parametros.toml` (§2bis) y entran a la huella del reporte. Excluyente y exhaustivo: sin `sin_dato`. +[cacu.estatus_seguimiento] +etiqueta = "Estatus de seguimiento" +expression = "cacu.seguimiento:estrato" +unidad = "paciente" +valores = [ + { valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" }, + { valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" }, + { valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" }, + { valor = "INFO_INSUFICIENTE", etiqueta = "Información insuficiente" }, +] + +[cacu.estatus_seguimiento.parametros] +seguimiento_marco = "cacu.seguimiento.marco" +seguimiento_referencia = "cacu.seguimiento.referencia" +seguimiento_precedencia = "cacu.seguimiento.precedencia" +seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias" +seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito" +seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito" +seguimiento_cie_valoracion = "cacu.diagnostico.cie" +seguimiento_especialidades_valoracion = "cacu.diagnostico.especialidades" +seguimiento_horizonte_valoracion = "cacu.horizontes.toma_diagnostico_dias" +seguimiento_motivos = "cacu.seguimiento.colposcopia.motivos" +seguimiento_especialidades_colposcopia = "cacu.seguimiento.colposcopia.especialidades" +seguimiento_cie_colposcopia = "cacu.seguimiento.colposcopia.cie" +seguimiento_diagnosticos = "cacu.seguimiento.colposcopia.diagnosticos" +seguimiento_fuentes_tratamiento = "cacu.seguimiento.tratamiento.fuentes" +seguimiento_cie_tratamiento = "cacu.seguimiento.tratamiento.cie" +seguimiento_insuficiente = "cacu.seguimiento.insuficiente.regla" +seguimiento_especialidades_vigilancia = "cacu.seguimiento.vigilancia.especialidades" diff --git a/webapi/follow_up/functions.py b/webapi/follow_up/functions.py new file mode 100644 index 0000000..f13fbc4 --- /dev/null +++ b/webapi/follow_up/functions.py @@ -0,0 +1,100 @@ +"""Lo que cada motor escribe distinto, como una función con una regla por motor. + +SQLAlchemy traduce la sintaxis, no las funciones de fecha. Aquí van las +que el kit necesita. Agregar un motor es agregar su regla; ninguna +definición cambia. Sin regla para un motor queda la forma neutra, que es +la que lee el registro de huellas y no se puede ejecutar. Solo la regla +de SQLite se ejecuta en las pruebas (D-S5). +""" + +from sqlalchemy import Integer +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.sql.expression import FunctionElement + + +class dias_entre(FunctionElement): + """Días enteros de `inicio` a `fin`: `dias_entre(inicio, fin)`.""" + + type = Integer() + inherit_cache = True + + +def _partes(elemento, compilador, opciones) -> tuple[str, str]: + inicio, fin = list(elemento.clauses) + return compilador.process(inicio, **opciones), compilador.process(fin, **opciones) + + +@compiles(dias_entre) +def _neutra(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"dias_entre({inicio}, {fin})" + + +@compiles(dias_entre, "sqlite") +def _sqlite(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)" + + +@compiles(dias_entre, "postgresql") +def _postgresql(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))" + + +@compiles(dias_entre, "mysql", "mariadb") +def _mysql(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"DATEDIFF({fin}, {inicio})" + + +@compiles(dias_entre, "mssql") +def _mssql(elemento, compilador, **opciones) -> str: + inicio, fin = _partes(elemento, compilador, opciones) + return f"DATEDIFF(day, {inicio}, {fin})" + + +class entero_de_json(FunctionElement): + """Un entero de un objeto JSON guardado como texto: `entero_de_json(columna, "clave")`. + + PostgreSQL no aplica `->>` a `text` y SQL Server no tiene tipo JSON: cada + motor lee la clave con su propia función. + """ + + type = Integer() + inherit_cache = True + + +def _columna_y_clave(elemento, compilador, opciones) -> tuple[str, str]: + columna, clave = list(elemento.clauses) + return compilador.process(columna, **opciones), clave.value + + +@compiles(entero_de_json) +def _entero_neutro(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"entero_de_json({columna}, '{clave}')" + + +@compiles(entero_de_json, "sqlite") +def _entero_sqlite(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(json_extract({columna}, '$.{clave}') AS INTEGER)" + + +@compiles(entero_de_json, "mysql", "mariadb") +def _entero_mysql(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(JSON_UNQUOTE(JSON_EXTRACT({columna}, '$.{clave}')) AS SIGNED)" + + +@compiles(entero_de_json, "postgresql") +def _entero_postgresql(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(CAST({columna} AS JSON) ->> '{clave}' AS INTEGER)" + + +@compiles(entero_de_json, "mssql") +def _entero_mssql(elemento, compilador, **opciones) -> str: + columna, clave = _columna_y_clave(elemento, compilador, opciones) + return f"CAST(JSON_VALUE({columna}, '$.{clave}') AS INT)" diff --git a/webapi/follow_up/listing.py b/webapi/follow_up/listing.py new file mode 100644 index 0000000..fde56f0 --- /dev/null +++ b/webapi/follow_up/listing.py @@ -0,0 +1,296 @@ +"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, una fila por paciente. + +El contrato es T-24a. Es una consulta al +vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada paciente con al menos un +estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su +grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del +estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas +de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula. + +**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta +lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal. + +Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento` +de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna. +""" + +import calendar +import hashlib +import json +import tomllib +from datetime import date, timedelta +from pathlib import Path +from types import SimpleNamespace + +from sqlalchemy import func, select +from sqlmodel import Session + +from webapi.follow_up.silver import citologias, notas +from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de +from webapi.orchestration.tables.cacu import TABLAS +from webapi.follow_up.view import P +from webapi.orchestration.reference.age_groups import grupos_de_cortes +from webapi.orchestration.reference.rules import valor_de +from webapi.orchestration.tables import TablasKit + +RAIZ = Path(__file__).resolve().parent # `estratos.toml` is next to this module +SIN_DATO = "sin_dato" + + +def leer_estrato(proyecto: str, nombre: str) -> SimpleNamespace: + """The stratum's rules and values in `estratos.toml` (the project's, or the common one).""" + with open(RAIZ / "estratos.toml", "rb") as archivo: + secciones = tomllib.load(archivo) + for seccion in (proyecto, "comun"): + if nombre in secciones.get(seccion, {}): + entrada = secciones[seccion][nombre] + return SimpleNamespace(parametros=entrada.get("parametros", {}), valores=entrada.get("valores", [])) + raise KeyError(f"No hay estrato {nombre!r} para {proyecto!r} en estratos.toml.") + + +def ejecutar(sesion: Session, consulta, parametros: dict): + """Runs with the parameters the query names.""" + nombrados = set(consulta.compile().params) + return sesion.execute(consulta, {n: v for n, v in parametros.items() if n in nombrados}) + +VENTANAS = (1, 3, 6, 12) +FECHAS_DE_ESTUDIO = ("toma", "reporte") +ESTUDIOS = ("citologia", "vph") +RESULTADOS_MOSTRADOS = ("ultimo", "mas_grave") +PAGINA_MAXIMA = 200 +# Nombre en esta lista -> clave en `parametros.toml`. +PARAMETROS_DE_LA_LISTA = { + "ventana_meses": "cacu.seguimiento.ventana_meses", + "fecha_estudio": "cacu.seguimiento.fecha_estudio", + "estudios": "cacu.seguimiento.estudios", + "resultado_mostrado": "cacu.seguimiento.resultado_mostrado", + "grupos_edad": "cacu.grupos_edad", + "catalogo": "cacu.catalogos.citologia", + "cie_diagnostico": "cacu.diagnostico.cie", + "especialidades_diagnostico": "cacu.diagnostico.especialidades", + "cie_antecedente": "cacu.diagnostico.cie_antecedente", + "horizonte_dias": "cacu.horizontes.toma_diagnostico_dias", +} +ESTRATO = "estatus_seguimiento" + + +class PedidoInvalido(ValueError): + """Un parámetro del pedido fuera de lo que admite el contrato (400).""" + + +class PaginaFuera(LookupError): + """Una página mayor que la última, habiendo pacientes (404).""" + + +def seguimiento_de( + sesion: Session, + *, + sal: str, + corte: date | None = None, + meses: int | None = None, + estatus: str | None = None, + page: int = 1, + page_size: int = 50, + hoy: date | None = None, + tablas: TablasKit = TABLAS, +) -> dict: + """La lista de seguimiento al `corte`, lista para `json.dumps` (contrato §2). + + `corte` por omisión es `hoy`; en los dos casos se acota a la última fecha con datos de la plata. + `meses` por omisión es `cacu.seguimiento.ventana_meses`. + + Raises: + PedidoInvalido: `meses`, `estatus`, `page` o `page_size` fuera de rango. + PaginaFuera: `page` mayor que la última página, habiendo pacientes. + ReglaDesconocida: una regla de `parametros.toml` con una opción que el código no sabe aplicar. + """ + lista = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in PARAMETROS_DE_LA_LISTA.items()} + del_estatus = leer_estrato("cacu", ESTRATO).parametros + valores_estatus = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in del_estatus.items()} + _validar_reglas(lista) + meses = lista["ventana_meses"] if meses is None else meses + if meses not in VENTANAS: + raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.") + if estatus is not None and estatus not in ESTATUS: + raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.") + if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA: + raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.") + + corte = _acotado(sesion, corte or hoy or date.today(), tablas) + desde = _meses_antes(corte, meses) + timedelta(days=1) + estatus_de = _estatus_al_corte(sesion, corte, valores_estatus) + items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas) + if estatus is not None: + items = [i for i in items if i["estatus"]["codigo"] == estatus] + + total = len(items) + paginas = -(-total // page_size) + if total and page > paginas: + raise PaginaFuera(f"page {page} pasa de la última ({paginas}).") + etiquetas = _etiquetas_de_estatus() + return { + "simulado": True, + "corte": corte.isoformat(), + "ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()}, + "filtros": {"estatus": estatus}, + "estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()], + "reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas), + "paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas}, + "items": items[(page - 1) * page_size : page * page_size], + } + + +def seudonimo(pac_id: int, sal: str) -> str: + """El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`.""" + return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper() + + +def _validar_reglas(lista: dict) -> None: + exigir_opcion("cacu.seguimiento.ventana_meses", lista["ventana_meses"], VENTANAS) + exigir_opcion("cacu.seguimiento.fecha_estudio", lista["fecha_estudio"], FECHAS_DE_ESTUDIO) + exigir_opciones("cacu.seguimiento.estudios", lista["estudios"], ESTUDIOS) + exigir_opcion("cacu.seguimiento.resultado_mostrado", lista["resultado_mostrado"], RESULTADOS_MOSTRADOS) + + +def _acotado(sesion: Session, corte: date, tablas: TablasKit) -> date: + """El corte, sin pasar de la última fecha con datos de la plata (si hay datos).""" + ultima = sesion.execute(select(func.max(tablas.Procedimiento.fecha))).scalar() + return corte if ultima is None else min(corte, _fecha(ultima)) + + +def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int, str]: + cte = estatus_al(P("corte_seguimiento"), reglas_de(valores), incluye_referencia=True) + filas = ejecutar(sesion, select(cte.c.pac_id, cte.c.estatus), {**valores, "corte_seguimiento": corte.isoformat()}) + return {pac_id: estatus for pac_id, estatus in filas} + + +def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]: + """Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua.""" + estudios = _estudios(sesion, corte, lista["fecha_estudio"]) + en_ventana: dict[int, dict[str, list]] = {} + for e in estudios: + if desde <= e["fecha"] <= corte: + de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []}) + if "citologia" in lista["estudios"]: + de_la_paciente["citologia"].append(e) + if "vph" in lista["estudios"] and e["vph"] is not None: + de_la_paciente["vph"].append(e) + gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])} + edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas) + notas_de = _notas_por_paciente(sesion, corte) + items = [] + for pac_id, de_la_paciente in en_ventana.items(): + if not de_la_paciente["citologia"] and not de_la_paciente["vph"]: + continue + cito = _mostrada(de_la_paciente["citologia"], lista["resultado_mostrado"], gravedad) + vph = max(de_la_paciente["vph"], key=lambda e: e["fecha"], default=None) + mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]]) + estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE") + items.append({ + "id_seudonimo": seudonimo(pac_id, sal), + "grupo_edad": edades.get(pac_id, SIN_DATO), + "estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]}, + "ultima_citologia": None if cito is None else { + "fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"], + }, + "ultimo_vph": None if vph is None else { + "fecha": vph["fecha"].isoformat(), "resultado": vph["vph"], + "genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]), + }, + "dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista), + "prioridad": None, + "_orden": mas_reciente, + }) + items.sort(key=lambda i: i["id_seudonimo"]) + items.sort(key=lambda i: i.pop("_orden"), reverse=True) + return items + + +def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]: + """Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe).""" + c = citologias() + filas = sesion.execute(select( + c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18, + )).all() + estudios = [] + for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas: + toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte) + conocido = reporte is not None and reporte <= corte + fecha = toma if fecha_estudio == "toma" else reporte + if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido): + continue + estudios.append({ + "pac_id": pac_id, "fecha": fecha, "toma": toma, "calidad": calidad, + "resultado": resultado if conocido else None, + "vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None, + }) + return estudios + + +def _mostrada(citologias_: list[dict], resultado_mostrado: str, gravedad: dict[str, int]) -> dict | None: + if not citologias_: + return None + if resultado_mostrado == "ultimo": + return max(citologias_, key=lambda e: e["fecha"]) + return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"])) + + +def _grupo_de_edad(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, str]: + """El grupo de edad de cada paciente con fecha de nacimiento, con la edad cumplida al corte.""" + grupos = grupos_de_cortes(cortes, tablas=tablas) + edades = {} + for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)): + if nacimiento is None: + continue + nacimiento = _fecha(nacimiento) + edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day)) + edades[pac_id] = next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO) + return edades + + +def _notas_por_paciente(sesion: Session, corte: date) -> dict[int, list[tuple[date, str, str]]]: + n = notas() + de = {} + filas = sesion.execute(select(n.c.pac_id, n.c.fecha, n.c.cie_codigo, n.c.especialidad)) + for pac_id, fecha, cie, especialidad in filas: + if fecha is not None and _fecha(fecha) <= corte: + de.setdefault(pac_id, []).append((_fecha(fecha), cie, especialidad)) + return de + + +def _dias_a_la_valoracion(cito: dict, notas_de: dict, lista: dict) -> int | None: + """Días de la toma a la primera nota que la resuelve, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO; nulo si aún no. + + También nulo si la paciente ya tenía un diagnóstico de cáncer antes de la toma: esa toma no se mide. + """ + toma, propias = cito["toma"], notas_de.get(cito["pac_id"], []) + if any(f < toma and cie in lista["cie_antecedente"] for f, cie, _ in propias): + return None + dias = [ + (f - toma).days for f, cie, especialidad in propias + if f > toma and (f - toma).days < lista["horizonte_dias"] + and cie in lista["cie_diagnostico"] and especialidad in lista["especialidades_diagnostico"] + ] + return min(dias, default=None) + + +def _reglas_usadas(sesion: Session, claves: list[str], tablas: TablasKit) -> list[dict]: + filas = [sesion.get(tablas.DefParametro, clave) for clave in dict.fromkeys(claves)] + return [{"clave": f.clave, "valor": json.loads(f.valor), "estado": f.estado} for f in filas if f is not None] + + +def _etiquetas_de_estatus() -> dict[str, str]: + """Código -> etiqueta, en orden de presentación: los `valores` del estrato en `estratos.toml`.""" + return {v["valor"]: v["etiqueta"] for v in leer_estrato("cacu", ESTRATO).valores} + + +def _meses_antes(fecha: date, meses: int) -> date: + """La misma fecha `meses` meses antes; si ese mes es más corto, su último día.""" + total = fecha.year * 12 + fecha.month - 1 - meses + anio, mes = divmod(total, 12) + return date(anio, mes + 1, min(fecha.day, calendar.monthrange(anio, mes + 1)[1])) + + +def _fecha(valor) -> date: + """Una fecha de la base, venga como `date` o como texto ISO (SQLite).""" + return valor if isinstance(valor, date) else date.fromisoformat(str(valor)[:10]) diff --git a/webapi/follow_up/pivot.py b/webapi/follow_up/pivot.py new file mode 100644 index 0000000..39aa71e --- /dev/null +++ b/webapi/follow_up/pivot.py @@ -0,0 +1,110 @@ +"""Bloques de consulta sobre la plata de dos tablas (F5, ADR-MD-007). + +Una consulta de indicador no escribe a mano los `JOIN` entre `procedimiento` y +`observacion`: pide un **pivote**, una fila por procedimiento de un estudio y una +clase, con una columna por resultado del catálogo. El valor de cada columna sale de +la columna de `observacion` que le toca según `tipo_valor`: + + codigo valor_id, o el texto tal como llegó si no está en el catálogo (valor_fuente) + booleano valor_numerico, como entero (0 o 1) + numero valor_numerico + fecha valor_fecha + texto valor_texto + externo valor_texto + +Las fechas salen sin tipo (`sin_tipo`), como en las vistas por tipo, para que los parámetros +de periodo se liguen igual que antes. Con eso, el vocabulario de cada proyecto (`

/consultas/plata.py`) se rearma como +CTE, sin vistas en la base: las dos tablas ya son el estado actual (sin versiones de +fila). Solo se arman expresiones de SQLAlchemy; no se lee ni se escribe nada. +""" + +from collections.abc import Mapping +from functools import cache + +from sqlalchemy import Integer, Subquery, and_, case, cast, func, select, type_coerce +from sqlalchemy.types import NullType + +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.tables import PROJECTS, TablasKit, tablas_de + +COLUMNAS_DEL_PROCEDIMIENTO = ("procedimiento_id", "padre_id", "pac_id", "fecha", "fuente_tabla", "fuente_id") + + +class TipoDeResultadoAmbiguo(ValueError): + """Un mismo `resultado_id` con dos `tipo_valor` distintos en dos catálogos.""" + + +@cache +def tipos_de_resultado() -> dict[str, str]: + """`resultado_id` -> `tipo_valor`, de los catálogos de los tres proyectos (deben coincidir donde se repiten).""" + tipos: dict[str, str] = {} + for proyecto in PROJECTS: + for resultado in catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas_de(proyecto)).resultados: + previo = tipos.setdefault(resultado.resultado_id, resultado.tipo_valor) + if previo != resultado.tipo_valor: + raise TipoDeResultadoAmbiguo(f"{resultado.resultado_id}: {previo} y {resultado.tipo_valor}.") + return tipos + + +def sin_tipo(columna): + """Una fecha sin tipo de SQLAlchemy, como las columnas de las vistas por tipo (`consultas.vista.vista`). + + Así un parámetro de la definición (`P("periodo_inicio")`) se liga como lo da el cálculo (texto ISO) + y no como `Date`, y las consultas de los indicadores comparan fechas igual que antes (T-18r). + """ + return type_coerce(columna, NullType()).label(columna.key) if hasattr(columna, "key") else type_coerce(columna, NullType()) + + +def valor(observacion, tipo_valor: str): + """La expresión del valor de una observación según su tipo.""" + if tipo_valor == "codigo": + return func.coalesce(observacion.c.valor_id, observacion.c.valor_fuente) + if tipo_valor == "booleano": + return cast(observacion.c.valor_numerico, Integer) + if tipo_valor == "numero": + return observacion.c.valor_numerico + if tipo_valor == "fecha": + return sin_tipo(observacion.c.valor_fecha) + return observacion.c.valor_texto + + +def pivote( + tablas: TablasKit, estudio_id: str, clase: str, resultados: Mapping[str, str | tuple[str, str]] | None = None, *, + nombre: str | None = None, columnas: tuple[str, ...] = (), +) -> Subquery: + """Una fila por procedimiento del estudio y la clase, con una columna por resultado. + + `resultados`: nombre de la columna -> `resultado_id` (`{"resultado": "citologia.bethesda"}`), o + -> `(resultado_id, columna)` para leer una columna de `observacion` en particular + (`("nota_medica.especialidad", "valor_id")`: el código, nulo si no se reconoció). + Las columnas del procedimiento van siempre: `procedimiento_id`, `padre_id`, `pac_id`, + `fecha`, `fuente_tabla` y `fuente_id`, más las de `columnas` (`("orden_numero",)`). Un resultado + sin observación da nulo. + """ + resultados = dict(resultados or {}) + p = tablas.Procedimiento.__table__ + o = tablas.Observacion.__table__.alias(f"o_{estudio_id}_{clase}") + tipos = tipos_de_resultado() + columnas = [sin_tipo(p.c[c]) if c == "fecha" else p.c[c] for c in (*COLUMNAS_DEL_PROCEDIMIENTO, *columnas)] + if not resultados: + consulta = select(*columnas).where(p.c.estudio_id == estudio_id, p.c.clase == clase) + return consulta.subquery(nombre or f"{estudio_id}_{clase}") + pares = {columna: r if isinstance(r, tuple) else (r, None) for columna, r in resultados.items()} + pivoteadas = [ + func.max(case((o.c.resultado_id == resultado_id, + o.c[especifica] if especifica else valor(o, tipos[resultado_id])))).label(columna) + for columna, (resultado_id, especifica) in pares.items() + ] + consulta = ( + select(*columnas, *pivoteadas) + .select_from(p.outerjoin(o, and_(o.c.procedimiento_id == p.c.procedimiento_id, + o.c.resultado_id.in_([r for r, _ in pares.values()])))) + .where(p.c.estudio_id == estudio_id, p.c.clase == clase) + .group_by(*(p.c[c.key] if c.key == "fecha" else c for c in columnas)) + ) + return consulta.subquery(nombre or f"{estudio_id}_{clase}") + + +def hijos_de(padre: Subquery, hijo: Subquery): + """La condición de unión de un procedimiento con sus hijos (el reporte con su toma).""" + return hijo.c.padre_id == padre.c.procedimiento_id diff --git a/webapi/follow_up.py b/webapi/follow_up/routes.py similarity index 93% rename from webapi/follow_up.py rename to webapi/follow_up/routes.py index eb1985c..2f06094 100644 --- a/webapi/follow_up.py +++ b/webapi/follow_up/routes.py @@ -3,7 +3,7 @@ GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size= Es dato por paciente, sobre datos simulados: toda respuesta lleva `simulado: true`. La ruta se registra -siempre; quién puede verla lo decidirá una regla de acceso. La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida, +siempre; quién puede verla lo decidirá una regla de acceso. La lista la arma `webapi.follow_up.listing`; aquí solo se valida, se abre la sesión y se traducen los errores. """ @@ -15,7 +15,7 @@ from collections.abc import Callable from datetime import date from flask import Blueprint, Response, jsonify, request -from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seguimiento_de +from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de from sqlmodel import Session FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") diff --git a/webapi/follow_up/silver.py b/webapi/follow_up/silver.py new file mode 100644 index 0000000..2a838fb --- /dev/null +++ b/webapi/follow_up/silver.py @@ -0,0 +1,99 @@ +"""El vocabulario de CaCu sobre la plata de dos tablas (F5, ADR-MD-007): citologías, biopsias, notas y órdenes. + +Lo que leen las familias reescritas, armado con `plata.consultas.pivote` como subconsultas +(sin vistas en la base). Los nombres de columna son los del concepto, no los de una tabla +por tipo: `fecha_toma`, `resultado`, `grado`. Cada uno lleva `procedimiento_id` y +`pac_id`; los que cuelgan de una toma llevan también la de su toma. +""" + +from sqlalchemy import Subquery, select + +from webapi.orchestration.tables.cacu import TABLAS +from webapi.follow_up.pivot import hijos_de, pivote +from webapi.orchestration.tables import TablasKit + + +def citologias(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por citología tomada, con su calidad, su resultado (Bethesda) y su VPH si ya los tiene. + + Lo mismo que la vista por tipo `v_citologia_con_resultado`, desde las dos tablas. + """ + toma = pivote(tablas, "citologia", "toma", {"calidad_muestra": "citologia.calidad_muestra"}, + columnas=("orden_numero",), nombre="toma_citologia") + reporte = pivote(tablas, "citologia", "reporte", {"resultado": "citologia.bethesda"}, nombre="reporte_citologia") + vph = pivote(tablas, "vph", "reporte", { + "vph": "vph.resultado", "genotipo_16_18": "vph.genotipo_16_18", + "genotipo_16": "vph.genotipo_16", "genotipo_18": "vph.genotipo_18", + }, nombre="reporte_vph") + return select( + toma.c.procedimiento_id, toma.c.fuente_tabla, toma.c.fuente_id, toma.c.pac_id, + toma.c.fecha.label("fecha_toma"), toma.c.calidad_muestra, toma.c.orden_numero, + reporte.c.fecha.label("fecha_reporte"), reporte.c.resultado, + vph.c.vph, vph.c.genotipo_16_18, vph.c.genotipo_16, vph.c.genotipo_18, + ).select_from( + toma.outerjoin(reporte, hijos_de(toma, reporte)).outerjoin(vph, hijos_de(toma, vph)) + ).subquery("citologias") + + +def biopsias(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por biopsia reportada, con su grado, su solicitud y la citología que la originó (si se encontró). + + Desde T-22h la biopsia es una orden (`biopsia`, `orden`: la solicitud, con su fecha y su número de orden) + y su reporte, una hija de ella: la toma queda dos niveles arriba (toma, orden, reporte). + """ + reporte = pivote(tablas, "biopsia", "reporte", {"grado": "biopsia.grado"}, nombre="reporte_biopsia") + orden = pivote(tablas, "biopsia", "orden", columnas=("orden_numero",), nombre="orden_biopsia") + toma = pivote(tablas, "citologia", "toma", nombre="toma_de_la_biopsia") + return select( + reporte.c.procedimiento_id, reporte.c.fuente_tabla, reporte.c.fuente_id, reporte.c.pac_id, + reporte.c.fecha.label("fecha_reporte"), reporte.c.grado, orden.c.fecha.label("fecha_solicitud"), orden.c.orden_numero, + toma.c.procedimiento_id.label("toma_id"), toma.c.pac_id.label("toma_pac_id"), toma.c.fecha.label("fecha_toma"), + ).select_from( + reporte.outerjoin(orden, hijos_de(orden, reporte)).outerjoin(toma, hijos_de(toma, orden)) + ).subquery("biopsias") + + +def notas(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por nota médica: su fecha, su CIE-10 y la especialidad que la escribió (código; nulo si no se reconoció).""" + nota = pivote(tablas, "nota_medica", "encuentro", { + "cie_codigo": "nota_medica.diagnostico", + "especialidad": ("nota_medica.especialidad", "valor_id"), + "especialidad_fuente": ("nota_medica.especialidad", "valor_fuente"), + }, nombre="nota_medica") + return select( + nota.c.procedimiento_id, nota.c.fuente_tabla, nota.c.fuente_id, nota.c.pac_id, nota.c.fecha, + nota.c.cie_codigo, nota.c.especialidad, nota.c.especialidad_fuente, + ).subquery("notas") + + +def notas_con_textos(tablas: TablasKit = TABLAS) -> Subquery: + """Las notas con su motivo de consulta y su diagnóstico en texto (tal como llegan) y su identificador del hospital. + + Aparte de `notas` para no mover la huella de las definiciones que ya la leen (T-24b, T-24c). + """ + nota = pivote(tablas, "nota_medica", "encuentro", { + "cie_codigo": "nota_medica.diagnostico", + "especialidad": ("nota_medica.especialidad", "valor_id"), + "motivo": "nota_medica.motivo", + "diagnostico_texto": "nota_medica.diagnostico_texto", + }, columnas=("id_hospital",), nombre="nota_con_textos") + return select( + nota.c.procedimiento_id, nota.c.pac_id, nota.c.fecha, nota.c.cie_codigo, nota.c.especialidad, + nota.c.motivo, nota.c.diagnostico_texto, nota.c.id_hospital, + ).subquery("notas_con_textos") + + +def ordenes_de_biopsia(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por biopsia solicitada (la orden, con o sin reporte; T-22h): de quién y la fecha de la solicitud.""" + orden = pivote(tablas, "biopsia", "orden", nombre="orden_de_biopsia") + return select(orden.c.procedimiento_id, orden.c.pac_id, orden.c.fecha).subquery("ordenes_de_biopsia") + + +def tomas_con_especialidad(tablas: TablasKit = TABLAS) -> Subquery: + """Una fila por citología tomada, con la especialidad de la orden de la que cuelga (nula si no tiene o no se reconoce).""" + toma = pivote(tablas, "citologia", "toma", nombre="toma_con_especialidad") + orden = pivote(tablas, "citologia", "orden", {"especialidad": ("orden.especialidad", "valor_id")}, + nombre="orden_de_la_toma") + return select(toma.c.procedimiento_id, toma.c.pac_id, toma.c.fecha, orden.c.especialidad).select_from( + toma.outerjoin(orden, hijos_de(orden, toma)) + ).subquery("tomas_con_especialidad") diff --git a/webapi/follow_up/status.py b/webapi/follow_up/status.py new file mode 100644 index 0000000..142e5a7 --- /dev/null +++ b/webapi/follow_up/status.py @@ -0,0 +1,281 @@ +"""El estatus de seguimiento ASCCP de cada paciente a una fecha (T-24c; plan de seguimiento, §5.2). + +`estatus_al(referencia, reglas)` es la única regla: una CTE `(pac_id, estatus)` con un renglón +por persona. La usan el estrato `estatus_seguimiento` (`estrato`, a la referencia de cada +reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las cohortes (a su +fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo +pasado no cambia cuando la paciente avanza. + + POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia + POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si + es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de + valoración (la nota que resuelve una toma, como en CACU_DIAS_TOMA_DIAGNOSTICO); una + orden o una biopsia, por regla, si es del mismo día que una nota de colposcopia (la + colposcopia es la madre de la biopsia) + INFO_INSUFICIENTE la historia no alcanza (`cacu.seguimiento.insuficiente.regla`); también el resto + PRE_COLPOSCOPIA ninguna de las anteriores y, si se conoce la especialidad de sus citologías, + alguna es de vigilancia + +Ninguna regla está escrita aquí: todas son de `parametros.toml` (`cacu.seguimiento.*`, §2bis); qué +parámetro de la consulta es qué clave lo declara `estratos.toml` (`[cacu.estatus_seguimiento.parametros]`), +y llegan como `reglas`. Las listas (CIE-10, especialidades, evidencias) van ligadas como +parámetros (S-K76); los textos del motivo y del diagnóstico se comparan por contención, en +mayúsculas y sin acentos; la precedencia, la referencia y la regla de insuficiente arman la +consulta. Una opción que el código no sabe aplicar falla con `ReglaDesconocida`. +""" + +import unicodedata +from collections.abc import Mapping +from dataclasses import dataclass + +from sqlalchemy import ( + CTE, ColumnElement, and_, bindparam, case, exists, func, literal, literal_column, or_, select, union_all, +) + +from webapi.follow_up.silver import biopsias, notas_con_textos, ordenes_de_biopsia, tomas_con_especialidad +from webapi.orchestration.tables.cacu import TABLAS +from webapi.follow_up.functions import dias_entre +from webapi.follow_up.view import P, vista +from webapi.orchestration.tables import TablasKit + +ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA") +RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3) +MARCOS = ("estatus", "ronda") +REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte +EVIDENCIAS = ("motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia") +FUENTES_DE_TRATAMIENTO = ("nota_posterior_a_colposcopia",) +REGLAS_DE_INSUFICIENTE = ("inicio_datos_posterior_a_alta", "sin_alta_registrada", "ambos", "nunca") +REQUISITOS_DE_COLPOSCOPIA = ("valoracion_previa", "ninguno") +REQUISITOS_DE_BIOPSIA = ("mismo_dia_que_colposcopia", "ninguno") + +V_PERSONA = vista("v_persona", "pac_id") +SIN_ACENTO = {"Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U", "Ü": "U", "á": "a", "é": "e", "í": "i", "ó": "o", + "ú": "u", "ü": "u"} # fmt: skip + + +class ReglaDesconocida(ValueError): + """Una regla de `cacu.seguimiento.*` con una opción que el código no sabe aplicar.""" + + +@dataclass(frozen=True) +class Reglas: + """Las reglas que dan forma a la consulta, ya validadas. Las listas no van aquí: se ligan al ejecutar.""" + + referencia: str # el parámetro del reporte: `periodo_inicio` o `fecha_corte` + precedencia: tuple[str, ...] + motivos: tuple[str, ...] # normalizados + diagnosticos: tuple[str, ...] # normalizados + insuficiente: str + valoracion_previa: bool # una nota de colposcopia cuenta solo después de una cita de valoración + biopsia_mismo_dia: bool # la orden y la biopsia cuentan solo el día de una nota de colposcopia + + +def reglas_de(valores: Mapping) -> Reglas: + """Valida las reglas (`{parámetro de la consulta: valor}`, los de `estratos.toml`) contra las opciones admitidas.""" + exigir_opciones("cacu.seguimiento.marco", valores["seguimiento_marco"], MARCOS) + if "estatus" not in valores["seguimiento_marco"]: + raise ReglaDesconocida("cacu.seguimiento.marco no incluye «estatus»: el estrato no se publica.") + if "ronda" in valores["seguimiento_marco"]: + raise ReglaDesconocida("cacu.seguimiento.marco: «ronda» (UE) todavía no se sabe aplicar.") + exigir_opcion("cacu.seguimiento.referencia", valores["seguimiento_referencia"], tuple(REFERENCIAS)) + precedencia = tuple(valores["seguimiento_precedencia"]) + if sorted(precedencia) != sorted(ESTATUS): + raise ReglaDesconocida( + f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; " + f"llegó {precedencia}." + ) + exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS) + exigir_opciones( + "cacu.seguimiento.tratamiento.fuentes", valores["seguimiento_fuentes_tratamiento"], FUENTES_DE_TRATAMIENTO + ) + exigir_opcion("cacu.seguimiento.insuficiente.regla", valores["seguimiento_insuficiente"], REGLAS_DE_INSUFICIENTE) + exigir_opcion("cacu.seguimiento.colposcopia.requisito", valores["seguimiento_requisito"], REQUISITOS_DE_COLPOSCOPIA) + exigir_opcion( + "cacu.seguimiento.colposcopia.biopsia_requisito", + valores["seguimiento_biopsia_requisito"], + REQUISITOS_DE_BIOPSIA, + ) + return Reglas( + referencia=REFERENCIAS[valores["seguimiento_referencia"]], + precedencia=precedencia, + motivos=tuple(normalizado(m) for m in valores["seguimiento_motivos"]), + diagnosticos=tuple(normalizado(d) for d in valores["seguimiento_diagnosticos"]), + insuficiente=valores["seguimiento_insuficiente"], + valoracion_previa=valores["seguimiento_requisito"] == "valoracion_previa", + biopsia_mismo_dia=valores["seguimiento_biopsia_requisito"] == "mismo_dia_que_colposcopia", + ) + + +def estrato(valores: Mapping) -> CTE: + """El estrato `estatus_seguimiento` (`estratos.toml`): `(unidad_id, estrato)`, a la referencia del reporte.""" + reglas = reglas_de(valores) + estatus = estatus_al(P(reglas.referencia), reglas, incluye_referencia=reglas.referencia == "fecha_corte") + return select(estatus.c.pac_id.label("unidad_id"), estatus.c.estatus.label("estrato")).cte( + "estrato_estatus_seguimiento" + ) + + +def estatus_al( + referencia: ColumnElement, reglas: Reglas, *, incluye_referencia: bool = False, tablas: TablasKit = TABLAS +) -> CTE: + """La CTE `(pac_id, estatus)`: un renglón por persona, con lo ocurrido antes de `referencia`. + + `referencia` es una fecha de SQL (un parámetro: `P("periodo_inicio")`, `P("corte")`). Con + `incluye_referencia`, cuenta también lo de ese día (un corte); sin él, solo lo anterior (el inicio + de un periodo). Los parámetros `seguimiento_*` de las listas se ligan al ejecutar. + """ + + def antes(fecha) -> ColumnElement: + return fecha <= referencia if incluye_referencia else fecha < referencia + + nota, orden, reporte, toma = ( + notas_con_textos(tablas), ordenes_de_biopsia(tablas), biopsias(tablas), tomas_con_especialidad(tablas) + ) + # La cita de valoración: la nota que resuelve una toma, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO. + valoracion = ( + select(nota.c.pac_id, func.min(nota.c.fecha).label("primera")) + .select_from(nota.join(toma, toma.c.pac_id == nota.c.pac_id)) + .where( + antes(nota.c.fecha), + nota.c.fecha > toma.c.fecha, + dias_entre(toma.c.fecha, nota.c.fecha) < P("seguimiento_horizonte_valoracion"), + nota.c.cie_codigo.in_(P("seguimiento_cie_valoracion", lista=True)), + nota.c.especialidad.in_(P("seguimiento_especialidades_valoracion", lista=True)), + ) + .group_by(nota.c.pac_id) + .cte("seguimiento_valoracion") + ) + # Una nota de colposcopia: de su especialidad y, por regla, posterior a la primera valoración. + de_colposcopia = and_( + antes(nota.c.fecha), + nota.c.especialidad.in_(P("seguimiento_especialidades_colposcopia", lista=True)), + nota.c.fecha > valoracion.c.primera if reglas.valoracion_previa else _siempre(), + ) + con_valoracion = nota.outerjoin(valoracion, valoracion.c.pac_id == nota.c.pac_id) + # Los días con una nota de colposcopia válida: la orden de biopsia se expide ese día (su madre). + visitas = select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(de_colposcopia).cte( + "seguimiento_visitas_de_colposcopia" + ) + + def de_una_visita(pac_id, fecha) -> ColumnElement: + if not reglas.biopsia_mismo_dia: + return _siempre() + return exists().where(visitas.c.pac_id == pac_id, visitas.c.fecha == fecha) + + evidencias = union_all( + select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where( + _habilitada("motivo"), de_colposcopia, _contiene(nota.c.motivo, reglas.motivos, "motivo") + ), + select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where( + _habilitada("cie"), de_colposcopia, nota.c.cie_codigo.in_(P("seguimiento_cie_colposcopia", lista=True)), + ), + select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where( + _habilitada("diagnostico_texto"), de_colposcopia, + _contiene(nota.c.diagnostico_texto, reglas.diagnosticos, "diagnostico"), + ), + select(orden.c.pac_id, orden.c.fecha).where( + _habilitada("orden_biopsia"), antes(orden.c.fecha), de_una_visita(orden.c.pac_id, orden.c.fecha) + ), + select(reporte.c.pac_id, reporte.c.fecha_reporte.label("fecha")).where( + _habilitada("biopsia"), antes(reporte.c.fecha_reporte), + de_una_visita(reporte.c.pac_id, reporte.c.fecha_solicitud), + ), + ).subquery("evidencias_de_colposcopia") + colposcopia = ( + select(evidencias.c.pac_id, func.min(evidencias.c.fecha).label("primera")) + .group_by(evidencias.c.pac_id) + .cte("seguimiento_colposcopia") + ) + tratamiento = ( + select(nota.c.pac_id) + .distinct() + .select_from(nota.join(colposcopia, colposcopia.c.pac_id == nota.c.pac_id)) + .where( + antes(nota.c.fecha), + nota.c.fecha > colposcopia.c.primera, + nota.c.cie_codigo.in_(P("seguimiento_cie_tratamiento", lista=True)), + ) + .cte("seguimiento_tratamiento") + ) + # Fuera de vigilancia: todas sus citologías tienen especialidad conocida y ninguna es de vigilancia. + de_vigilancia = or_( + toma.c.especialidad.is_(None), toma.c.especialidad.in_(P("seguimiento_especialidades_vigilancia", lista=True)) + ) + fuera_de_vigilancia = ( + select(toma.c.pac_id) + .where(antes(toma.c.fecha)) + .group_by(toma.c.pac_id) + .having(func.sum(case((de_vigilancia, 1), else_=0)) == 0) + .cte("seguimiento_fuera_de_vigilancia") + ) + persona = V_PERSONA + cumple = { + "POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None), + "POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None), + "INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente), + "PRE_COLPOSCOPIA": fuera_de_vigilancia.c.pac_id.is_(None), + } + estatus = case(*((cumple[e], literal(e)) for e in reglas.precedencia), else_=literal(RESTO)) + return ( + select(persona.c.pac_id, estatus.label("estatus")) + .select_from( + persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id) + .outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id) + .outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id) + ) + .cte("seguimiento_estatus") + ) + + +def normalizado(texto: str) -> str: + """Un texto para comparar: sin espacios al borde, sin acentos y en mayúsculas (la Ñ se queda).""" + return "".join(SIN_ACENTO.get(c, c) for c in unicodedata.normalize("NFC", texto.strip())).upper() + + +def _normalizado_sql(columna: ColumnElement) -> ColumnElement: + """`normalizado` en SQL: sin acentos (antes de `upper`, que en SQLite solo sabe ASCII) y en mayúsculas.""" + for con, sin in SIN_ACENTO.items(): + columna = func.replace(columna, con, sin) + return func.upper(columna) + + +def _contiene(columna: ColumnElement, textos: tuple[str, ...], nombre: str) -> ColumnElement: + """La columna, normalizada, contiene alguno de los textos (ya normalizados). Sin textos, nunca.""" + if not textos: + return _nunca() + normal = _normalizado_sql(columna) + return or_(*(normal.contains(bindparam(f"seguimiento_{nombre}_{i}", t)) for i, t in enumerate(textos))) + + +def _habilitada(evidencia: str) -> ColumnElement: + """La evidencia está en `cacu.seguimiento.colposcopia.evidencias` (ligada al ejecutar).""" + return literal(evidencia).in_(P("seguimiento_evidencias", lista=True)) + + +def _insuficiente(regla: str) -> ColumnElement: + """La regla de historia insuficiente. Hoy no hay fecha de alta (usuario, 2026-10-22): se asume posterior al + inicio de los datos, así que `inicio_datos_posterior_a_alta` no marca a nadie y `sin_alta_registrada`, a todas.""" + return _siempre() if regla in ("sin_alta_registrada", "ambos") else _nunca() + + +def _siempre() -> ColumnElement: + """Una condición verdadera. No `true()`: SQL Server la escribe como `1`, que no es condición.""" + return literal_column("1") == literal_column("1") + + +def _nunca() -> ColumnElement: + """Una condición falsa (ver `_siempre`).""" + return literal_column("1") == literal_column("0") + + +def exigir_opcion(clave: str, valor, admitidas: tuple) -> None: + """La regla `clave` vale una de las opciones que el código sabe aplicar; si no, `ReglaDesconocida`.""" + if valor not in admitidas: + raise ReglaDesconocida(f"{clave} = {valor!r}: el código sabe aplicar {list(admitidas)}.") + + +def exigir_opciones(clave: str, valores, admitidas: tuple) -> None: + """Cada valor de la regla `clave` es una opción que el código sabe aplicar; si no, `ReglaDesconocida`.""" + desconocidas = [v for v in valores if v not in admitidas] + if desconocidas: + raise ReglaDesconocida(f"{clave}: {desconocidas} no se saben aplicar; el código sabe {list(admitidas)}.") diff --git a/webapi/follow_up/view.py b/webapi/follow_up/view.py new file mode 100644 index 0000000..2a764d2 --- /dev/null +++ b/webapi/follow_up/view.py @@ -0,0 +1,26 @@ +"""De dónde lee una definición: una vista o una tabla por su nombre, y sus parámetros. + +Una definición de indicador lee la plata genérica por su vocabulario +(`/consultas/plata.py`) y las tablas de apoyo (`dim_fecha`, +`dim_grupo_edad`, `v_persona`) por `vista`. Desde F6 (ADR-MD-009) no hay +tablas de hechos por tipo ni sus vistas `v__actual`. + +Las consultas son objetos de SQLAlchemy: el SQL lo escribe SQLAlchemy +para el motor de la sesión. +""" + +from sqlalchemy import BindParameter, FromClause, bindparam, column, table + + +def vista(nombre: str, *columnas: str) -> FromClause: + """Una vista o una tabla por su nombre y sus columnas, para las que no salen de un modelo.""" + return table(nombre, *(column(nombre_columna) for nombre_columna in columnas)) + + +def P(nombre: str, *, lista: bool = False) -> BindParameter: + """Un parámetro de una definición. `lista`: su valor es una lista y va en un `IN`. + + El valor no entra al SQL: se liga al ejecutar, así que la definición + no cambia cuando cambia una regla del TOML (S-K76). + """ + return bindparam(nombre, expanding=lista) diff --git a/webapi/orchestration/cycle.py b/webapi/orchestration/cycle.py index 2fe7003..a54c9f1 100644 --- a/webapi/orchestration/cycle.py +++ b/webapi/orchestration/cycle.py @@ -17,30 +17,30 @@ from importlib import import_module from pathlib import Path from hamilton.function_modifiers import config -from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata -from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado -from indicadores_kit.oro.cohortes.definicion import leer_definicion -from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging -from indicadores_kit.plata.periodo_observacion import periodos_de_observacion -from indicadores_kit.plata.vistas import ddl_de_vistas as ddl_de_v_persona -from indicadores_kit.registry.apoyo import ( +from webapi.orchestration.silver.quality import verificar_plata as calidad_de_la_plata +from webapi.orchestration.silver.loads import carga_desde_staging, tablas_de_staging +from webapi.orchestration.silver.observation_periods import periodos_de_observacion +from webapi.orchestration.silver.views import ddl_de_vistas as ddl_de_v_persona +from webapi.orchestration.reference.support import ( CLAVE_DIM_FECHA_DESDE, filas_de_dim_fecha, grupos_de_edad_de, ) -from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.registry.parametros import ( +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.reference.rules import ( RUTA_PARAMETROS, leer_parametros, valores_del_archivo, ) -from indicadores_kit.registry.periodos import periodos_de_tipos -from indicadores_kit.tablas import tablas_de +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 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 log = logging.getLogger(__name__) @@ -173,17 +173,17 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]: Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read. """ tablas = tablas_de(ctx.project) - tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES + 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 armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, + return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte, linea=ctx.repos.silver.timeline.query) armados = {} for ruta in cohort_definitions(ctx.project): - definicion = leer_definicion(ruta) + definicion = read_definition(ruta) armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion)) return armados @@ -192,26 +192,26 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]: def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]: """El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008). - Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador + Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador (`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica. Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden `confirm-risks`, no este paso. """ - tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES + tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES lotes = {} for ruta in cohort_definitions(ctx.project): - definicion = leer_definicion(ruta) + definicion = read_definition(ruta) estimador = ctx.estimators.get(definicion.url) if estimador is None: continue - def marco(sesion, definicion=definicion): - armado_id = ultimo_armado(sesion, definicion.url, cohortes=tablas_cohorte) - return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion, + 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) - armado_id, ancho = ctx.repos.gold.cohorts.read(marco) + armado_id, ancho = ctx.repos.gold.cohorts.read(frame) if armado_id is None: continue riesgos = [tuple(r) for r in estimador.estimar(*ancho)] diff --git a/webapi/orchestration/project.py b/webapi/orchestration/project.py index 8daf180..07c9e67 100644 --- a/webapi/orchestration/project.py +++ b/webapi/orchestration/project.py @@ -1,9 +1,9 @@ -"""Lo que el ciclo necesita saber de las definiciones de un proyecto: sus periodos (dbt) y sus cohortes (el kit).""" +"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`).""" import json from pathlib import Path -from indicadores_kit.oro.cohortes.definicion import RAIZ +from models.cohorts.definition import ROOT def period_types(proyecto: str, manifest: Path) -> list[str]: @@ -14,5 +14,6 @@ def period_types(proyecto: str, manifest: Path) -> list[str]: def cohort_definitions(proyecto: str) -> list[Path]: - """Los TOML de cohortes que el ciclo arma (`/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h).""" - return sorted((RAIZ / proyecto / "cohortes").glob("*.toml")) + """The cohort TOMLs the cycle builds (`models/cohorts//*.toml`): today only CaCu's surveillance cohort. + Those in `/proposals/` aren't built.""" + return sorted((ROOT / proyecto).glob("*.toml")) diff --git a/webapi/orchestration/reference/__init__.py b/webapi/orchestration/reference/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/webapi/orchestration/reference/age_groups.py b/webapi/orchestration/reference/age_groups.py new file mode 100644 index 0000000..d5ba5b4 --- /dev/null +++ b/webapi/orchestration/reference/age_groups.py @@ -0,0 +1,61 @@ +"""`dim_grupo_edad`: los grupos de edad como datos, para etiquetar sin funciones del motor. + +Una fila por grupo, con sus dos límites incluidos. El SQL calcula la edad +cumplida con las partes de la fecha de `dim_fecha` y cruza con esta +tabla. Los cortes de cada proyecto son la regla `.grupos_edad` +del TOML de parámetros (una lista de pares mínimo y máximo): cambiar los +grupos es editar el TOML, no un SQL. +""" + +from core.indicadores.registro import DimGrupoEdadBase +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + + +EDAD_MAXIMA = 150 # tope del grupo abierto de arriba; una edad mayor es un error de captura + + +def grupos_de_cortes(cortes: list[list[int]], *, tablas: TablasKit) -> list[DimGrupoEdadBase]: + """De los pares `[edad_min, edad_max]` del TOML a los grupos, más dos abiertos. + + [[25, 34], [35, 44]] -> "<25", "25-34", "35-44", "45+". Los grupos + abiertos (S-M3, usuario, 2026-10-08) hacen que toda edad conocida + caiga en un grupo: `sin_dato` queda solo para quien no tiene fecha de + nacimiento (o una edad imposible). Por lo mismo, los cortes no pueden + encimarse ni dejar huecos. + """ + grupos = [] + for corte in cortes: + if len(corte) != 2 or not all(type(edad) is int for edad in corte): + raise ValueError(f"Un corte de edad son dos enteros, mínimo y máximo; llegó {corte!r}.") + minimo, maximo = corte + grupos.append( + tablas.DimGrupoEdad(etiqueta=f"{minimo}-{maximo}", edad_min=minimo, edad_max=maximo) + ) + _exigir_contiguos(grupos) + menor = min(grupo.edad_min for grupo in grupos) + mayor = max(grupo.edad_max for grupo in grupos) + if menor > 0: + grupos.insert(0, tablas.DimGrupoEdad(etiqueta=f"<{menor}", edad_min=0, edad_max=menor - 1)) + if mayor < EDAD_MAXIMA: + grupos.append( + tablas.DimGrupoEdad(etiqueta=f"{mayor + 1}+", edad_min=mayor + 1, edad_max=EDAD_MAXIMA) + ) + return grupos + + +def _exigir_contiguos(grupos: list[DimGrupoEdadBase]) -> None: + if not grupos: + raise ValueError("Hace falta al menos un corte de edad.") + anterior = None + for grupo in sorted(grupos, key=lambda g: g.edad_min): + if grupo.edad_min > grupo.edad_max: + raise ValueError(f"El grupo {grupo.etiqueta!r} tiene los límites al revés.") + if anterior is not None and grupo.edad_min <= anterior.edad_max: + raise ValueError(f"Los grupos {anterior.etiqueta!r} y {grupo.etiqueta!r} se enciman.") + if anterior is not None and grupo.edad_min > anterior.edad_max + 1: + raise ValueError( + f"Entre {anterior.etiqueta!r} y {grupo.etiqueta!r} hay edades sin grupo." + ) + anterior = grupo diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py new file mode 100644 index 0000000..afb0798 --- /dev/null +++ b/webapi/orchestration/reference/catalogs.py @@ -0,0 +1,136 @@ +"""Catálogos de la plata (F1): `core/catalogos/.toml` leído y validado. + +Un catálogo es estudio -> resultado -> valor (`core/catalogos/LEEME.md`). +Aquí solo se lee el archivo y se devuelven las filas de `cat_estudio`, +`cat_resultado` y `cat_valor` del proyecto; las escribe Persistance por la +arista `catalogos` de webapi.orchestration (T-17c). + +`codigos_hospital` de cada estudio no va a ninguna tabla: es cómo nombra el +hospital al estudio (tipo de estudio de la orden, instrumento), y lo usa la +carga de F5. +""" + +import tomllib +from pathlib import Path +from typing import NamedTuple + +import core +from core.indicadores.catalogos import TIPOS_DE_VALOR +from sqlmodel import SQLModel + +from webapi.orchestration.tables import TablasKit + +# Los catálogos viven en Core, junto a los modelos de sus tablas. +RAIZ_CATALOGOS = Path(core.__file__).parent / "catalogos" + + +class CatalogoInvalido(ValueError): + """El archivo de catálogo no cumple sus reglas.""" + + +class Catalogo(NamedTuple): + """Las filas de las tres tablas de catálogo de un proyecto, en el orden del archivo.""" + + estudios: list[SQLModel] + resultados: list[SQLModel] + valores: list[SQLModel] + + +def ruta_de_catalogo(proyecto: str) -> Path: + """El archivo de catálogo del proyecto: `core/catalogos/.toml`.""" + return RAIZ_CATALOGOS / f"{proyecto}.toml" + + +def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo: + """Lee el archivo, lo valida y devuelve las filas con las clases de `tablas`. + + `resultado_id` es `"."`; el `orden` de un valor es su + posición en la lista, desde 1, y todos llegan `vigente` (retirar uno es + cosa de quien sincroniza la tabla). + """ + estudios, resultados, valores = [], [], [] + for estudio_id, estudio in _leer(ruta).items(): + estudios.append(tablas.CatEstudio(estudio_id=estudio_id, etiqueta=_etiqueta(estudio, estudio_id))) + for nombre, resultado in estudio.get("resultados", {}).items(): + resultado_id = f"{estudio_id}.{nombre}" + tipo_valor = _tipo_de_valor(resultado, resultado_id) + resultados.append( + tablas.CatResultado( + resultado_id=resultado_id, + estudio_id=estudio_id, + etiqueta=_etiqueta(resultado, resultado_id), + tipo_valor=tipo_valor, + unidad=resultado.get("unidad"), + sistema=resultado.get("sistema"), + ) + ) + valores += [ + tablas.CatValor( + resultado_id=resultado_id, + valor_id=valor_id, + etiqueta=etiqueta, + orden=orden, + estado="vigente", + ) + for orden, (valor_id, etiqueta) in enumerate(_valores(resultado, resultado_id, tipo_valor), start=1) + ] + return Catalogo(estudios, resultados, valores) + + +def codigos_hospital(proyecto: str) -> dict[str, str]: + """Código del hospital -> `estudio_id`, del catálogo del proyecto. + + Un código que aparece en dos estudios es un error: no se sabría a cuál va. + """ + codigos: dict[str, str] = {} + for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items(): + for codigo in estudio.get("codigos_hospital", []): + if codigo in codigos: + raise CatalogoInvalido( + f"El código del hospital {codigo!r} está en dos estudios: {codigos[codigo]!r} y {estudio_id!r}." + ) + codigos[codigo] = estudio_id + return codigos + + +def _leer(ruta: Path) -> dict: + return tomllib.loads(Path(ruta).read_text(encoding="utf-8")) + + +def _etiqueta(seccion: dict, nombre: str) -> str: + if "etiqueta" not in seccion: + raise CatalogoInvalido(f"{nombre}: falta la etiqueta.") + return seccion["etiqueta"] + + +def _tipo_de_valor(resultado: dict, resultado_id: str) -> str: + """El `tipo_valor` del resultado, y las llaves que ese tipo admite.""" + tipo_valor = resultado.get("tipo_valor") + if tipo_valor not in TIPOS_DE_VALOR: + raise CatalogoInvalido( + f"{resultado_id}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}." + ) + if tipo_valor == "codigo" and not resultado.get("valores"): + raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.") + if tipo_valor != "codigo" and "valores" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.") + if tipo_valor != "externo" and "sistema" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.") + if tipo_valor != "numero" and "unidad" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.") + return tipo_valor + + +def _valores(resultado: dict, resultado_id: str, tipo_valor: str) -> list[tuple[str, str]]: + """(valor, etiqueta) de cada valor del resultado, en el orden del archivo; sin repetidos.""" + if tipo_valor != "codigo": + return [] + vistos: set[str] = set() + valores = [] + for entrada in resultado["valores"]: + valor = entrada["valor"] + if valor in vistos: + raise CatalogoInvalido(f"{resultado_id}: el valor {valor!r} está repetido.") + vistos.add(valor) + valores.append((valor, _etiqueta(entrada, f"{resultado_id}: {valor!r}"))) + return valores diff --git a/webapi/orchestration/reference/dates.py b/webapi/orchestration/reference/dates.py new file mode 100644 index 0000000..e4c3408 --- /dev/null +++ b/webapi/orchestration/reference/dates.py @@ -0,0 +1,35 @@ +"""`dim_fecha`: una fila por día, para hacer aritmética de fechas sin funciones del motor. + +Sumar días o medir un intervalo es una resta de `dia_num` con un cruce. +`dia_habil_num` cuenta solo de lunes a viernes; los días festivos no +están (haría falta un calendario, S-K27). `anio`, `mes` y `dia` son las +partes de la fecha: sirven para la edad cumplida, que no es una resta de +días. Se reemplaza entera por `RegistroRepository.reemplazar`. +""" + +from datetime import date, timedelta + +from core.indicadores.registro import DimFechaBase + +from webapi.orchestration.tables import TablasKit + + +def dias(desde: date, hasta: date, *, tablas: TablasKit) -> list[DimFechaBase]: + """Los días de `desde` a `hasta`, los dos incluidos.""" + if hasta < desde: + raise ValueError(f"El rango de dim_fecha va al revés: {desde} a {hasta}.") + filas, habiles = [], 0 + for numero in range((hasta - desde).days + 1): + dia = desde + timedelta(days=numero) + habiles += dia.weekday() < 5 + filas.append( + tablas.DimFecha( + fecha=dia, + dia_num=numero, + dia_habil_num=habiles, + anio=dia.year, + mes=dia.month, + dia=dia.day, + ) + ) + return filas diff --git a/webapi/orchestration/reference/parametros.toml b/webapi/orchestration/reference/parametros.toml new file mode 100644 index 0000000..776275d --- /dev/null +++ b/webapi/orchestration/reference/parametros.toml @@ -0,0 +1,701 @@ +# Parámetros de indicadores_kit, para todos los proyectos. +# +# Cada parámetro lleva: +# valor lo que usa el cálculo +# estado "sin_definir" nadie lo ha decidido; el valor solo permite correr +# "provisional" hay una propuesta documentada, falta confirmarla +# "confirmado" decisión cerrada +# fuente dónde está documentada la decisión o la pendiente +# +# Se carga en la tabla def_parametro de cada base con +# registry.parametros.cargar_parametros. La clave es "seccion.nombre". + +[comun.dim_fecha.desde] +# El primer día de `dim_fecha`, la tabla de fechas que cruzan las consultas portables (la edad del estrato +# `grupo_edad`). Fijo, porque `dia_num` y `dia_habil_num` se cuentan desde él; el último día es el fin del +# último año del ciclo. Tiene que ser anterior al nacimiento más antiguo: si no, la guarda de cobertura +# (`calidad/cobertura.exigir_cobertura`) detiene el cálculo y lo dice (T-24f, I-MD27). +valor = "1920-01-01" +estado = "provisional" +fuente = "Usuario, 2026-10-22: dim_fecha y dim_grupo_edad se llenan de los TOML (T-24f, I-MD27); 1920 cubre edades hasta los 106 años" + +[comun.umbral_supresion] +# Se suprime un resultado cuyo denominador es menor que este valor. +valor = 5 +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta confirmarla (usuario, 2026-10-12). Los catálogos dicen < 5 y dejan la pregunta abierta (conventions.suppression.min_cell)" + +# Bandas del resumen de riesgos (`mart/riesgos.py`, T-21d). Provisionales: la compuerta +# pide que todo indicador calcule sin `sin_definir`; son candidatos documentados, falta que clínica decida (MD-Q5). +[comun.riesgos.corte_intermedio] +# Probabilidad desde la que la banda es INTERMEDIO (de 0 a 1). +valor = 0.04 +estado = "provisional" +fuente = "Candidato del prototipo: umbral de acción de ASCCP 2019 para colposcopia (4 %, riesgo inmediato de CIN3+). Decide clínica (MD-Q5)" + +[comun.riesgos.corte_alto] +# Probabilidad desde la que la banda es ALTO (de 0 a 1). +valor = 0.25 +estado = "provisional" +fuente = "Candidato del prototipo: umbral de ASCCP 2019 para tratamiento (25 %). En TEA no hay candidato propio. Decide clínica (MD-Q5)" + +[cacu.riesgos.horizonte_banda] +# Años desde la fecha índice de la evaluación que se clasifica; 0 = riesgo prevalente (inmediato). +valor = 0 +estado = "provisional" +fuente = "Prototipo: horizonte 0, el que miden los umbrales de ASCCP. Decide clínica con modelos (MD-Q5)" + +[cama.riesgos.horizonte_banda] +# Años desde el BI-RADS índice: el horizonte del desenlace de la cohorte de tamizaje (365 días, T-21g). +valor = 1 +estado = "provisional" +fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)" + +[tea.riesgos.horizonte_banda] +# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses). +valor = 4 +estado = "provisional" +fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)" + +[comun.catalogos.banda_riesgo] +# Las bandas del resumen de riesgos, de menor a mayor. +valor = [ + { clave = "BAJO", etiqueta = "Riesgo bajo", color = "#9DBFE3" }, + { clave = "INTERMEDIO", etiqueta = "Riesgo intermedio", color = "#E8C28E" }, + { clave = "ALTO", etiqueta = "Riesgo alto", color = "#D98E4A" }, +] +estado = "provisional" +fuente = "Propuesta T-21d: tres bandas fijas con dos cortes (comun.riesgos.*); los nombres siguen a MD-Q5" + +[cacu.calidad_insatisfactoria] +valor = "INSATISFACTORIO" +estado = "provisional" +fuente = "kpi_catalog_cacu_eu.yaml CACU_EU8; Core admite también \"0\" (CITO_CALIDAD_ESPECIMEN_ALIAS); valores reales sin confirmar" + +[cama.calidad_satisfactoria] +valor = "SATISFACTORIO" +estado = "provisional" +fuente = "kpi_catalog_cama_eu.yaml CAMA_EU8; mast_calidad_imagen es texto libre, valores reales sin confirmar" + +[cacu.grupos_edad] +# Grupos de edad del estrato `grupo_edad`: pares [mínimo, máximo] en años cumplidos, incluidos, +# contiguos. Se agrega un grupo abierto en cada extremo ("<25", "65+"). +valor = [[25, 34], [35, 44], [45, 54], [55, 64]] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar" + +[cama.grupos_edad] +valor = [[40, 49], [50, 59], [60, 69]] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar" + +# =========================================================================== +# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8) +# +# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la +# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses". +# Las listas y tablas se guardan en def_parametro como JSON. +# El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga. +# Documentos citados (repositorio analisis-tea, carpeta docs/): +# lista = lista_indicadores_TEA_v2.md · contexto = contexto_reporte_pipeline_TEA.md +# estandares = estandares_indicadores_TEA.md · modif = modificaciones.md +# =========================================================================== + +[tea.cohorte.edad_min_meses] +valor = 16 +estado = "confirmado" +fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)" + +[tea.cohorte.edad_max_meses] +valor = 36 +estado = "confirmado" +fuente = "contexto §1 (director)" + +[tea.cohorte.dias_por_mes] +# Mes medio para pasar días a meses (edad con un decimal). +valor = 30.4375 +estado = "confirmado" +fuente = "analisis-tea/tea/comun.py, edad_meses" + +[tea.cohorte.plazo_ados2_eeg_dias] +# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo. +valor = 30 +estado = "confirmado" +fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)" + +[tea.cohorte.ventanas] +# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos. +valor = [ + { clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" }, + { clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" }, + { clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" }, +] +estado = "confirmado" +fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)" + +[tea.instrumentos.informantes_ramos] +# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre. +valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"] +estado = "confirmado" +fuente = "contexto §1 (equipo); psicología no registra al cuidador principal" + +[tea.instrumentos.informantes_otros] +valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"] +estado = "confirmado" +fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21" + +[tea.ramos.areas] +# «TOTAL» no cuenta como área. +valor = [ + { clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" }, + { clave = "LINGUISTICO", etiqueta = "Lingüístico" }, + { clave = "FISICO", etiqueta = "Físico" }, + { clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" }, + { clave = "ADAPTATIVO", etiqueta = "Adaptativo" }, +] +estado = "confirmado" +fuente = "spec v2, catálogo de ins_area; contexto §1" + +[tea.poblacion.css_min_tea] +# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor. +valor = 3 +estado = "confirmado" +fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo" + +[tea.diagnostico.cie_tea] +# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840). +valor = ["F840"] +estado = "confirmado" +fuente = "usuario (2026-10-15): solo F84.0 (autismo)" + +[tea.diagnostico.instrumentos_mchat] +# M25: valores de psi_instrumento_tamizaje que son un M-CHAT. +valor = ["M_CHAT_R", "M_CHAT_RF"] +estado = "confirmado" +fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)" + +[tea.atencion.plazo_referencia_evaluacion_dias] +# K1: inicio de la evaluación a más tardar este número de días después de la referencia. +valor = 90 +estado = "confirmado" +fuente = "estandares: NICE QS51, enunciado 1 (3 meses)" + +[tea.parto.apgar_corte] +# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10). +valor = 7 +estado = "confirmado" +fuente = "lista, M17: menor de 7, 7, y 8 a 10" + +# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar: +# un cambio pide volver a cargar. +[tea.antecedentes_maternos.no_registrado] +valor = "NO_REGISTRADO" +estado = "confirmado" +fuente = "spec v2: NO_REGISTRADO = sin dato" + +[tea.antecedentes_maternos.hipertension_ninguno] +valor = "NINGUNO" +estado = "confirmado" +fuente = "spec v2, catálogo de amg_hipertension_preeclampsia" + +[tea.antecedentes_maternos.embarazo_no_unico] +valor = ["GEMELAR", "TRIPLE_O_MAS"] +estado = "confirmado" +fuente = "spec v2, catálogo de amg_embarazo_multiple" + +[tea.antecedentes_maternos.liquido_anormal] +valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"] +estado = "confirmado" +fuente = "spec v2, catálogo de amg_liquido_amniotico" + +[tea.supresion.activa] +# Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se +# suprime nada, aunque comun.umbral_supresion tenga valor. +valor = false +estado = "provisional" +fuente = "modif: supresión opcional, apagada por omisión (tablero interno); CaCu tiene la suya sin decidir (bloqueos.md D1)" + +[tea.presentacion.fuente] +valor = "Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL" +estado = "confirmado" +fuente = "lista: toda figura lleva la fuente" + +[tea.presentacion.leyenda] +valor = "Uso exclusivo de investigación. No usar para decisiones clínicas." +estado = "confirmado" +fuente = "marco_regulatorio_TEA.md §3" + +# Catálogos de las composiciones (C2): clave (como en la base), etiqueta y color. +# Colores: paleta de ejemplo del estándar común, hasta que se fije la hoja de estilo. +[tea.catalogos.sin_dato] +valor = { etiqueta = "Sin dato", color = "#C9CDD2" } +estado = "confirmado" +fuente = "lista: «sin dato» siempre se muestra como categoría propia" + +[tea.catalogos.sexo] +valor = [ + { clave = "F", etiqueta = "Femenino", color = "#E0A030" }, + { clave = "M", etiqueta = "Masculino", color = "#2F6DB3" }, + { clave = "I", etiqueta = "Indeterminado", color = "#8A9199" }, +] +estado = "provisional" +fuente = "spec v2, pac_sexo; colores provisionales" + +[tea.catalogos.resultado_mchat] +valor = [ + { clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" }, + { clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" }, + { clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" }, +] +estado = "provisional" +fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales" + +[tea.catalogos.interpretacion_ramos] +valor = [ + { clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" }, + { clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" }, + { clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" }, +] +estado = "provisional" +fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales" + +[tea.catalogos.grado_hipoacusia] +valor = [ + { clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" }, + { clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" }, + { clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" }, + { clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" }, + { clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" }, + { clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" }, +] +estado = "provisional" +fuente = "spec v2, pea_grado_hipoacusia; colores provisionales" + +[tea.catalogos.apgar_5min] +valor = [ + { clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" }, + { clave = "SIETE", etiqueta = "7", color = "#E8C28E" }, + { clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" }, +] +estado = "provisional" +fuente = "lista, M17; colores provisionales" + +# =========================================================================== +# CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml) +# =========================================================================== + +[cacu.citologia_anomala] +# Resultados de citología (células escamosas) que cuentan como anómalos en IND1. +valor = ["ASC-US", "ASC-H", "LIEBG", "LIEAG", "CIS"] +estado = "provisional" +fuente = "Usuario, 2026-10-24: ASC-US cuenta como anómalo. Antes (2026-10-12) quedaba fuera, como en kpi_catalog.yaml IND1 ('abnormal set is LSIL+, ASC-H, HSIL'); falta que clínica lo confirme y decidir glandulares y carcinoma (I-K61)" + +[cacu.biopsia_cis] +valor = ["CIS"] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). IND2b (I-K16): arranque con el grado CIS de Core (GradoCIN); falta que clínica lo confirme y ver que llega poblado en bx_cin_grado" + +[cacu.deteccion_grados] +# Grados de biopsia que cuentan como lesión detectada en CACU_EU13: el umbral CIN2+. +valor = ["LIEAG", "CIS", "CARCINOMA"] +estado = "provisional" +fuente = "Propuesta del catálogo (kpi_catalog_cacu_eu.yaml CACU_EU13: CIN2+), falta que clínica la confirme. CIN3+ no se puede: `bx_cin_grado` guarda CIN2 y CIN3 juntos como LIEAG (I-K15)" + +[cacu.citologia_alto_grado] +# Resultados de citología de alto grado: la población de CACU_CONFIRMACION_CITOLOGIA (la paciente entra si su +# última citología válida del periodo es una de estos) y los valores del estrato `citologia_alto_grado`. +valor = ["ASC-H", "LIEAG", "CIS"] +estado = "provisional" +fuente = "Usuario, 2026-10-24: confirmación por biopsia según resultado citológico, las tres peores categorías Bethesda; falta que clínica la confirme" + +# =========================================================================== +# CaCu · estatus de seguimiento ASCCP (T-24c): las reglas de `cacu/seguimiento.py` +# +# El código solo aplica estas reglas; cada una dice en su comentario las opciones que +# sabe aplicar. Una opción desconocida falla con un mensaje que lista las admitidas. +# Los textos se comparan en mayúsculas y sin acentos, por contención. +# =========================================================================== + +[cacu.seguimiento.marco] +# Qué estratificación de seguimiento se publica. Opciones: "estatus" (ASCCP), "ronda" (UE, todavía no). +valor = ["estatus"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22 (§5.1): ASCCP provisional; las rondas UE, después" + +[cacu.seguimiento.referencia] +# A qué fecha se evalúa el estatus en el estrato: "inicio_periodo" (lo que traía al entrar al +# periodo, como `grupo_edad`) o "fecha_corte" (al corte del reporte). +valor = "inicio_periodo" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo" + +[cacu.seguimiento.precedencia] +# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de +# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir). +# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo). +valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.colposcopia.evidencias] +# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto): +# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos` +# "cie" una nota de colposcopia con un CIE-10 de `colposcopia.cie` +# "diagnostico_texto" una nota de colposcopia cuyo diagnóstico en texto contiene uno de +# `colposcopia.diagnosticos` (la nota que llega «S/C») +# "orden_biopsia" una orden de biopsia (la solicitud) +# "biopsia" una biopsia reportada +# «Nota de colposcopia»: de una de `colposcopia.especialidades` y, con `colposcopia.requisito`, posterior +# a la cita de valoración. +valor = ["motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: el motivo, el CIE y el diagnóstico en texto, solo en notas de colposcopia" + +[cacu.seguimiento.colposcopia.requisito] +# Qué tiene que haber antes de una nota de colposcopia para que cuente. Opciones: +# "valoracion_previa" una cita de valoración anterior: la nota que resuelve una toma, con las reglas de +# CACU_DIAS_TOMA_DIAGNOSTICO (`cacu.diagnostico.cie`, `cacu.diagnostico.especialidades` +# y `cacu.horizontes.toma_diagnostico_dias`); es de donde sale la fecha de diagnóstico +# "ninguno" cuenta sola +valor = "valoracion_previa" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «si no hay cita de valoración, que es de la que se toma la fecha de diagnóstico, no puede haber cita de colposcopia»" + +[cacu.seguimiento.colposcopia.biopsia_requisito] +# Cuándo cuentan la orden de biopsia y la biopsia reportada. Opciones: +# "mismo_dia_que_colposcopia" la orden (o la solicitud de la reportada) es del mismo día que una nota de +# colposcopia válida de la paciente: la colposcopia es la madre de la biopsia +# "ninguno" cuentan solas +valor = "mismo_dia_que_colposcopia" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «la orden de biopsia debe ser expedida el mismo día que la de colposcopia»; «la colposcopia es padre de la biopsia»" + +[cacu.seguimiento.colposcopia.motivos] +# Textos del motivo de consulta de una nota de colposcopia que la indican (lista libre, en mayúsculas y sin acentos). +valor = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.colposcopia.especialidades] +# Especialidades de una nota de colposcopia (para el motivo, el CIE y el diagnóstico en texto). Opciones: +# el enum `Especialidad` de Core (MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA). +valor = ["CLINICA_MUJER_COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: la nota de colposcopia es de «Clínica de la Mujer y Colposcopia», no hay otra" + +[cacu.seguimiento.colposcopia.cie] +# CIE-10 de una nota de colposcopia que indican colposcopia, como los deja la carga (sin punto). +# Opciones: el enum CIE-10 compartido con dev-data. +valor = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme; B97.7 (VPH) agregado por el ejemplo del usuario (2026-10-22)" + +[cacu.seguimiento.colposcopia.diagnosticos] +# Textos del diagnóstico de una nota de colposcopia que indican colposcopia aunque el CIE llegue +# «S/C» (lista libre, en mayúsculas y sin acentos). +valor = ["VIRUS DEL PAPILOMA HUMANO"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «S/C y con Diagnóstico: VIRUS DEL PAPILOMA HUMANO»" + +[cacu.seguimiento.tratamiento.fuentes] +# Qué cuenta como tratamiento. Opciones: "nota_posterior_a_colposcopia" (una nota con un CIE-10 de +# `tratamiento.cie`, posterior en fecha a la primera evidencia de colposcopia). +valor = ["nota_posterior_a_colposcopia"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: el tratamiento está en la nota médica, después de una de colposcopia" + +[cacu.seguimiento.tratamiento.cie] +# CIE-10 de la nota de tratamiento, como los deja la carga. Opciones: el enum CIE-10 compartido. +valor = ["D06", "D060", "D061", "D067", "D069"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «un código CIE-10 anómalo, por ejemplo D06»" + +[cacu.seguimiento.insuficiente.regla] +# Cuándo la historia no alcanza. Opciones: "inicio_datos_posterior_a_alta", "sin_alta_registrada", +# "ambos", "nunca". Hoy no hay fecha de alta (derechohabiencia): con "inicio_datos_posterior_a_alta" +# se asume alta posterior al inicio de los datos y nadie cae; con "sin_alta_registrada", todas caerían. +valor = "inicio_datos_posterior_a_alta" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: sin columna de alta, se asume posterior" + +[cacu.seguimiento.vigilancia.especialidades] +# Especialidades de las citologías de vigilancia. Opciones: el enum `Especialidad` de Core. Se aplica +# solo cuando la especialidad de la citología se conoce (la de su orden): una paciente sale de +# vigilancia si todas sus citologías tienen especialidad conocida y ninguna está aquí. +valor = ["MEDICINA_FAMILIAR", "CLINICA_MUJER_COLPOSCOPIA"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: solo cuando se conoce" + +# =========================================================================== +# CaCu · la lista de seguimiento (T-24d): `GET /cacu/seguimiento`, `serving/seguimiento.py` +# =========================================================================== + +[cacu.seguimiento.ventana_meses] +# Meses hacia atrás desde el corte en los que un estudio mete a la paciente en la lista. Opciones: 1, 3, 6, 12. +valor = 3 +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.fecha_estudio] +# Desde qué fecha cuenta la ventana. Opciones: "toma" (la de la toma) o "reporte" (la de su resultado). +valor = "toma" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.estudios] +# Qué estudios meten a la paciente en la lista. Opciones: cualquier subconjunto de "citologia" y "vph". +valor = ["citologia", "vph"] +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +[cacu.seguimiento.resultado_mostrado] +# Qué citología mostrar si hay varias en la ventana. Opciones: "ultimo" o "mas_grave" (por el orden de +# `cacu.catalogos.citologia`, de menos a más grave; empate, la más reciente). El VPH muestra siempre el último. +valor = "ultimo" +estado = "provisional" +fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme" + +# Catálogo de resultados citológicos de CaCu (C2), de menos a más grave. Las claves son las +# de `CelulasEscamosas` en Core (`cit_celulas_escamosas`). +[cacu.catalogos.sin_dato] +valor = { etiqueta = "Sin dato", color = "#C9CDD2" } +estado = "confirmado" +fuente = "lista: «sin dato» siempre se muestra como categoría propia" + +[cacu.catalogos.citologia] +valor = [ + { clave = "NORMAL", etiqueta = "Normal", color = "#9DBFE3" }, + { clave = "ASC-US", etiqueta = "ASC-US", color = "#2F6DB3" }, + { clave = "LIEBG", etiqueta = "LIEBG", color = "#E8C28E" }, + { clave = "ASC-H", etiqueta = "ASC-H", color = "#D98E4A" }, + { clave = "LIEAG", etiqueta = "LIEAG", color = "#B55A1F" }, + { clave = "CIS", etiqueta = "Carcinoma in situ", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Las seis categorías de CelulasEscamosas (Core); falta decidir si se agrupan (indicadores.md pide cinco como máximo en la figura) y si entran glandulares y carcinoma invasor (I-K61); colores provisionales" + +[cacu.catalogos.resultado_anormal] +valor = [ + { clave = "NO_ANORMAL", etiqueta = "Sin anomalía", color = "#9DBFE3" }, + { clave = "ANORMAL", etiqueta = "Anormal", color = "#B55A1F" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Anormal es la lista `cacu.citologia_anomala` (la de IND1); colores provisionales" + +# Catálogo de BI-RADS de CaMa (C2). Las claves son las del staging (`mast_birads`). +[cama.catalogos.sin_dato] +valor = { etiqueta = "Sin dato", color = "#C9CDD2" } +estado = "confirmado" +fuente = "lista: «sin dato» siempre se muestra como categoría propia" + +[cama.catalogos.birads] +valor = [ + { clave = "B0", etiqueta = "BI-RADS 0", color = "#8A9199" }, + { clave = "B1", etiqueta = "BI-RADS 1", color = "#9DBFE3" }, + { clave = "B2", etiqueta = "BI-RADS 2", color = "#2F6DB3" }, + { clave = "B3", etiqueta = "BI-RADS 3", color = "#E8C28E" }, + { clave = "B4A", etiqueta = "BI-RADS 4A", color = "#E0A060" }, + { clave = "B4B", etiqueta = "BI-RADS 4B", color = "#CF7D3C" }, + { clave = "B4C", etiqueta = "BI-RADS 4C", color = "#C26A2B" }, + { clave = "B5", etiqueta = "BI-RADS 5", color = "#B55A1F" }, + { clave = "B6", etiqueta = "BI-RADS 6", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). fixture de CaMa (B0, B1, B2, B4). Subcategorías 4A, 4B y 4C: el hospital las reporta y llegan normalizadas (usuario, 2026-10-16). Un 4 sin subcategoría ya no tiene barra fija en 0: si llega alguno, se reporta tal cual después de «Sin dato», como todo valor fuera del catálogo, y sigue contando como sospecha y en BI-RADS 4 a 6 (cama.birads_sospecha, cama.birads_4_a_6). Colores provisionales" + +[cacu.catalogos.biopsia] +# Grados histológicos de la biopsia cervical (C2), de menos a más grave. Las claves son las +# de `GradoCIN` en Core (`bx_cin_grado`). +valor = [ + { clave = "NORMAL", etiqueta = "Normal", color = "#9DBFE3" }, + { clave = "LIEBG", etiqueta = "LIEBG (CIN 1)", color = "#E8C28E" }, + { clave = "LIEAG", etiqueta = "LIEAG (CIN 2 y 3)", color = "#D98E4A" }, + { clave = "CIS", etiqueta = "Carcinoma in situ", color = "#B55A1F" }, + { clave = "CARCINOMA", etiqueta = "Carcinoma invasor", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Los grados de GradoCIN (Core) menos DESCONOCIDO, que se reporta tal cual; colores provisionales" + +[cama.catalogos.biopsia] +# Grados histológicos de la biopsia de mama (C2), de menos a más grave. Las claves son las de +# `GradoHistologicoMama` en Core (`bx_grado_histologico`). +valor = [ + { clave = "BENIGNO", etiqueta = "Benigno", color = "#9DBFE3" }, + { clave = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ", color = "#D98E4A" }, + { clave = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme. Los grados de GradoHistologicoMama (Core) menos DESCONOCIDO, que se reporta tal cual; colores provisionales" + +[cama.biopsia_cancer] +# Grados de la biopsia de mama que cuentan como cáncer: el grupo «anómalo» de CAMA_BIOPSIAS. +valor = ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"] +estado = "provisional" +fuente = "Propuesta para poder agrupar, falta que clínica la confirme (usuario, 2026-10-13: par de gráficas de biopsias)" + +[cama.birads_gravedad] +# Las categorías de BI-RADS de menos a más grave, para ordenar su presentación. Es el mismo +# orden con que CAMA_BIRADS elige la categoría de cada paciente (`GRAVEDAD`, S-M54). +valor = ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"] +estado = "provisional" +fuente = "S-M54: un BI-RADS 0 (incompleto) pide más estudios y pesa más que uno benigno; falta que clínica lo confirme. Un 4 sin subcategoría pesa menos que 4A (usuario, 2026-10-16)" + +[cama.birads_sospecha] +# BI-RADS que piden biopsia: el denominador de CAMA_CONFIRMACION_BIRADS45. +valor = ["B4", "B4A", "B4B", "B4C", "B5"] +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme (usuario, 2026-10-13: «confirmación histopatológica BI-RADS 4/5»). Con las subcategorías 4A, 4B y 4C (usuario, 2026-10-16)" + +[cama.birads_4_a_6] +# BI-RADS que cuentan CAMA_BIRADS456_PACIENTE y CAMA_BIRADS456_MASTOGRAFIA: los de sospecha +# (4, 5) y la malignidad confirmada (6). No es `birads_sospecha`: ese es el denominador de la +# confirmación histopatológica, y un B6 ya está confirmado. +valor = ["B4", "B4A", "B4B", "B4C", "B5", "B6"] +estado = "provisional" +fuente = "Usuario, 2026-10-16: conteos de BI-RADS 4, 5 y 6 por paciente y por mastografía; falta que clínica lo confirme" + +[cama.catalogos.birads_4_a_6] +valor = [ + { clave = "B4A", etiqueta = "BI-RADS 4A", color = "#E0A060" }, + { clave = "B4B", etiqueta = "BI-RADS 4B", color = "#CF7D3C" }, + { clave = "B4C", etiqueta = "BI-RADS 4C", color = "#C26A2B" }, + { clave = "B5", etiqueta = "BI-RADS 5", color = "#B55A1F" }, + { clave = "B6", etiqueta = "BI-RADS 6", color = "#7A2E0E" }, +] +estado = "provisional" +fuente = "Subconjunto de cama.catalogos.birads, con los mismos colores. Sin B4: un 4 sin subcategoría se reporta tal cual después de «Sin dato» (usuario, 2026-10-16)" + +# =========================================================================== +# Periodo de observación: desde cuándo hay datos de cada proyecto +# =========================================================================== + +[cacu.observacion.inicio_datos] +# Primer día del que hay datos cargados. Antes de esa fecha no se sabe qué le pasó a la +# paciente: quien se tamizó antes parece nueva. Lo usa el paso `observar`. +valor = "2023-01-01" +estado = "sin_definir" +fuente = "indicadores_kit_0, issues del catálogo de CaCu (I-12): «con historia desde 2023»; falta que quien administra la fuente confirme la fecha de la primera extracción" + +[cama.observacion.inicio_datos] +valor = "2023-01-01" +estado = "sin_definir" +fuente = "Sin fuente propia: se copia el de CaCu para poder correr; falta la fecha de la primera extracción de CaMa" + +[tea.observacion.inicio_datos] +valor = "2025-01-01" +estado = "confirmado" +fuente = "responsable de TEA, 2026-10-21" + +# =========================================================================== +# Vínculos entre un resultado y su toma (paso `verificar_vinculos`) +# =========================================================================== + +[comun.vinculos.minimo_validos] +# Proporción mínima de filas con vínculo válido, de 0 a 1. Solo se exige si la arista se +# llama con `exigir=True` (`vinculos_del_proyecto` de webapi.orchestration): por debajo, falla en vez de dejar calcular con vínculos rotos. +valor = 0.95 +estado = "sin_definir" +fuente = "Sin decisión: 0.95 es un punto de partida para poder correr; falta medirlo con datos reales" + +# =========================================================================== +# Horizontes: una clave por par de eventos (MV-4). Días desde el primer evento en los que +# todavía se espera el segundo; el día en que se cumplen ya no se espera. +# =========================================================================== + +[cacu.horizontes.toma_reporte_dias] +# Días desde la toma en los que todavía se espera el resultado: pasado ese plazo sin +# resultado, el estudio ya no está «en observación» y cuenta como excluido de C3r. +valor = 60 +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme: no hay ventana de monitoreo fijada (usuario, 2026-10-13). S-K85 (indicadores_mvp.md): 60 es el de las pruebas de campo" + +[cama.horizontes.toma_reporte_dias] +valor = 60 +estado = "provisional" +fuente = "Propuesta para poder calcular, falta que clínica la confirme: no hay ventana de monitoreo fijada (usuario, 2026-10-13). S-K85 (indicadores_mvp.md): 60 es el de las pruebas de campo" + +[cacu.horizontes.toma_diagnostico_dias] +# Días desde la toma en los que una nota de diagnóstico todavía se le atribuye: la primera +# nota con un CIE-10 de `cacu.diagnostico.cie` antes de que se cumpla el plazo es su +# diagnóstico. Pasado el plazo sin nota, la toma cuenta como excluida de C3r (S-TD4). +valor = 180 +estado = "provisional" +fuente = "Arbitrario para poder calcular (usuario, 2026-10-16: «las ventanas de tiempo, dejarlas parametrizadas»); falta que clínica lo fije" + +[cama.horizontes.toma_diagnostico_dias] +valor = 180 +estado = "provisional" +fuente = "Arbitrario para poder calcular (usuario, 2026-10-16: «las ventanas de tiempo, dejarlas parametrizadas»); falta que clínica lo fije" + +# =========================================================================== +# Diagnóstico: las notas médicas que resuelven una toma y las que son antecedente (S-TD3) +# =========================================================================== +# Los CIE-10 van sin punto (C53.9 -> C539) y se comparan exactos: cada lista trae el código +# de tres caracteres y sus subcategorías. Se cambian aquí sin tocar el código. + +[cacu.diagnostico.cie] +# CACU_DIAS_TOMA_DIAGNOSTICO: CIE-10 de la nota que resuelven la toma, sea cual sea el +# resultado (usuario, 2026-10-16: «el diagnóstico no necesariamente tiene que ser maligno»): +# normal: Z01.4 (examen ginecológico) y Z12.4 (pesquisa de tumor del cuello uterino); +# VPH: B97.7 (papilomavirus); citología anormal: R87.6; +# lesión escamosa: N87.0, N87.1, N87.2 y N87.9 (displasia cervical leve, moderada, grave +# y sin especificar); +# cáncer: D06 (carcinoma in situ) y C53 (tumor maligno del cuello del útero). +valor = [ + "Z014", "Z124", + "B977", "R876", + "N87", "N870", "N871", "N872", "N879", + "D06", "D060", "D061", "D067", "D069", + "C53", "C530", "C531", "C538", "C539", +] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cacu.diagnostico.cie_antecedente] +# Una nota con uno de estos CIE-10 anterior a la toma deja fuera la toma: la paciente ya es +# un caso (S-TD2). Solo la incidencia, D06 y C53: con la lista amplia, cualquier consulta +# previa sacaría a la paciente del tamizaje. +valor = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cacu.diagnostico.especialidades] +# Las especialidades (código de `Core`, `nota_medica.enums.Especialidad`) cuyas notas +# resuelven la toma: las que dan el diagnóstico, no medicina familiar. +valor = ["CLINICA_MUJER_COLPOSCOPIA", "CIRUGIA_ONCOLOGICA"] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cama.diagnostico.cie] +# CAMA_DIAS_TOMA_DIAGNOSTICO: CIE-10 de la nota que resuelven la toma, sea cual sea el resultado: +# normal: Z12.3 (pesquisa de tumor de la mama); +# benignos: N60 (displasia mamaria benigna), N61 a N64 (otros trastornos de la mama) y +# D24 (tumor benigno de la mama); +# imagen anormal: R92; +# cáncer: D05 (carcinoma in situ) y C50 (tumor maligno de la mama). +valor = [ + "Z123", + "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", + "N61", "N62", "N63", + "N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", + "D24", "R92", + "D05", "D050", "D051", "D057", "D059", + "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509", +] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cama.diagnostico.cie_antecedente] +# Como en CaCu: solo la incidencia, D05 y C50. +valor = [ + "D05", "D050", "D051", "D057", "D059", + "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509", +] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" + +[cama.diagnostico.especialidades] +# El catálogo de `Core` no tiene una clínica de mama: queda cirugía oncológica. +valor = ["CIRUGIA_ONCOLOGICA"] +estado = "provisional" +fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles" diff --git a/webapi/orchestration/reference/periods.py b/webapi/orchestration/reference/periods.py new file mode 100644 index 0000000..4d8f6a7 --- /dev/null +++ b/webapi/orchestration/reference/periods.py @@ -0,0 +1,154 @@ +"""`dim_periodo`: una sola definición de a qué periodo pertenece una fecha. + +Se genera, no se escribe a mano ni se calcula con `strftime` en cada SQL +(ADR-003 §9, regla 4). Cada periodo es el intervalo `[inicio, fin)`. + +Hay un tipo por granularidad (S-M4, T-1 de v0.4.0); el `periodo_id` dice +el tipo y ordena bien como texto: + + dia 2025-03-05 un día + semana_epidemiologica 2025-SE10 domingo a domingo + semana_habil 2025-SH10 lunes a sábado: los cinco días hábiles + semana_iso 2025-W10 lunes a lunes, ISO 8601 + mes 2025-03 + bimestre 2025-B2 enero-febrero = B1 + trimestre 2025-T1 enero-marzo = T1 + semestre 2025-S1 enero-junio = S1 + +`anio` es el año del periodo; en las semanas, el año de la semana, que +puede empezar en diciembre del anterior. `semestre` es el semestre que +contiene el inicio del periodo. +""" + +from collections.abc import Callable, Iterable +from datetime import date, timedelta + +from core.indicadores.registro import DimPeriodoBase +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + +Generador = Callable[[type[DimPeriodoBase], int], list[DimPeriodoBase]] + + +class TipoDePeriodoDesconocido(ValueError): + """Se pidió un tipo de periodo que el kit no sabe generar.""" + + +def semestres(anio_inicio: int, anio_fin: int, *, tablas: TablasKit) -> list[DimPeriodoBase]: + """Los semestres de `anio_inicio` a `anio_fin`, los dos incluidos.""" + return periodos("semestre", anio_inicio, anio_fin, tablas=tablas) + + +def periodos( + tipo: str, anio_inicio: int, anio_fin: int, *, tablas: TablasKit +) -> list[DimPeriodoBase]: + """Los periodos de un tipo cuyo año va de `anio_inicio` a `anio_fin`, los dos incluidos.""" + if tipo not in _GENERADORES: + raise TipoDePeriodoDesconocido( + f"No hay periodos de tipo {tipo!r}; los tipos son {', '.join(TIPOS_PERIODO)}." + ) + generar = _GENERADORES[tipo] + return [ + fila for anio in range(anio_inicio, anio_fin + 1) for fila in generar(tablas.DimPeriodo, anio) + ] + + +def periodos_de_tipos( + tipos: Iterable[str], anio_inicio: int, anio_fin: int, *, tablas: TablasKit +) -> list[DimPeriodoBase]: + """Los periodos de varios tipos, uno tras otro. Los `periodo_id` no chocan entre tipos.""" + return [fila for tipo in tipos for fila in periodos(tipo, anio_inicio, anio_fin, tablas=tablas)] + + +def inicio_semana_epidemiologica(anio: int) -> date: + """El domingo en que empieza la semana epidemiológica 1 de `anio`. + + La semana 1 es la primera que tiene al menos cuatro días en el año + (regla de la Secretaría de Salud y del CDC): la que contiene el 4 de + enero. Puede empezar entre el 29 de diciembre y el 4 de enero. + """ + cuatro_de_enero = date(anio, 1, 4) + return cuatro_de_enero - timedelta(days=(cuatro_de_enero.weekday() + 1) % 7) + + +def _fila( + modelo: type[DimPeriodoBase], periodo_id: str, tipo: str, inicio: date, fin: date, anio: int +) -> DimPeriodoBase: + return modelo( + periodo_id=periodo_id, + tipo=tipo, + inicio=inicio, + fin=fin, + anio=anio, + semestre=1 if inicio.month <= 6 else 2, + ) + + +def _dias(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]: + primero, siguiente = date(anio, 1, 1), date(anio + 1, 1, 1) + return [ + _fila(modelo, dia.isoformat(), "dia", dia, dia + timedelta(days=1), anio) + for dia in (primero + timedelta(days=n) for n in range((siguiente - primero).days)) + ] + + +def _por_meses(meses: int, tipo: str, prefijo: str) -> Generador: + """Los periodos de `meses` meses que parten el año desde enero.""" + + def generar(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]: + filas = [] + for numero in range(1, 12 // meses + 1): + mes = (numero - 1) * meses + 1 + inicio = date(anio, mes, 1) + fin = date(anio + 1, 1, 1) if mes + meses > 12 else date(anio, mes + meses, 1) + periodo_id = f"{anio}-{numero:02d}" if not prefijo else f"{anio}-{prefijo}{numero}" + filas.append(_fila(modelo, periodo_id, tipo, inicio, fin, anio)) + return filas + + return generar + + +def _semanas( + tipo: str, prefijo: str, inicio_del_anio: Callable[[int], date], dias_desde_el_inicio: tuple[int, int] +) -> Generador: + """Las semanas de un año: de `inicio_del_anio(anio)` al de `anio + 1`, de siete en siete. + + `dias_desde_el_inicio` recorta cada semana: (0, 7) es la semana entera; + (1, 6), de lunes a sábado en una semana que empieza en domingo. + """ + desde, hasta = dias_desde_el_inicio + + def generar(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]: + primera, siguiente = inicio_del_anio(anio), inicio_del_anio(anio + 1) + return [ + _fila( + modelo, + f"{anio}-{prefijo}{numero:02d}", + tipo, + semana + timedelta(days=desde), + semana + timedelta(days=hasta), + anio, + ) + for numero, semana in enumerate( + (primera + timedelta(weeks=n) for n in range((siguiente - primera).days // 7)), + start=1, + ) + ] + + return generar + + +_GENERADORES: dict[str, Generador] = { + "dia": _dias, + "semana_epidemiologica": _semanas("semana_epidemiologica", "SE", inicio_semana_epidemiologica, (0, 7)), + # La semana hábil lleva el número y el año de la epidemiológica que la contiene (S-M7). + "semana_habil": _semanas("semana_habil", "SH", inicio_semana_epidemiologica, (1, 6)), + "semana_iso": _semanas("semana_iso", "W", lambda anio: date.fromisocalendar(anio, 1, 1), (0, 7)), + "mes": _por_meses(1, "mes", ""), + "bimestre": _por_meses(2, "bimestre", "B"), + "trimestre": _por_meses(3, "trimestre", "T"), + "semestre": _por_meses(6, "semestre", "S"), +} + +TIPOS_PERIODO = tuple(_GENERADORES) diff --git a/webapi/orchestration/reference/rules.py b/webapi/orchestration/reference/rules.py new file mode 100644 index 0000000..fe11c8f --- /dev/null +++ b/webapi/orchestration/reference/rules.py @@ -0,0 +1,101 @@ +"""Registro L2 de parámetros: `parametros.toml` cargado en `def_parametro`. + +El archivo en git es la única fuente de verdad. La tabla se reconstruye +entera en cada carga; nadie la edita a mano (ADR-003 §9). +""" + +import hashlib +import json +import tomllib +from pathlib import Path + +from core.indicadores.registro import DefParametroBase +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + +# Un solo archivo para todos los proyectos, dentro del paquete. +RUTA_PARAMETROS = Path(__file__).resolve().parent / "parametros.toml" +ESTADOS_PARAMETRO = ("sin_definir", "provisional", "confirmado") + + +class ParametroSinDefinir(LookupError): + """Se pidió un parámetro que nadie ha decidido todavía.""" + + +def leer_parametros(ruta: Path, *, tablas: TablasKit) -> list[DefParametroBase]: + """Lee el archivo y devuelve una fila por parámetro, ya validada. + + Un parámetro es una tabla con algún valor que no es tabla; su clave es + la ruta de secciones con puntos: `[tea.cohorte.edad_min_meses]` da + `"tea.cohorte.edad_min_meses"`. Una tabla sin esas llaves es una + sección más. + """ + contenido = Path(ruta).read_bytes() + toml_sha = hashlib.sha256(contenido).hexdigest() + secciones = tomllib.loads(contenido.decode("utf-8")) + return [ + _a_fila(tablas.DefParametro, clave, parametro, toml_sha) + for clave, parametro in _parametros_de(secciones) + ] + + +def valores_del_archivo(ruta: Path = RUTA_PARAMETROS) -> dict: + """Clave -> valor de cada parámetro del archivo, sin estado ni base. + + Para quien necesita una regla antes de que exista `def_parametro` + (los antecedentes de TEA, al cargar). No comprueba el estado. + """ + secciones = tomllib.loads(Path(ruta).read_text(encoding="utf-8")) + return {clave: parametro.get("valor") for clave, parametro in _parametros_de(secciones)} + + +def valor_de( + sesion: Session, clave: str, *, tablas: TablasKit, permitir_sin_definir: bool = False +): + """El valor de un parámetro. + + Un parámetro `sin_definir` trae un valor que solo permite correr: hay que pedirlo a propósito con `permitir_sin_definir=True`. + """ + fila = sesion.get(tablas.DefParametro, clave) + if fila is None: + raise KeyError(f"No existe el parámetro {clave!r}.") + if fila.estado == "sin_definir" and not permitir_sin_definir: + raise ParametroSinDefinir( + f"El parámetro {clave!r} está sin definir ({fila.fuente})." + ) + return json.loads(fila.valor) + + +def _parametros_de(seccion: dict, ruta: tuple[str, ...] = ()): + """(clave, tabla) de cada parámetro, en el orden del archivo.""" + for nombre, contenido in seccion.items(): + if not isinstance(contenido, dict): + raise ValueError(f"{'.'.join(ruta) or 'El archivo'}: {nombre!r} no es una sección.") + # Una sección solo tiene tablas; un parámetro tiene al menos un valor suelto + # (`estado`, `fuente`). Así una sección se puede llamar `fuente`. + if not all(isinstance(valor, dict) for valor in contenido.values()): + yield ".".join((*ruta, nombre)), contenido + else: + yield from _parametros_de(contenido, (*ruta, nombre)) + + +def _a_fila( + modelo: type[DefParametroBase], clave: str, parametro: dict, toml_sha: str +) -> DefParametroBase: + # Solo un parámetro sin definir puede no tener valor todavía. + obligatorias = {"estado", "fuente"} | ( + set() if parametro.get("estado") == "sin_definir" else {"valor"} + ) + faltan = obligatorias - set(parametro) + if faltan: + raise ValueError(f"Al parámetro {clave!r} le falta {sorted(faltan)}.") + if parametro["estado"] not in ESTADOS_PARAMETRO: + raise ValueError(f"Parámetro {clave!r}: estado desconocido {parametro['estado']!r}.") + return modelo( + clave=clave, + valor=json.dumps(parametro.get("valor"), ensure_ascii=False), + estado=parametro["estado"], + fuente=parametro["fuente"], + toml_sha=toml_sha, + ) diff --git a/webapi/orchestration/reference/support.py b/webapi/orchestration/reference/support.py new file mode 100644 index 0000000..8992cf5 --- /dev/null +++ b/webapi/orchestration/reference/support.py @@ -0,0 +1,38 @@ +"""Las tablas de apoyo que salen de los TOML (I-MD27, T-24f): `dim_fecha` y `dim_grupo_edad`. + +Las usan los estratos que cruzan fechas (`grupo_edad`: la edad cumplida, portable entre +SQLite y Postgres). Las escribe la arista `registro` de webapi.orchestration; aquí solo se arman: + + filas_de_dim_fecha de `comun.dim_fecha.desde` a `hasta`, como diccionarios para un + INSERT en bloque (se arman una vez por proceso: son decenas de miles) + grupos_de_edad_de los grupos de `.grupos_edad`, o `None` si el proyecto no + tiene cortes (TEA) + +`comun.dim_fecha.desde` es fijo porque `dia_num` y `dia_habil_num` se cuentan desde él. +""" + +from collections.abc import Mapping +from datetime import date +from functools import lru_cache + +from webapi.orchestration.reference.age_groups import grupos_de_cortes +from webapi.orchestration.reference.dates import dias +from webapi.orchestration.tables import TablasKit, tablas_de + +CLAVE_DIM_FECHA_DESDE = "comun.dim_fecha.desde" + + +def filas_de_dim_fecha(valores: Mapping, hasta: date, *, proyecto: str) -> list[dict]: + """Los días de `comun.dim_fecha.desde` a `hasta`, como diccionarios de `dim_fecha`.""" + return list(_dias(date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE]), hasta, proyecto)) + + +def grupos_de_edad_de(proyecto: str, valores: Mapping, *, tablas: TablasKit) -> list | None: + """Los grupos de edad de `.grupos_edad` (más los dos abiertos), o `None` si no tiene cortes.""" + cortes = valores.get(f"{proyecto}.grupos_edad") + return None if cortes is None else grupos_de_cortes(cortes, tablas=tablas) + + +@lru_cache(maxsize=8) +def _dias(desde: date, hasta: date, proyecto: str) -> tuple[dict, ...]: + return tuple(fila.model_dump() for fila in dias(desde, hasta, tablas=tablas_de(proyecto))) diff --git a/webapi/orchestration/silver/__init__.py b/webapi/orchestration/silver/__init__.py new file mode 100644 index 0000000..32e37cd --- /dev/null +++ b/webapi/orchestration/silver/__init__.py @@ -0,0 +1,10 @@ +"""La plata de dos tablas (F5, ADR-MD-007): de staging a `persona`, `procedimiento` y `observacion_clinica`. + + procedimiento.py `DeStaging`, `plata_desde_staging` y el orden de escritura por padres + carga.py `carga_desde_staging`: de las filas de staging a las personas y la plata + valores.py las normalizaciones de un valor de staging + personas.py de una fila de pacientes a `persona` + ordenes_y_notas.py la orden de estudio y la nota médica de CaCu y CaMa + periodo_observacion.py desde y hasta cuándo hay datos de cada paciente + vistas.py la DDL de `v_persona` +""" diff --git a/webapi/orchestration/silver/cacu.py b/webapi/orchestration/silver/cacu.py new file mode 100644 index 0000000..2a264ea --- /dev/null +++ b/webapi/orchestration/silver/cacu.py @@ -0,0 +1,69 @@ +"""CaCu en la plata de dos tablas (ADR-MD-007), por staging directo (T-20c, ADR-MD-009). + +`DESDE_STAGING`: qué procedimientos salen de cada fila de staging, con la normalización como columnas +derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`). +""" + +from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente +from core.cacu.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad + +from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio +from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre + +PACIENTES = Paciente # de donde salen las personas +ESPECIALIDADES = {e.value for e in Especialidad} +LA_TOMA_DE_SU_FILA = Padre(estudio_id="citologia", clase="toma", fuente_id="cit_id", tabla=CitologiaCervical.__tablename__) +LA_ORDEN_DEL_ESTUDIO = Padre(por_numero_de_orden="ord_numero_hospital") + + +def _genotipo_16_18(fila): + genotipos = (fila.cit_vph_genotipo_16, fila.cit_vph_genotipo_18) + return None if genotipos == (None, None) else int(any(genotipos)) + + +# La biopsia (T-22h, I-MD23): solicitada, es una `orden` del estudio `biopsia` que cuelga de la toma que la +# originó; su reporte llega después como hija `reporte`, sin reescribir la orden. Pasa de staging solo lo +# realizado: la que trae fecha de solicitud o de reporte. Con reporte y sin solicitud, la orden queda sin fecha. +def _biopsia_que_pasa(fila) -> bool: + return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None + + +DESDE_STAGING = ( + DeStaging( + CitologiaCervical, "cit_id", "toma", estudio_id="citologia", fecha="cit_fecha_toma", + padres=(LA_ORDEN_DEL_ESTUDIO,), columnas={"orden_numero": "ord_numero_hospital"}, + resultados={"cit_calidad_especimen": "citologia.calidad_muestra"}, + ), + # Un resultado sin fecha de reporte todavía no es un resultado: la fila no da reporte. + DeStaging( + CitologiaCervical, "cit_id", "reporte", estudio_id="citologia", fecha="cit_fecha_reporte", + solo_si=lambda f: f.cit_fecha_reporte is not None, padres=(LA_TOMA_DE_SU_FILA,), + resultados={ + "cit_celulas_escamosas": "citologia.bethesda", + "cit_celulas_glandulares": "citologia.celulas_glandulares", + "cit_carcinoma_invasor": "citologia.carcinoma_invasor", + "cit_dx_lesion": "citologia.dx_lesion", + }, + ), + # El VPH de la misma muestra, si se hizo; con la fecha del reporte de la citología (S-K38). + DeStaging( + CitologiaCervical, "cit_id", "reporte", estudio_id="vph", fecha="cit_fecha_reporte", + solo_si=lambda f: f.cit_fecha_reporte is not None and f.cit_vph_resultado is not None, + padres=(LA_TOMA_DE_SU_FILA,), derivadas={"genotipo_16_18": _genotipo_16_18}, + resultados={ + "cit_vph_resultado": "vph.resultado", + "genotipo_16_18": "vph.genotipo_16_18", + "cit_vph_genotipo_16": "vph.genotipo_16", + "cit_vph_genotipo_18": "vph.genotipo_18", + }, + ), + DeStaging( + BiopsiaCervical, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud", + solo_si=_biopsia_que_pasa, padres=(LA_TOMA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"}, + hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte", + resultados={"bx_cin_grado": "biopsia.grado"}),), + ), + orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES), + # El motivo de consulta y el diagnóstico en texto: de ahí sale la colposcopia del estatus de seguimiento (T-24b, T-24c). + nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, con_textos=True), +) diff --git a/webapi/orchestration/silver/cama.py b/webapi/orchestration/silver/cama.py new file mode 100644 index 0000000..e81acba --- /dev/null +++ b/webapi/orchestration/silver/cama.py @@ -0,0 +1,46 @@ +"""CaMa en la plata de dos tablas (ADR-MD-007), por staging directo (T-20c, ADR-MD-009). + +`DESDE_STAGING`: qué procedimientos salen de cada fila de staging, con la normalización como columnas +derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`). +""" + +from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente +from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad + +from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio +from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre + +PACIENTES = Paciente # de donde salen las personas +ESPECIALIDADES = {e.value for e in Especialidad} +# La toma de un resultado: la mastografía de su fila (BI-RADS) o la que la originó (`mast_id` de la biopsia). +LA_MASTOGRAFIA_DE_SU_FILA = Padre(estudio_id="mastografia", clase="toma", fuente_id="mast_id", tabla=Mastografia.__tablename__) +LA_ORDEN_DEL_ESTUDIO = Padre(por_numero_de_orden="ord_numero_hospital") + +# La biopsia (T-22h, I-MD23): solicitada, es una `orden` del estudio `biopsia` que cuelga de la toma que la +# originó; su reporte llega después como hija `reporte`, sin reescribir la orden. Pasa de staging solo lo +# realizado: la que trae fecha de solicitud o de reporte. Con reporte y sin solicitud, la orden queda sin fecha. +def _biopsia_que_pasa(fila) -> bool: + return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None + + +DESDE_STAGING = ( + DeStaging( + Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma", + padres=(LA_ORDEN_DEL_ESTUDIO,), columnas={"orden_numero": "ord_numero_hospital"}, + resultados={"mast_calidad_imagen": "mastografia.calidad_imagen"}, + ), + # Un resultado sin fecha de reporte todavía no es un resultado. + 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,), + resultados={"mast_birads": "mastografia.birads"}, + ), + 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"}, + hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte", + resultados={"bx_grado_histologico": "biopsia.grado"}),), + ), + orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES), + nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES), +) diff --git a/webapi/orchestration/silver/loads.py b/webapi/orchestration/silver/loads.py new file mode 100644 index 0000000..d545d62 --- /dev/null +++ b/webapi/orchestration/silver/loads.py @@ -0,0 +1,47 @@ +"""La carga del staging directo (T-20c): de las filas de staging a las personas y la plata. Pura. + +En un paso: las personas salen de la tabla de pacientes del proyecto (`

/plata.PACIENTES`) +y los procedimientos y observaciones, de `

/plata.DESDE_STAGING`. Lo escribe Persistance +(`guardar_carga_en`) por el modelo `carga` de webapi.orchestration. +""" + +from collections.abc import Iterable, Mapping +from importlib import import_module +from typing import NamedTuple + +from webapi.orchestration.silver.persons import a_persona +from webapi.orchestration.silver.procedures import LotePlata, plata_desde_staging +from webapi.orchestration.reference.catalogs import catalogo_desde_toml, codigos_hospital, ruta_de_catalogo +from webapi.orchestration.tables import tablas_de + + +class CargaDesdeStaging(NamedTuple): + fuente: str # las tablas de staging que dan procedimientos, en el orden de `DESDE_STAGING` + personas: list + plata: LotePlata + + +def _plata(proyecto: str): + return import_module(f"webapi.orchestration.silver.{proyecto}") + + + +def tablas_de_staging(proyecto: str) -> tuple[type, ...]: + """Las tablas de staging que lee la carga: la de pacientes y las de `DESDE_STAGING`, sin repetir.""" + plata = _plata(proyecto) + return (plata.PACIENTES, *dict.fromkeys(c.staging for c in plata.DESDE_STAGING)) + + +def carga_desde_staging(filas: Mapping[str, Iterable], *, proyecto: str) -> CargaDesdeStaging: + """Las personas y la plata de un proyecto, desde sus filas de staging (tabla -> filas).""" + plata = _plata(proyecto) + tablas = tablas_de(proyecto) + lote = plata_desde_staging( + filas, correspondencias=plata.DESDE_STAGING, + catalogo=catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas), + codigos_hospital=codigos_hospital(proyecto), + pacientes=(p.pac_id for p in filas.get(plata.PACIENTES.__tablename__, ())), + ) + personas = [a_persona(paciente, tablas=tablas) for paciente in filas.get(plata.PACIENTES.__tablename__, ())] + fuente = ", ".join(dict.fromkeys(c.staging.__tablename__ for c in plata.DESDE_STAGING)) + return CargaDesdeStaging(fuente, personas, lote) diff --git a/webapi/orchestration/silver/observation_periods.py b/webapi/orchestration/silver/observation_periods.py new file mode 100644 index 0000000..13f1edb --- /dev/null +++ b/webapi/orchestration/silver/observation_periods.py @@ -0,0 +1,97 @@ +"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente. + +Un indicador que mira hacia atrás (¿es su primera citología?) o hacia +adelante (¿llegó la biopsia?) necesita saber cuánto se pudo observar a la +paciente. Sin eso, quien se tamizó antes de que empezaran los datos +parece nueva, y a quien se tamizó ayer parece que no le llegó nada. + +El periodo es el de la extracción: empieza el día que dice la regla +`.observacion.inicio_datos` y termina en la fecha de corte (la +de la última carga, si no se da otra). Es el mismo para todas las +pacientes; la tabla es por paciente para cuando haya una fuente mejor +(alta y baja de la derechohabiencia). Aquí se calculan las filas; las escribe +`ObservacionRepository` de Persistance (plata), en la arista `observar`. +""" + +import json +from datetime import date, datetime + +from sqlmodel import Session, func, select + +from webapi.orchestration.reference.rules import ParametroSinDefinir +from webapi.orchestration.tables import tablas_de + +TIPO_EXTRACCION = "extraccion" + + +class ObservacionSinCorte(ValueError): + """No se dio fecha de corte y no hay ninguna carga de donde tomarla.""" + + +def clave_de_inicio(proyecto: str) -> str: + """La regla que dice desde cuándo hay datos del proyecto.""" + return f"{proyecto}.observacion.inicio_datos" + + +def periodos_de_observacion( + sesion: Session, proyecto: str, *, corte: date | None = None, permitir_sin_definir: bool = False +) -> list: + """Las filas de `periodo_observacion`: un periodo de extracción por persona. Solo lee. + + Necesita las personas (la carga) y la regla en `def_parametro` (el registro). + `corte` es el último día observado; sin él, el de la última carga. Una regla + sin definir hay que pedirla a propósito, como en el cálculo. + + Raises: + KeyError: la regla no está en `def_parametro`. + ParametroSinDefinir: la regla está sin definir y no se pidió permitirla. + ObservacionSinCorte: no hay corte ni cargas. + ValueError: el corte es anterior al inicio de los datos. + """ + tablas = tablas_de(proyecto) + clave = clave_de_inicio(proyecto) + inicio = _inicio(clave, sesion.get(tablas.DefParametro, clave), permitir_sin_definir) + corte = _corte(fecha_de_ultima_carga(sesion, tablas) if corte is None else corte, inicio) + personas = sesion.exec(select(tablas.Persona).order_by(tablas.Persona.pac_id)).all() + return _periodos(tablas, inicio, corte, personas) + + +def _inicio(clave: str, regla, permitir_sin_definir: bool) -> date: + if regla is None: + raise KeyError(f"No existe el parámetro {clave!r}: corra la arista `registro`.") + if regla.estado == "sin_definir" and not permitir_sin_definir: + raise ParametroSinDefinir(f"El parámetro {clave!r} está sin definir ({regla.fuente}).") + return date.fromisoformat(json.loads(regla.valor)) + + +def _corte(corte, inicio: date) -> date: + if corte is None: + raise ObservacionSinCorte("No se dio corte y no hay ninguna carga de donde tomarlo.") + corte = a_fecha(corte) + if corte < inicio: + raise ValueError(f"El corte ({corte}) es anterior al inicio de los datos ({inicio}).") + return corte + + +def _periodos(tablas, inicio: date, corte: date, personas) -> list: + return [ + tablas.PeriodoObservacion( + pac_id=persona.pac_id, fecha_inicio=inicio, fecha_fin=corte, tipo_periodo=TIPO_EXTRACCION + ) + for persona in personas + ] + + +def fecha_de_ultima_carga(sesion: Session, 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() + return None if ultima is None else a_fecha(ultima) + + +def a_fecha(valor) -> date: + """A date however the engine returns it: text, date or date-time.""" + if isinstance(valor, datetime): + return valor.date() + if isinstance(valor, date): + return valor + return date.fromisoformat(str(valor)[:10]) diff --git a/webapi/orchestration/silver/orders_and_notes.py b/webapi/orchestration/silver/orders_and_notes.py new file mode 100644 index 0000000..f7ecde6 --- /dev/null +++ b/webapi/orchestration/silver/orders_and_notes.py @@ -0,0 +1,73 @@ +"""La orden de estudio y la nota médica de CaCu y CaMa en el staging directo (T-20c). + +El staging de los dos proyectos trae las mismas columnas (`ordenesestudio`, `notamedica`); cada uno +da sus tablas y su catálogo de especialidades. Es la normalización que hacían `cdm/ordenes.py` y +`cdm/notas.py`, como columnas derivadas: +- una orden es lo que se pidió, se haya hecho o no; sin ninguna fecha no es una orden, y su fecha es + la de emisión o, si falta, la de solicitud; +- la especialidad se guarda en el código de Core (nula si no se reconoce) y, como `valor_fuente`, tal + como llegó; +- el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`; +- el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b), + sin normalizarlos (I-K61). +""" + +from collections.abc import Collection, Mapping + +from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio +from webapi.orchestration.silver.procedures import DeStaging + + +def especialidad(columna: str, alias: Mapping[str, str], codigos: Collection[str]) -> dict: + """Las derivadas de una especialidad: su código en Core y el texto tal como llegó.""" + return { + "especialidad": lambda f: codigo_de_especialidad(getattr(f, columna), alias, codigos), + "especialidad_fuente": lambda f: texto_limpio(getattr(f, columna)), + } + + +def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collection[str]) -> DeStaging: + return DeStaging( + staging, "ord_id", "orden", estudio_de="tipo_estudio", fecha="fecha_orden", + solo_si=lambda f: (f.ord_fecha or f.ord_fecha_solicitud) is not None, + derivadas={ + "tipo_estudio": lambda f: texto_limpio(f.ord_tipo_estudio), + "fecha_orden": lambda f: f.ord_fecha or f.ord_fecha_solicitud, + "intencion": lambda f: INTENCION, + "estatus": lambda f: texto_limpio(f.ord_estatus), + "diagnostico": lambda f: texto_limpio(f.ord_diagnostico), + **especialidad("ord_especialidad", alias, codigos), + }, + columnas={"numero_hospital": "ord_numero_hospital", "codigo_fuente": "ord_tipo_estudio"}, + resultados={ + "intencion": "orden.intencion", + "ord_fecha_solicitud": "orden.fecha_solicitud", + "ord_fecha_resultado": "orden.fecha_resultado", + "estatus": "orden.estatus", + "especialidad": "orden.especialidad", + "diagnostico": "orden.diagnostico", + }, + fuentes={"especialidad": "especialidad_fuente"}, + ) + + +def nota_medica( + staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False +) -> DeStaging: + textos = { + "motivo": lambda f: texto_limpio(f.nm_motivo_consulta), + "diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto), + } if con_textos else {} + return DeStaging( + staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha", + columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional) + derivadas={ + "cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos, + }, + resultados={ + "cie_codigo": "nota_medica.diagnostico", + "especialidad": "nota_medica.especialidad", + **({f: f"nota_medica.{f}" for f in textos}), + }, + fuentes={"especialidad": "especialidad_fuente"}, + ) diff --git a/webapi/orchestration/silver/persons.py b/webapi/orchestration/silver/persons.py new file mode 100644 index 0000000..613c760 --- /dev/null +++ b/webapi/orchestration/silver/persons.py @@ -0,0 +1,30 @@ +"""De una fila de pacientes de staging a `persona` (T-20c).""" + +from core.indicadores.comunes import PersonaBase + +from webapi.orchestration.silver.values import codigo, texto_limpio +from webapi.orchestration.tables import TablasKit + + +def a_persona(paciente, *, tablas: TablasKit, **propias) -> PersonaBase: + """La persona de una fila de pacientes; las columnas propias del proyecto salen de `tablas.persona_propias`.""" + return tablas.Persona( + pac_id=paciente.pac_id, + pac_id_hospital=paciente.pac_id_hospital, + fecha_nacimiento=paciente.pac_fecha_nacimiento, + **{**tablas.persona_propias(paciente), **propias}, + ) + + +def de_derechohabiente(paciente) -> dict: + """Lo que la persona de CaCu y CaMa agrega a las comunes: lo que el hospital sabe de la derechohabiente.""" + return { + "dependencia": texto_limpio(paciente.pac_dependencia), + "parentesco": texto_limpio(paciente.pac_parentesco), + "codigo_postal": texto_limpio(paciente.pac_codigo_postal), + } + + +def con_sexo(paciente) -> dict: + """Lo que la persona de TEA agrega: el sexo, como código.""" + return {"sexo": codigo(paciente.pac_sexo)} diff --git a/webapi/orchestration/silver/procedures.py b/webapi/orchestration/silver/procedures.py new file mode 100644 index 0000000..9946a2d --- /dev/null +++ b/webapi/orchestration/silver/procedures.py @@ -0,0 +1,257 @@ +"""De staging a `procedimiento` y `observacion` (F5, ADR-MD-007; staging directo, T-20c y ADR-MD-009). + +Cada proyecto declara en `/plata.py`, `DESDE_STAGING`, qué procedimientos salen de cada +fila de cada tabla de staging (`DeStaging`): su clase, su estudio, su fecha, su padre, sus columnas +y sus resultados, nombrando columnas de staging o **derivadas** (funciones de la fila: la +normalización). `plata_desde_staging` reparte cada fila en un procedimiento (el acto) y sus +observaciones (un valor por resultado del catálogo). La carga doble y su `Correspondencia` por +tabla por tipo se retiraron en T-20c2. + +Solo se calcula: lo escribe Persistance (`guardar_carga_en`), en una transacción. Las filas salen como diccionarios, con la +llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`, +`clase`) y la de su padre, porque los `procedimiento_id` solo los conoce la base. +""" + +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import NamedTuple + +from webapi.orchestration.reference.catalogs import Catalogo + +# A igual profundidad, el orden en que se escriben las clases (`en_orden_de_padres`). +ORDEN_DE_CLASES = ("orden", "encuentro", "toma", "reporte", "parte") +# Las columnas de `procedimiento` que puede llenar una correspondencia, además de pac_id y fecha. +COLUMNAS_DE_PROCEDIMIENTO = ("numero_hospital", "orden_numero", "codigo_fuente", "id_hospital") + +Llave = tuple[str, str, str, str] # (fuente_tabla, fuente_id, estudio_id, clase) + + +@dataclass(frozen=True) +class Padre: + """Cómo encuentra un procedimiento a su padre. + + Por la llave de otra fila de staging: `fuente_id` (y, si la trae, `fuente_tabla`) son + columnas de la fila; `tabla` es la tabla de staging del padre cuando la fila no la + trae. O por el número de orden del hospital (`por_numero_de_orden`): el padre es la + orden con ese `numero_hospital`. + """ + + estudio_id: str | None = None + clase: str | None = None + fuente_id: str | None = None + fuente_tabla: str | None = None + tabla: str | None = None + por_numero_de_orden: str | None = None + + +@dataclass(frozen=True) +class Hija: + """Un procedimiento que sale de la misma fila que otro y cuelga de él (el ADOS-2 de una evaluación). + + Solo se crea si alguna de las columnas `solo_si` de la fila trae valor. Su llave tiene la + misma fila de staging, con su propio estudio y clase. + """ + + estudio_id: str + clase: str + solo_si: tuple[str, ...] + fecha: str | None = None + resultados: Mapping[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class DeStaging: + """Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c). + + El contenido de la fila son sus columnas de staging más las `derivadas` (nombre -> función de + la fila). `paciente` es la columna con el `pac_id`; nula si el procedimiento lo toma de su padre + (un instrumento, un segmento). `columnas`: columna de `procedimiento` -> columna del contenido. + `estudio_id`, `estudio_de`, `fecha`, `padres`, `resultados`, `fuentes` e `hijas` nombran + columnas del contenido. + - `solo_si`: si da falso, la fila no produce este procedimiento (un reporte sin fecha todavía + no es un reporte); no es un descarte. + - `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en + `descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging. + + Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada. + Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17). + """ + + staging: type + llave: str + clase: str + estudio_id: str | None = None + estudio_de: str | None = None + fecha: str | None = None + padres: tuple[Padre, ...] = () + columnas: Mapping[str, str] = field(default_factory=dict) + resultados: Mapping[str, str] = field(default_factory=dict) + fuentes: Mapping[str, str] = field(default_factory=dict) + hijas: tuple[Hija, ...] = () + derivadas: Mapping[str, Callable] = field(default_factory=dict) + paciente: str | None = "pac_id" + solo_si: Callable | None = None + descartar: Callable | None = None + + +class LotePlata(NamedTuple): + """Lo que recibe `guardar_plata_en`: procedimientos en orden de clase, sus observaciones y los descartes.""" + + procedimientos: list[dict] + observaciones: list[dict] + descartes: dict[str, int] + + +def plata_desde_staging( + filas: Mapping[str, Iterable], + *, + correspondencias: Iterable[DeStaging], + catalogo: Catalogo, + codigos_hospital: Mapping[str, str], + pacientes: Iterable[int] = (), +) -> LotePlata: + """De las filas de staging (tabla -> filas) a procedimientos y observaciones. Pura (staging directo, T-20c). + + Cada `DeStaging` arma el contenido de cada fila de su tabla (columnas más derivadas) y lo + reparte en un procedimiento (y sus hijas) con sus observaciones. Cada procedimiento sale como + `{"llave": Llave, "padres": [Llave | ("orden", numero)], "pac_id", "fecha", ...}` y cada + observación como `{"procedimiento": Llave, "pac_id", "resultado_id", "valor_id", + "valor_numerico", "valor_fecha", "valor_texto", "valor_fuente"}`. Una fila cuyo estudio no se + encuentra en `codigos_hospital` no entra y se cuenta en `descartes`, como una fila a la + que `descartar` le da motivo se cuenta en `descartes` y no entra. `pacientes`: los `pac_id` + conocidos, para `descartar`. + """ + pacientes = set(pacientes) + tipos, vigentes = _tipos_y_vigentes(catalogo) + procedimientos, observaciones, descartes = [], [], {} + for c in correspondencias: + tabla = c.staging.__tablename__ + for fila in filas.get(tabla, ()): + fuente_id = getattr(fila, c.llave) + if c.descartar is not None and (motivo := c.descartar(fila, pacientes)) is not None: + descartes[motivo] = descartes.get(motivo, 0) + 1 + continue + if c.solo_si is not None and not c.solo_si(fila): + continue + contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}} + contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente) + contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()}) + _repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital, + tipos, vigentes, procedimientos, observaciones, descartes) + return LotePlata(en_orden_de_padres(procedimientos), observaciones, descartes) + + +class CicloDePadres(ValueError): + """Un procedimiento del lote que es, por sus padres, ancestro de sí mismo.""" + + +def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]: + """Los procedimientos en el orden en que se escriben: cada uno después de sus padres del mismo lote (T-22h). + + `guardar_plata_en` resuelve el padre con lo que ya escribió, así que un padre del lote va antes que + sus hijos aunque su clase vaya después (la orden de una biopsia cuelga de su toma). A igual + profundidad, por `ORDEN_DE_CLASES` y, dentro de la clase, como llegaron. Un padre fuera del lote (ya + escrito, o la orden del hospital por su número) no cuenta. Un ciclo de padres falla con `CicloDePadres`. + """ + por_llave = {p["llave"]: p for p in procedimientos} + profundidad: dict = {} + + def de(llave, camino=()): + if llave in profundidad: + return profundidad[llave] + if llave in camino: + raise CicloDePadres(f"Ciclo de padres en el lote: {' -> '.join(map(str, (*camino, llave)))}.") + padres = [padre for padre in por_llave[llave]["padres"] if padre in por_llave] + profundidad[llave] = 1 + max((de(padre, (*camino, llave)) for padre in padres), default=-1) + return profundidad[llave] + + return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3]))) + + +def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]: + tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados} + vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"} + return tipos, vigentes + + +def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, columnas: tuple[str, ...], + codigos_hospital: Mapping[str, str], tipos: dict, vigentes: set, + procedimientos: list, observaciones: list, descartes: dict) -> None: + """Un procedimiento (y sus hijas) con sus observaciones, desde el contenido de una fila: el motor común.""" + estudio_id = c.estudio_id or codigos_hospital.get(contenido.get(c.estudio_de)) + if estudio_id is None: + motivo = f"{nombre}: {c.estudio_de} fuera de catálogo" + descartes[motivo] = descartes.get(motivo, 0) + 1 + return + llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase) + procedimientos.append({ + "llave": llave, + "padres": [p for p in (_parent(padre, contenido) for padre in c.padres) if p is not None], + "pac_id": contenido.get("pac_id"), + "fecha": contenido.get(c.fecha) if c.fecha else None, + # Sin columna de fecha (instrumentos, segmentos), la fecha es la del padre; con ella, puede quedar nula. + "fecha_del_padre": c.fecha is None, + **{columna: contenido.get(columna) for columna in columnas}, + }) + observaciones += _observaciones(llave, contenido, c.resultados, c.fuentes, tipos, vigentes) + for hija in c.hijas: + if all(contenido.get(columna) is None for columna in hija.solo_si): + continue + llave_hija = (fuente_tabla, str(fuente_id), hija.estudio_id, hija.clase) + procedimientos.append({ + "llave": llave_hija, "padres": [llave], "pac_id": contenido.get("pac_id"), + "fecha": contenido.get(hija.fecha) if hija.fecha else None, "fecha_del_padre": hija.fecha is None, + }) + observaciones += _observaciones(llave_hija, contenido, hija.resultados, c.fuentes, tipos, vigentes) + + +def valor_de_observacion(valor, fuente, *, tipo_valor: str, en_catalogo: Callable[[str], bool]) -> dict: + """El valor en su columna según `tipo_valor` (ADR-MD-007). Un valor nulo da la observación con valor nulo.""" + fila = {"valor_id": None, "valor_numerico": None, "valor_fecha": None, "valor_texto": None, "valor_fuente": None} + if tipo_valor == "codigo": + texto = None if valor is None else str(valor) + fila["valor_id"] = texto if texto is not None and en_catalogo(texto) else None + fila["valor_fuente"] = None if fuente is None else str(fuente) + elif tipo_valor in ("booleano", "numero"): + fila["valor_numerico"] = None if valor is None else float(valor) + elif tipo_valor == "fecha": + fila["valor_fecha"] = valor + else: # texto, externo + fila["valor_texto"] = None if valor is None else str(valor) + return fila + + +def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str], fuentes: Mapping[str, str], + tipos: dict, vigentes: set) -> list[dict]: + filas = [] + for columna, plantilla in resultados.items(): + resultado_id = plantilla.format(estudio=llave[2]) + filas.append({ + "procedimiento": llave, + "pac_id": contenido.get("pac_id"), + "resultado_id": resultado_id, + **valor_de_observacion( + contenido.get(columna), _fuente(contenido, columna, fuentes), + tipo_valor=tipos[resultado_id], en_catalogo=lambda v, r=resultado_id: (r, v) in vigentes, + ), + }) + return filas + + +def _fuente(contenido: dict, columna: str, fuentes: Mapping[str, str]): + """El valor tal como llegó: el de su columna fuente, o el mismo valor si esa columna viene vacía.""" + fuente = contenido.get(fuentes.get(columna, columna)) + return contenido.get(columna) if fuente is None else fuente + + +def _parent(padre: Padre, contenido: dict): + if padre.por_numero_de_orden: + numero = contenido.get(padre.por_numero_de_orden) + return None if numero is None else ("orden", numero) + fuente_id = contenido.get(padre.fuente_id) + if fuente_id is None: + return None + tabla = contenido.get(padre.fuente_tabla) if padre.fuente_tabla else padre.tabla + if tabla is None: + return None + return (tabla, str(fuente_id), padre.estudio_id, padre.clase) diff --git a/webapi/orchestration/silver/quality.py b/webapi/orchestration/silver/quality.py new file mode 100644 index 0000000..249f8fe --- /dev/null +++ b/webapi/orchestration/silver/quality.py @@ -0,0 +1,43 @@ +"""Calidad de la plata de dos tablas: lo que está mal en `procedimiento` y `observacion`, contado. + +Cuatro conteos, una consulta cada uno (ADR-MD-007): + + reporte_sin_padre un reporte o una parte sin procedimiento padre + fuera_de_catalogo una observación codificada cuyo valor no está en `cat_valor` (llegó texto, no código) + de_otro_estudio una observación de un resultado de otro estudio que el de su procedimiento + (salvo los `orden.*` de una orden, cuyo estudio es el pedido) + nulas una observación sin ningún valor + +Solo lee y solo cuenta. Qué hacer con los conteos (avisar) lo decide la arista +`verificar_plata` de webapi.orchestration. +""" + +from sqlalchemy import and_, func, not_, select +from sqlmodel import Session + +from webapi.orchestration.tables import TablasKit + +CONTEOS = ("reporte_sin_padre", "fuera_de_catalogo", "de_otro_estudio", "nulas") +VALORES = ("valor_id", "valor_numerico", "valor_fecha", "valor_texto", "valor_fuente") + + +def verificar_plata(sesion: Session, *, tablas: TablasKit) -> dict[str, int]: + """Los cuatro conteos de `CONTEOS` sobre el estado actual de las dos tablas.""" + p, o, r = tablas.Procedimiento, tablas.Observacion, tablas.CatResultado + observaciones_con_resultado = select(func.count()).select_from(o).join(r, r.resultado_id == o.resultado_id) + consultas = { + "reporte_sin_padre": select(func.count()).select_from(p).where( + p.clase.in_(("reporte", "parte")), p.padre_id.is_(None) + ), + "fuera_de_catalogo": observaciones_con_resultado.where( + r.tipo_valor == "codigo", o.valor_id.is_(None), o.valor_fuente.is_not(None) + ), + "de_otro_estudio": observaciones_con_resultado.join(p, p.procedimiento_id == o.procedimiento_id).where( + r.estudio_id != p.estudio_id, + not_(and_(r.estudio_id == "orden", p.clase == "orden")), + ), + "nulas": select(func.count()).select_from(o).where( + *(getattr(o, columna).is_(None) for columna in VALORES) + ), + } + return {nombre: sesion.execute(consulta).scalar_one() for nombre, consulta in consultas.items()} diff --git a/webapi/orchestration/silver/values.py b/webapi/orchestration/silver/values.py new file mode 100644 index 0000000..4292b54 --- /dev/null +++ b/webapi/orchestration/silver/values.py @@ -0,0 +1,44 @@ +"""Las normalizaciones de un valor de staging que usan las columnas derivadas de `DESDE_STAGING` (T-20c). + +Una sola definición por regla (T-20c3; antes repartidas en `cdm/` y en la normalización de cada proyecto, +retirados en T-20c2). +""" + +from collections.abc import Collection, Mapping + +INTENCION = "order" # FHIR `ServiceRequest.intent` de una orden; sus valores están sin definir + + +def texto_limpio(valor) -> str | None: + """Un texto de staging sin espacios alrededor; nulo si viene vacío. No lo normaliza más (I-K61).""" + if valor is None: + return None + return str(valor).strip() or None + + +def codigo(texto: str | None) -> str | None: + """Un código como lo compara ulises: sin espacios al borde y en mayúsculas; vacío es nulo.""" + if texto is None: + return None + return texto.strip().upper() or None + + +def cie(texto: str | None) -> str | None: + """Un código CIE-10 para compararlo: sin espacios, sin punto y en mayúsculas (C53.9 -> C539); vacío es nulo.""" + if texto is None: + return None + return texto.strip().upper().replace(".", "").replace(" ", "") or None + + +def codigo_de_especialidad(texto, alias: Mapping[str, str], codigos: Collection[str]) -> str | None: + """La especialidad en el código de Core: el propio código o su alias, sin distinguir mayúsculas. + + Nulo si no viene o no se reconoce: quien la use la cuenta como sin dato. + """ + limpio = texto_limpio(texto) + if limpio is None: + return None + en_mayusculas = limpio.upper() + if en_mayusculas in codigos: + return en_mayusculas + return alias.get(en_mayusculas) diff --git a/webapi/orchestration/silver/views.py b/webapi/orchestration/silver/views.py new file mode 100644 index 0000000..36f81be --- /dev/null +++ b/webapi/orchestration/silver/views.py @@ -0,0 +1,72 @@ +"""La vista `v_persona`, la única que queda en la base de un proyecto (F6, ADR-MD-009). + +Es un `select` de SQLAlchemy; `CreateView` y `DropView`, de aquí, la escriben para +el motor (T-2 de v0.5.0). La crea la arista `vistas`, no la migración (B21). Aquí +solo se arma la DDL; no se ejecuta. + +Antes eran las de `sqlalchemy-utils`, pero importar ese paquete registra para toda +sesión de SQLAlchemy un `after_flush` (`sqlalchemy_utils.aggregates`) que recorre +todos los objetos de la sesión en cada flush. La carga a plata hace un flush por +procedimiento nuevo, así que la carga crecía con el cuadrado de los pacientes +(TEA, 1000 pacientes: 25 s con él, 9 s sin él). + +Las vistas por tipo (`v__actual`, las de rol y las de cada proyecto) +se borraron con sus tablas en las migraciones de F6. +""" + +from sqlalchemy import Select, column, select, table +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.schema import DDLElement +from sqlalchemy.sql.expression import Executable + +from core.indicadores.comunes import PersonaBase + + +def ddl_de_vistas(persona: type = PersonaBase) -> list[Executable]: + """La DDL que crea o reemplaza `v_persona`, con las columnas de la persona del proyecto. No la ejecuta. + + La ejecuta Persistance (`VistasRepository.construir`) o, en una base de + prueba, `pruebas.construir_vistas`. + """ + # `persona` no tiene versiones: su vista es la tabla, para que un + # indicador lea solo vistas (B18, I-K23). + return reemplazar_vista("v_persona", select(*_columnas("persona", persona))) + + +def _columnas(nombre: str, modelo: type) -> list: + """Las columnas de `modelo`, leídas de la tabla o vista `nombre`.""" + return list(table(nombre, *(column(campo) for campo in modelo.model_fields)).c) + + +class CreateView(DDLElement): + """`CREATE VIEW nombre AS `, con los valores escritos en la consulta.""" + + def __init__(self, nombre: str, consulta: Select) -> None: + self.nombre, self.consulta = nombre, consulta + + +class DropView(DDLElement): + """`DROP VIEW IF EXISTS nombre`, sin CASCADE: SQLite no lo acepta (I-K100).""" + + def __init__(self, nombre: str) -> None: + self.nombre = nombre + + +@compiles(CreateView) +def _crear(elemento: CreateView, compilador, **_) -> str: + nombre = compilador.dialect.identifier_preparer.quote(elemento.nombre) + return f"CREATE VIEW {nombre} AS {compilador.sql_compiler.process(elemento.consulta, literal_binds=True)}" + + +@compiles(DropView) +def _borrar(elemento: DropView, compilador, **_) -> str: + return f"DROP VIEW IF EXISTS {compilador.dialect.identifier_preparer.quote(elemento.nombre)}" + + +def borrar_vista(nombre: str) -> DropView: + return DropView(nombre) + + +def reemplazar_vista(nombre: str, consulta: Select) -> list[Executable]: + """La DDL que crea la vista `nombre` con esa consulta; si ya existe, la reemplaza.""" + return [borrar_vista(nombre), CreateView(nombre, consulta)] diff --git a/webapi/orchestration/tables/__init__.py b/webapi/orchestration/tables/__init__.py new file mode 100644 index 0000000..fd15b32 --- /dev/null +++ b/webapi/orchestration/tables/__init__.py @@ -0,0 +1,87 @@ +"""Las tablas de un proyecto, juntas, para pasarlas al código común. + +El código común (carga, registro, cálculo, contratos) no importa clases +de tabla: recibe las del proyecto en un `TablasKit`. Así cada proyecto +puede tener sus propias clases, aunque las columnas sean las mismas, y +CaCu y CaMa corren en el mismo proceso sin un "proyecto activo". + +Cada proyecto declara la suya en `/tablas.py` como `TABLAS`. +""" + +from collections.abc import Callable +from dataclasses import dataclass +from importlib import import_module + +from sqlmodel import SQLModel + +PROJECTS = ("cacu", "cama") + + +@dataclass(frozen=True) +class TablasKit: + """Las tablas de un proyecto: el registro, el oro y la plata genérica (una sola plata, ADR-MD-009).""" + + Persona: type[SQLModel] + PeriodoObservacion: type[SQLModel] + Carga: type[SQLModel] + DefParametro: type[SQLModel] + DimPeriodo: type[SQLModel] + DimFecha: type[SQLModel] + DimGrupoEdad: type[SQLModel] + MeasureReport: type[SQLModel] + # Los catálogos de la plata (F1): estudio -> resultado -> valor, de `core/catalogos/.toml`. + CatEstudio: type[SQLModel] + CatResultado: type[SQLModel] + CatValor: type[SQLModel] + # La plata de dos tablas (F5, ADR-MD-007). + Procedimiento: type[SQLModel] + Observacion: type[SQLModel] + # El oro por unidad y su catálogo (§6f, MD-19): opcionales para que un registro de prueba no los necesite. + CatMeasure: type[SQLModel] | None = None + CatMeasureResultado: type[SQLModel] | None = None + CatMeasureValor: type[SQLModel] | None = None + CatMeasureGrupo: type[SQLModel] | None = None + CatEstrato: type[SQLModel] | None = None + CatEstratoValor: type[SQLModel] | None = None + CatMeasureEstrato: type[SQLModel] | None = None + MeasureReportUnidad: type[SQLModel] | None = None + MeasureReportUnidadEstrato: type[SQLModel] | None = None + # De una fila de `paciente` de staging, las columnas que este proyecto agrega a su `persona`. + persona_propias: Callable[[object], dict] = lambda paciente: {} + + def comunes(self) -> list[type[SQLModel]]: + return [ + self.Persona, + self.PeriodoObservacion, + self.Carga, + self.DefParametro, + self.DimPeriodo, + self.DimFecha, + self.DimGrupoEdad, + self.MeasureReport, + self.CatEstudio, + self.CatResultado, + self.CatValor, + self.Procedimiento, + self.Observacion, + ] + + def publicacion(self) -> list[type[SQLModel]]: + """Las tablas de §6f (MD-19) que el proyecto declara, en orden de llaves foráneas.""" + return [m for m in (self.CatMeasure, self.CatMeasureResultado, self.CatMeasureValor, self.CatMeasureGrupo, self.CatEstrato, self.CatEstratoValor, self.CatMeasureEstrato, self.MeasureReportUnidad, self.MeasureReportUnidadEstrato) if m is not None] + + def catalogo_de_publicacion(self) -> list[type[SQLModel]]: + """Las siete tablas `cat_*` de §6f, padres antes que hijos (lo que sincroniza la arista `definiciones`).""" + return [m for m in (self.CatEstrato, self.CatEstratoValor, self.CatMeasure, self.CatMeasureResultado, + self.CatMeasureValor, self.CatMeasureGrupo, self.CatMeasureEstrato) if m is not None] + + def todas(self) -> list[type[SQLModel]]: + """Todo lo que la base del proyecto lleva del kit (sin staging ni cohortes).""" + return [*self.comunes(), *self.publicacion()] + + +def tablas_de(proyecto: str) -> TablasKit: + """El `TablasKit` del proyecto, de `/tablas.py`.""" + if proyecto not in PROJECTS: + raise KeyError(f"Proyecto desconocido: {proyecto!r}.") + return import_module(f"webapi.orchestration.tables.{proyecto}").TABLAS diff --git a/webapi/orchestration/tables/cacu.py b/webapi/orchestration/tables/cacu.py new file mode 100644 index 0000000..8b9801a --- /dev/null +++ b/webapi/orchestration/tables/cacu.py @@ -0,0 +1,77 @@ +"""Las tablas de CaCu: viven en `Core`, en el registro del dominio (ADR-004). + +`TABLAS` es lo que el código común recibe para trabajar con este proyecto. +""" + +from core.cacu.indicadores.models import ( + CatMeasure, + CatMeasureResultado, + CatMeasureValor, + CatMeasureGrupo, + CatEstrato, + CatEstratoValor, + CatMeasureEstrato, + MeasureReportUnidad, + MeasureReportUnidadEstrato, + CatEstudio, + CatResultado, + CatValor, + Observacion, + Procedimiento, + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, + Carga, + DefParametro, + DimFecha, + DimGrupoEdad, + DimPeriodo, + MeasureReport, + PeriodoObservacion, + Persona, +) + +from webapi.orchestration.silver.persons import de_derechohabiente +from core.indicadores.cohortes import TablasCohorte +from webapi.orchestration.tables import TablasKit + +__all__ = ["TABLAS", "COHORTES"] + +TABLAS = TablasKit( + Persona=Persona, + PeriodoObservacion=PeriodoObservacion, + Carga=Carga, + DefParametro=DefParametro, + DimPeriodo=DimPeriodo, + DimFecha=DimFecha, + DimGrupoEdad=DimGrupoEdad, + MeasureReport=MeasureReport, + CatEstudio=CatEstudio, + CatResultado=CatResultado, + CatValor=CatValor, + Procedimiento=Procedimiento, + Observacion=Observacion, + CatMeasure=CatMeasure, + CatMeasureResultado=CatMeasureResultado, + CatMeasureValor=CatMeasureValor, + CatMeasureGrupo=CatMeasureGrupo, + CatEstrato=CatEstrato, + CatEstratoValor=CatEstratoValor, + CatMeasureEstrato=CatMeasureEstrato, + MeasureReportUnidad=MeasureReportUnidad, + MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, + persona_propias=de_derechohabiente, +) + +# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003). +COHORTES = TablasCohorte( + CohorteArmado=CohorteArmado, + CohorteMiembro=CohorteMiembro, + CohorteExclusion=CohorteExclusion, + CohorteVariable=CohorteVariable, + EvaluacionRiesgoLote=EvaluacionRiesgoLote, + EvaluacionRiesgo=EvaluacionRiesgo, +) diff --git a/webapi/orchestration/tables/cama.py b/webapi/orchestration/tables/cama.py new file mode 100644 index 0000000..c1a7b5f --- /dev/null +++ b/webapi/orchestration/tables/cama.py @@ -0,0 +1,77 @@ +"""Las tablas de CaMa: viven en `Core`, en el registro del dominio (ADR-004). + +`TABLAS` es lo que el código común recibe para trabajar con este proyecto. +""" + +from core.cama.indicadores.models import ( + CatMeasure, + CatMeasureResultado, + CatMeasureValor, + CatMeasureGrupo, + CatEstrato, + CatEstratoValor, + CatMeasureEstrato, + MeasureReportUnidad, + MeasureReportUnidadEstrato, + CatEstudio, + CatResultado, + CatValor, + Observacion, + Procedimiento, + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, + Carga, + DefParametro, + DimFecha, + DimGrupoEdad, + DimPeriodo, + MeasureReport, + PeriodoObservacion, + Persona, +) + +from webapi.orchestration.silver.persons import de_derechohabiente +from core.indicadores.cohortes import TablasCohorte +from webapi.orchestration.tables import TablasKit + +__all__ = ["TABLAS", "COHORTES"] + +TABLAS = TablasKit( + Persona=Persona, + PeriodoObservacion=PeriodoObservacion, + Carga=Carga, + DefParametro=DefParametro, + DimPeriodo=DimPeriodo, + DimFecha=DimFecha, + DimGrupoEdad=DimGrupoEdad, + MeasureReport=MeasureReport, + CatEstudio=CatEstudio, + CatResultado=CatResultado, + CatValor=CatValor, + Procedimiento=Procedimiento, + Observacion=Observacion, + CatMeasure=CatMeasure, + CatMeasureResultado=CatMeasureResultado, + CatMeasureValor=CatMeasureValor, + CatMeasureGrupo=CatMeasureGrupo, + CatEstrato=CatEstrato, + CatEstratoValor=CatEstratoValor, + CatMeasureEstrato=CatMeasureEstrato, + MeasureReportUnidad=MeasureReportUnidad, + MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, + persona_propias=de_derechohabiente, +) + +# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003; MD-12). +COHORTES = TablasCohorte( + CohorteArmado=CohorteArmado, + CohorteMiembro=CohorteMiembro, + CohorteExclusion=CohorteExclusion, + CohorteVariable=CohorteVariable, + EvaluacionRiesgoLote=EvaluacionRiesgoLote, + EvaluacionRiesgo=EvaluacionRiesgo, +) -- 2.53.0 From 205bc214fa4f04850483ec7e083482fa5a9fcb91 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 17:28:24 -0600 Subject: [PATCH 11/24] Every stratum value an answer writes is in the stratum-value catalog --- tests/test_metrics_on_request.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/test_metrics_on_request.py b/tests/test_metrics_on_request.py index ee03ccc..2b7ba59 100644 --- a/tests/test_metrics_on_request.py +++ b/tests/test_metrics_on_request.py @@ -158,6 +158,19 @@ def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7 assert without(composition_cells(result), STATUS) == expected["published"], period_id +def test_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7): + """Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't + enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the + stratum values the catalog lacks.""" + for d in (eu13, eu7): + ask(base, d, "2025-S1") + with base.motor.connect() as connection: + written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar() + broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all() + assert written > 0 + assert broken == [] + + def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7): """Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing.""" -- 2.53.0 From e224b8b2aa4165820cf8697372da8c3b7a99e458 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 12 Nov 2026 15:21:25 -0600 Subject: [PATCH 12/24] TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary --- pyproject.toml | 1 + tests/conftest.py | 2 +- tests/staging/tea.py | 139 +++++++ tests/test_fhir_measures.py | 60 +++ tests/test_fhir_tea.py | 223 +++++++++++ tests/test_imports_endpoints.py | 26 +- tests/test_imports_pdf_endpoints.py | 8 +- tests/test_new_sources.py | 95 ++--- tests/test_orquestacion_ciclo.py | 2 +- tests/test_orquestacion_oro.py | 7 +- tests/test_orquestacion_pasos.py | 2 +- tests/test_orquestacion_plata.py | 1 + tests/test_orquestacion_regla_repositorios.py | 2 +- tests/test_schemas.py | 19 +- tests/test_schemas_registry.py | 23 +- tests/test_source_ids.py | 28 +- tests/test_tea_measures.py | 245 ++++++++++++ uv.lock | 28 +- webapi/__init__.py | 10 +- webapi/compositions.py | 4 + webapi/durations.py | 12 +- webapi/fhir/__init__.py | 360 ++++++++++++++++++ webapi/fhir/common.py | 93 +++++ webapi/fhir/measures.py | 194 ++++++++++ webapi/fhir/tea.py | 352 +++++++++++++++++ webapi/fhir/tea_eeg.toml | 53 +++ webapi/fhir/terminology.py | 74 ++++ webapi/imports/connectors/edf.py | 55 +-- webapi/imports/schemas/coercion.py | 10 +- webapi/imports/schemas/registry.py | 100 ++--- webapi/imports/schemas/tea/ados2.py | 55 +++ .../tea/antecedentes_maternos_gestacion.py | 55 --- webapi/imports/schemas/tea/eeg.py | 26 ++ webapi/imports/schemas/tea/eeg_estudio.py | 69 ---- webapi/imports/schemas/tea/eeg_metrica.py | 16 + .../schemas/tea/eeg_metrica_electrodo.py | 12 + webapi/imports/schemas/tea/eeg_segmento.py | 21 - .../schemas/tea/evaluacion_neuropediatrica.py | 27 ++ .../schemas/tea/evaluacion_psicologica.py | 86 ----- .../schemas/tea/instrumento_aplicado.py | 13 - webapi/imports/schemas/tea/mchat.py | 13 + webapi/imports/schemas/tea/nota_medica.py | 46 --- webapi/imports/schemas/tea/ordenes_estudio.py | 26 +- webapi/imports/schemas/tea/pacientes.py | 18 +- webapi/imports/schemas/tea/parto_neonatal.py | 50 --- .../tea/potenciales_evocados_auditivos.py | 26 -- webapi/metrics.py | 199 +++++++++- webapi/orchestration/__main__.py | 2 +- .../orchestration/reference/parametros.toml | 151 +------- webapi/orchestration/semantic_layer.py | 14 +- webapi/orchestration/silver/procedures.py | 43 ++- webapi/orchestration/silver/tea.py | 120 ++++++ webapi/orchestration/tables/__init__.py | 2 +- webapi/orchestration/tables/tea.py | 75 ++++ webapi/recomputation.py | 2 +- 55 files changed, 2607 insertions(+), 788 deletions(-) create mode 100644 tests/staging/tea.py create mode 100644 tests/test_fhir_measures.py create mode 100644 tests/test_fhir_tea.py create mode 100644 tests/test_tea_measures.py create mode 100644 webapi/fhir/__init__.py create mode 100644 webapi/fhir/common.py create mode 100644 webapi/fhir/measures.py create mode 100644 webapi/fhir/tea.py create mode 100644 webapi/fhir/tea_eeg.toml create mode 100644 webapi/fhir/terminology.py create mode 100644 webapi/imports/schemas/tea/ados2.py delete mode 100644 webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py create mode 100644 webapi/imports/schemas/tea/eeg.py delete mode 100644 webapi/imports/schemas/tea/eeg_estudio.py create mode 100644 webapi/imports/schemas/tea/eeg_metrica.py create mode 100644 webapi/imports/schemas/tea/eeg_metrica_electrodo.py delete mode 100644 webapi/imports/schemas/tea/eeg_segmento.py create mode 100644 webapi/imports/schemas/tea/evaluacion_neuropediatrica.py delete mode 100644 webapi/imports/schemas/tea/evaluacion_psicologica.py delete mode 100644 webapi/imports/schemas/tea/instrumento_aplicado.py create mode 100644 webapi/imports/schemas/tea/mchat.py delete mode 100644 webapi/imports/schemas/tea/nota_medica.py delete mode 100644 webapi/imports/schemas/tea/parto_neonatal.py delete mode 100644 webapi/imports/schemas/tea/potenciales_evocados_auditivos.py create mode 100644 webapi/orchestration/silver/tea.py create mode 100644 webapi/orchestration/tables/tea.py diff --git a/pyproject.toml b/pyproject.toml index b501ebf..208f351 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,7 @@ packages = ["webapi"] [dependency-groups] dev = [ + "fhir-resources>=8", "pytest>=8.0.0", "reportlab>=4.0", ] diff --git a/tests/conftest.py b/tests/conftest.py index aeb86b2..304fb19 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -71,7 +71,7 @@ def base_de(proyecto: str, carpeta, datos=None) -> Base: return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor) -@pytest.fixture(params=["cacu", "cama"]) +@pytest.fixture(params=["cacu", "cama", "tea"]) def proyecto(request): return request.param diff --git a/tests/staging/tea.py b/tests/staging/tea.py new file mode 100644 index 0000000..8bb82ce --- /dev/null +++ b/tests/staging/tea.py @@ -0,0 +1,139 @@ +"""TEA's synthetic staging, written by hand. Never real data. + +Seven children screened in 2025, each one exercising a rule of the screening's chain (M-CHAT, psychology note +with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first M-CHAT, in completed months: + +- 1, H-T01, 19 months (16 to 23): the whole chain. M-CHAT 10 Jan, ADOS-2 5 Feb, F84.0 note 12 Mar, a bad EEG + 2 Apr, a good EEG 20 May with a slow posterior rhythm, then a second good EEG 1 Sep that changes nothing. Leaves + after May. Its EEG has an order. +- 2, H-T02, 26 months (24 to 29): M-CHAT 20 Jan, ADOS-2 1 Mar, a note with F84 without subcode 10 Apr (not a + confirmation), no EEG: stays at neuropediatrics. +- 3, H-T03, 35 months (30 to 36): M-CHAT 14 Feb (a second one 10 Jun doesn't count), ADOS-2 28 Feb, nothing else: + stays at psychology. +- 4, H-T04, 39 months: out of the cohort, never counted. +- 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in + order, so it stays at M-CHAT. +- 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG + step is dated by the note, so it reaches EEG on 2 Jun and leaves after June. +- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else. + +Every EEG's quality criteria are written as its analysis would; a bad EEG has one criterion out of its threshold. + +Test support: writes in the session it's given, never in the domain's database. +""" + +from datetime import date + +from core.tea.models import ( + Ados2, + Eeg, + EegMetrica, + EegMetricaElectrodo, + EvaluacionNeuropediatrica, + Mchat, + OrdenesEstudio, + Pacientes, +) +from sqlmodel import Session + +# (pac_id, pac_id_hospital, birth date) +PACIENTES = ( + (1, "H-T01", date(2023, 6, 1)), + (2, "H-T02", date(2022, 11, 15)), + (3, "H-T03", date(2022, 3, 1)), + (4, "H-T04", date(2021, 12, 1)), + (5, "H-T05", date(2023, 9, 1)), + (6, "H-T06", date(2023, 1, 10)), + (7, "H-T07", None), +) + +# (pac_id, date, score) +MCHATS = ( + (1, date(2025, 1, 10), 12), + (2, date(2025, 1, 20), 9), + (3, date(2025, 2, 14), 15), + (3, date(2025, 6, 10), 4), + (4, date(2025, 3, 3), 11), + (5, date(2025, 6, 15), 8), + (6, date(2025, 4, 5), 14), + (7, date(2025, 5, 1), 7), +) + +# (pac_id, date, module, CSS, classification) +ADOS2 = ( + (1, date(2025, 2, 5), "MODULO_1", 7, "AUTISMO"), + (2, date(2025, 3, 1), "Toddler", 4, "espectro autista"), + (3, date(2025, 2, 28), "MODULO_2", 2, "NO_TEA"), + (6, date(2025, 4, 20), "MODULO_1", 8, "AUTISMO"), +) + +# (pac_id, date, ICD-10 as the hospital writes it) +NOTAS = ( + (1, date(2025, 3, 12), "F84.0"), + (2, date(2025, 4, 10), "F84"), + (5, date(2025, 7, 1), "f84.0"), + (6, date(2025, 6, 2), "F84.0"), +) + +GOOD = {"amplitud": 0, "alta_frecuencia": 1, "correlacion": 0, "sin_senal": 0, "linea": 3.5} +BAD = {**GOOD, "sin_senal": 5} + +# (eeg id, pac_id, date, laboratory id, criteria, with sleep) +EEGS = ( + ("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0), + ("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1), + ("eeg-1c", 1, date(2025, 9, 1), "LAB-1C", GOOD, 1), + ("eeg-5", 5, date(2025, 7, 20), "LAB-5", GOOD, 0), + ("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1), +) + +# (metric id, eeg id, code, value): a null value can't be evaluated. +METRICAS = ( + ("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2), + ("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0), + ("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4), + ("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0), + ("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5), + ("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None), + ("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6), +) + +# (electrode value id, metric id, electrode, z-score) +ELECTRODOS = ( + ("mel-1", "met-1b-rp", "O1", -2.8), + ("mel-2", "met-1b-rp", "O2", -2.4), + ("mel-3", "met-1b-rp", "Pz", -1.1), +) + +# The EEG of child 1 that completes the chain hangs from an order. +ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),) +ORDEN_DE = {"eeg-1b": "ord-1b"} + +# What the load gives (`test_orquestacion_plata`). +PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS) + + +def insertar(sesion: Session) -> None: + """Writes the children, their orders and their studies.""" + sesion.add_all(Pacientes(pac_id=p, pac_id_hospital=h, pac_fecha_nacimiento=n) for p, h, n in PACIENTES) + sesion.add_all(OrdenesEstudio(ord_id=i, ord_pac_id=p, ord_id_hospital=h, ord_tipo_estudio=t, ord_fecha=f) + for i, p, h, t, f in ORDENES) + sesion.add_all(Mchat(mch_id=f"mch-{k}", mch_pac_id=p, mch_fecha=f, mch_puntaje=s) + for k, (p, f, s) in enumerate(MCHATS, 1)) + for k, (p, f, modulo, css, clasificacion) in enumerate(ADOS2, 1): + items = {f"ado_sa_b{n}": n % 3 for n in range(1, 6)} | {"ado_rrb_d1": 2, "ado_rrb_d2": 1} + sesion.add(Ados2(ado_id=f"ado-{k}", ado_pac_id=p, ado_fecha=f, ado_modulo=modulo, ado_css=css, + ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items)) + sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c) + for k, (p, f, c) in enumerate(NOTAS, 1)) + for i, p, f, lab, criterios, sueno in EEGS: + sesion.add(Eeg( + eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i), + eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0, + eeg_canales_amplitud=criterios["amplitud"], eeg_canales_alta_frecuencia=criterios["alta_frecuencia"], + eeg_canales_correlacion=criterios["correlacion"], eeg_canales_sin_senal=criterios["sin_senal"], + eeg_ruido_linea_db=criterios["linea"], + )) + sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v) for i, e, c, v in METRICAS) + sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v) + for i, m, e, v in ELECTRODOS) diff --git a/tests/test_fhir_measures.py b/tests/test_fhir_measures.py new file mode 100644 index 0000000..f842703 --- /dev/null +++ b/tests/test_fhir_measures.py @@ -0,0 +1,60 @@ +"""What this module covers: the FHIR R4 measure routes of `webapi.fhir` for CaCu and CaMa: every `Measure` of the +domain and one `MeasureReport` of each, checked against FHIR's models (`fhir.resources`, R4B), and the patient routes +absent outside TEA. + +Fixtures: `domain_client`, a Flask app with only the domain's FHIR blueprint over its fixture database loaded through +the cycle up to `event_models` (`conftest.base_de`); needs `DBT_MANIFEST`. +""" + +import os +from pathlib import Path + +import pytest +from fhir.resources.R4B import get_fhir_model_class +from flask import Flask + +from conftest import base_de +from webapi.fhir import fhir_blueprint + +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@pytest.fixture(scope="module", params=["cacu", "cama"]) +def domain_client(request, tmp_path_factory): + manifest = os.environ.get("DBT_MANIFEST") + if not manifest: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + base = base_de(request.param, tmp_path_factory.mktemp(request.param)) + base.run(*UNTIL_MODELS, allow_undecided=True) + app = Flask(__name__) + app.register_blueprint(fhir_blueprint(request.param, base.dominio, Path(manifest), with_patients=True), + url_prefix=f"/{request.param}/fhir") + yield request.param, app.test_client() + base.motor.dispose() + + +def valid(resource: dict) -> dict: + get_fhir_model_class(resource["resourceType"]).model_validate(resource) + for item in resource.get("entry", ()): + get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"]) + return resource + + +def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client): + """Pins down: each Measure of the domain, and its report for 2025-S1, validate as FHIR R4 resources, compositions + with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape.""" + domain, client = domain_client + measures = valid(client.get(f"/{domain}/fhir/Measure").get_json()) + assert measures["total"] == 7 + for item in measures["entry"]: + response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1") + assert response.status_code in (200, 409), response.get_json() + valid(response.get_json()) + + +def test_the_patient_routes_are_tea_s_only(domain_client): + """Pins down: `EpisodeOfCare` exists only on TEA's endpoint; elsewhere it's an OperationOutcome 404. Fails if + the patient routes register for another domain.""" + domain, client = domain_client + response = client.get(f"/{domain}/fhir/EpisodeOfCare") + assert response.status_code == 404 and valid(response.get_json())["resourceType"] == "OperationOutcome" diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py new file mode 100644 index 0000000..03b8789 --- /dev/null +++ b/tests/test_fhir_tea.py @@ -0,0 +1,223 @@ +"""What this module covers: TEA's FHIR R4 endpoint (`/tea/fhir/`): the capability statement, the measures as +`Measure` and their answers as `MeasureReport` (one period and several), the follow-up list as `EpisodeOfCare` with +its filters, paging and includes, the EEG summary and the patient summary; and that the alterations stay hidden until +validated. Every resource is checked against FHIR's models (`fhir.resources`, R4B, which keeps R4's shape for these +resources). + +Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes exist) over TEA's fixture database +(`staging.tea`) loaded through the cycle up to `event_models`; needs `DBT_MANIFEST`. `validated`, the switch that +shows the alterations (`TEA_ALTERACIONES_VALIDADAS`). +""" + +import os + +import pytest +from fhir.resources.R4B import get_fhir_model_class + +from conftest import base_de + +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@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") + mp = pytest.MonkeyPatch() + mp.setenv("DEV_REVISION", "pruebas") + mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) + base = base_de("tea", tmp_path_factory.mktemp("tea_fhir")) + base.run(*UNTIL_MODELS, allow_undecided=True) + from webapi import create_app + + app = create_app() + app.config.update(TESTING=True) + with app.test_client() as test_client: + yield test_client + base.motor.dispose() + mp.undo() + + +@pytest.fixture +def validated(monkeypatch): + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + + +def valid(resource: dict) -> dict: + """The resource, after checking it and every resource in it against FHIR's model of its type.""" + get_fhir_model_class(resource["resourceType"]).model_validate(resource) + for item in resource.get("entry", ()): + get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"]) + return resource + + +def get(client, url: str, status: int = 200) -> dict: + response = client.get(url) + assert response.status_code == status, response.get_json() + assert response.mimetype == "application/fhir+json" + return valid(response.get_json()) + + +def resources(bundle: dict, kind: str | None = None, mode: str | None = None) -> list[dict]: + return [e["resource"] for e in bundle["entry"] if (kind is None or e["resource"]["resourceType"] == kind) + and (mode is None or e.get("search", {}).get("mode") == mode)] + + +def test_the_capability_statement_lists_the_measures_and_the_patient_routes(client): + """Pins down: `metadata` is a valid CapabilityStatement naming Measure with `evaluate-measure` and, in DEV, + EpisodeOfCare with its search parameters. Fails if a route drops out of it.""" + body = get(client, "/tea/fhir/metadata") + kinds = {r["type"]: r for r in body["rest"][0]["resource"]} + assert {"Measure", "MeasureReport", "EpisodeOfCare", "Patient"} <= set(kinds) + assert {p["name"] for p in kinds["EpisodeOfCare"]["searchParam"]} >= {"date", "etapa", "fecha-etapa", "alteracion"} + + +def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monkeypatch): + """Pins down: the Measure list has the nine measures without alterations; M30 shows only with the switch on. + Fails if M30 leaks before the domain expert validates the references, or the switch stops showing it.""" + ids = {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} + assert len(ids) == 9 and "M30-resultado-eeg" not in ids + assert get(client, "/tea/fhir/Measure/M30_resultado_eeg", 404)["resourceType"] == "OperationOutcome" + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} + + +def test_a_measure_carries_what_the_page_needs(client): + """Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category + labels. Fails if the page's catalog fields stop reaching the Measure.""" + m28 = get(client, "/tea/fhir/Measure/M28_casos_por_estado") + assert m28["url"] == "https://isssteleon.org/fhir/Measure/M28-casos-por-estado" + assert m28["title"] == "Casos por estatus" and m28["scoring"]["coding"][0]["code"] == "cohort" + assert {e["extension"][0]["valueCode"] for e in m28["extension"] if e["url"].endswith("/categoria")} == { + "SOLO_MCHAT", "PSICOLOGIA", "NEUROPEDIATRIA", "EEG"} + m24 = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico") + assert m24["group"][0]["stratifier"][0]["code"]["coding"][0]["code"] == "grupo_edad" + assert "denominator-exclusion" in {p["code"]["coding"][0]["code"] for p in m24["group"][0]["population"]} + + +def test_evaluate_measure_answers_one_period_as_a_measure_report(client): + """Pins down: `$evaluate-measure` with periodStart and periodEnd answers that period of `dim_periodo`: M28's first + semester of 2025 counts six children by stage, as a cohort whose stages are a stratifier. Fails if the period + lookup, the canonical or the C2 shape changes.""" + report = get(client, "/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure" + "?periodStart=2025-01-01&periodEnd=2025-06-30") + assert report["measure"].startswith("https://isssteleon.org/fhir/Measure/M28-casos-por-estado|") + (group,) = report["group"] + assert group["population"][0]["count"] == 6 + stages = {s["value"]["coding"][0]["code"]: s["population"][0]["count"] for s in group["stratifier"][0]["stratum"]} + assert stages == {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2} + + +def test_a_proportion_reports_its_exclusion_and_its_strata_with_codings(client): + """Pins down: M24's report has the exclusion count (child 2's note without F84.0) and each age group as a coded + stratum. Fails if `denominator-exclusion` or the stratum codings drop out.""" + report = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico/$evaluate-measure?periodo=2025-04") + counts = {p["code"]["coding"][0]["code"]: p["count"] for p in report["group"][0]["population"]} + assert counts == {"denominator": 3, "numerator": 1, "denominator-exclusion": 1} + values = {s["value"]["coding"][0]["code"] for s in report["group"][0]["stratifier"][0]["stratum"]} + assert {"16_23", "30_36"} <= values + + +def test_the_measure_report_search_answers_several_periods_with_paging(client): + """Pins down: `MeasureReport?measure=…&tipo-periodo=mes&period=ge…&period=le…` gives one report per month, and + `_count` pages them with a `next` link. Fails if the search stops selecting `dim_periodo` by type and dates.""" + url = ("/tea/fhir/MeasureReport?measure=https://isssteleon.org/fhir/Measure/M26-dias-mchat-ados2" + "&tipo-periodo=mes&period=ge2025-01-01&period=le2025-03-31") + body = get(client, url) + assert body["total"] == 3 and [r["period"]["start"] for r in resources(body)] == [ + "2025-01-01", "2025-02-01", "2025-03-01"] + paged = get(client, url + "&_count=2") + assert len(paged["entry"]) == 2 and any(link["relation"] == "next" for link in paged["link"]) + + +def test_the_follow_up_list_is_each_child_s_episode_at_the_cut_off(client): + """Pins down: `EpisodeOfCare?date=le…` gives each child who entered by the cut-off, at its stage then: at 31 May, + children 1, 2, 3, 6 and 7 (child 5 enters in June), child 1 finished on its good EEG. A window from 1 June leaves + child 1 out. Fails if the episode's status, stage or window drift from the measures' rules.""" + may = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-05-31")) + assert len(may) == 5 + assert sorted(e["status"] for e in may) == ["active"] * 4 + ["finished"] + assert all(e["meta"]["tag"][0]["code"] == "simulado" for e in may) + june = resources(get(client, "/tea/fhir/EpisodeOfCare?date=ge2025-06-01&date=le2025-06-30")) + assert len(june) == 5 and "finished" in {e["status"] for e in june} + + +@pytest.mark.parametrize(("query", "n"), [ + ("etapa=PSICOLOGIA", 1), ("grupo-edad=24_29", 2), ("mchat=ge12", 3), ("css=ge4", 3), + ("fecha-etapa=ge2025-06-01&fecha-etapa=le2025-06-30", 2), ("status=finished", 2), ("resultado-eeg=sin-eeg-valido", 3), +]) +def test_the_follow_up_filters(client, query, n): + """Pins down each search parameter at the year's end, over the six children who entered by then: child 3 at + psychology; children 2 and 6 in 24 to 29 months (finished episodes still list); M-CHAT of 12 or more for children + 1, 3 and 6; CSS of 4 or more for 1, 2 and 6; a stage dated in June for child 5 (its M-CHAT; its EEG doesn't count) + and child 6 (EEG on 2 June); children 1 and 6 finished; children 2, 3 and 7 without a valid EEG. Fails if a filter + stops reading its column.""" + assert get(client, f"/tea/fhir/EpisodeOfCare?date=le2025-12-31&{query}")["total"] == n + + +def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client): + """Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT, + confirmed diagnosis and study EEG as a DiagnosticReport with its quality observations; no metric observation while + the alterations are hidden. Fails if an included resource drops out or the alterations leak.""" + body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*") + included = resources(body, mode="include") + kinds = {r["resourceType"] for r in included} + assert {"Patient", "CarePlan", "Observation", "Condition", "DiagnosticReport", "Procedure"} <= kinds + assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient") + reports = [r for r in included if r["resourceType"] == "DiagnosticReport"] + assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"} + assert all(len(r["result"]) == 5 for r in reports) + + +def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch): + """Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's + slow posterior rhythm). Fails if the filter leaks alterations before validation.""" + assert get(client, "/tea/fhir/EpisodeOfCare?alteracion=ritmo_posterior", 403)["resourceType"] == "OperationOutcome" + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&alteracion=ritmo_posterior")["total"] == 1 + + +def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(client, monkeypatch): + """Pins down `$resumen-eeg`: children 1, 5 and 6 with a valid EEG, 2, 3 and 7 without; with the alterations + validated, child 1 abnormal (posterior rhythm), 5 and 6 normal. Fails if the summary counts bad EEGs as valid or + shows the split before validation.""" + def counts(body): + return {p["name"]: p.get("valueInteger") for p in body["parameter"] if "valueInteger" in p} + + hidden = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31") + assert counts(hidden) == {"con_eeg_valido": 3, "sin_eeg_valido": 3} + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + shown = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31") + assert counts(shown) == {"con_eeg_valido": 3, "sin_eeg_valido": 3, "normales": 2, "anormales": 1} + + +def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch): + """Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first + good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated, + the metrics against their reference and the electrode values. Fails if the summary takes another EEG or shows the + alterations before validation.""" + episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished")) + (child_1,) = episodes + path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea" + bundle = get(client, path) + assert bundle["type"] == "collection" + (report,) = resources(bundle, "DiagnosticReport") + assert report["effectiveDateTime"] == "2025-05-20" and report["conclusionCode"][0]["coding"][0]["code"] == "BUENO" + ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-")) + codes = {c["code"]["coding"][0]["code"] for c in ados2["component"]} + assert {"ados2.modulo", "ados2.css", "SA", "RRB", "ados2.sa_b1"} <= codes + assert not any("tea-eeg-metrica" in o["code"]["coding"][0]["system"] for o in resources(bundle, "Observation")) + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + shown = get(client, path) + metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")] + rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-")) + assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5 + electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-")) + assert [c["code"]["coding"][0]["code"] for c in electrodes["component"]] == ["O1", "O2", "Pz"] + + +def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client): + """Pins down: errors are OperationOutcomes with the HTTP status: an unknown pseudonym (404), an unknown search + parameter (400). Fails if an error goes back to `{"error": …}`.""" + assert get(client, "/tea/fhir/Patient/P-NADIE/$resumen-tea", 404)["issue"][0]["code"] == "not-found" + assert get(client, "/tea/fhir/EpisodeOfCare?color=azul", 400)["issue"][0]["code"] == "invalid" diff --git a/tests/test_imports_endpoints.py b/tests/test_imports_endpoints.py index 1ab9b57..b98b148 100644 --- a/tests/test_imports_endpoints.py +++ b/tests/test_imports_endpoints.py @@ -124,7 +124,8 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, def test_commit_rejects_a_batch_mixing_domains(client): cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente") - tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes") + tea_source = _json_source([{"pac_id_hospital": "T-MIX-1"}], target="tea.Pacientes", + column_mapping={"pac_id_hospital": "pac_id_hospital"}) response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"}) assert response.status_code == 400 @@ -159,20 +160,21 @@ def test_commit_on_conflict_reject_then_upsert(client): def test_commit_upsert_rejected_for_target_without_natural_key(client): source = _json_source( - [{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"} + [{"pac_id_hospital": "H-NO-KEY"}], target="cacu.BiometriaHematica", + column_mapping={"pac_id_hospital": "pac_id_hospital"}, ) response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}) assert response.status_code == 400 def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client): - mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"} - first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}], + mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento"} + first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-05-01"}], target="tea.Pacientes", column_mapping=mapping) body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json() assert body["results"][0]["created"] == 1 - again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}], + again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-06-01"}], target="tea.Pacientes", column_mapping=mapping) body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json() assert body["results"][0]["created"] == 0 @@ -180,20 +182,22 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client): [paciente] = client.get("/data/tea.Pacientes").get_json()["rows"] assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1" - assert paciente["pac_sexo"] == "M" + assert paciente["pac_fecha_nacimiento"] == "2023-06-01" -def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client): - """The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation. +def test_an_import_into_tea_queues_its_recomputation(client): + """Pins down: TEA's measures come from the cycle like CaCu's and CaMa's, so a TEA import saves its rows and + asks for a recomputation of TEA. - Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500. + Fails if TEA leaves the queue's domains (`DOMAINS` in `webapi.recomputation`). """ - source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes") + source = _json_source([{"pac_id_hospital": "T-RECALC"}], target="tea.Pacientes", + column_mapping={"pac_id_hospital": "pac_id_hospital"}) response = client.post("/imports/commit", json={"sources": [source]}) assert response.status_code == 200 body = response.get_json() assert body["results"][0]["created"] == 1 - assert body["indicadores_en_recalculo"] is False + assert body["indicadores_en_recalculo"] is True @pytest.fixture diff --git a/tests/test_imports_pdf_endpoints.py b/tests/test_imports_pdf_endpoints.py index 2df8d7a..8cb8072 100644 --- a/tests/test_imports_pdf_endpoints.py +++ b/tests/test_imports_pdf_endpoints.py @@ -2,7 +2,7 @@ - detect -> table/preview -> validate -> commit, for the ruled-table path, writing into `cacu.Paciente`. - detect -> page-image -> regions/extract -> validate -> commit, for the - OCR/region path, writing into `tea.Pacientes`. + OCR/region path, writing into `cacu.Paciente` as well. """ import base64 @@ -201,7 +201,7 @@ def test_pdf_page_image_missing_file_returns_400(client): # --------------------------------------------------------------------- # OCR/region path: detect -> page-image -> regions/extract -> validate -> -# commit (tea.Pacientes) +# commit (cacu.Paciente) # --------------------------------------------------------------------- @@ -241,7 +241,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): source = { "source_type": "pdf", - "target": "tea.Pacientes", + "target": "cacu.Paciente", "column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}, "payload": { "file_base64": base64.b64encode(pdf_bytes).decode(), @@ -261,7 +261,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): commit_body = commit_response.get_json() assert commit_body["ok"] is True result = commit_body["results"][0] - assert result["target"] == "tea.Pacientes" + assert result["target"] == "cacu.Paciente" assert result["created"] == 1 diff --git a/tests/test_new_sources.py b/tests/test_new_sources.py index 3fd3d62..f647c74 100644 --- a/tests/test_new_sources.py +++ b/tests/test_new_sources.py @@ -78,31 +78,35 @@ def test_unknown_engine_and_missing_host_are_rejected(client): # -- EEG ----------------------------------------------------------------------------- -def test_edf_preview_maps_onto_eeg_estudio(client): - data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"} +def test_edf_preview_maps_onto_eeg(client): + """Pins down: an EDF previews as one row with the study id, patient, date, channels and duration read from the + file, and its columns suggest the `eeg` fields. Fails if the connector stops reading the header or the column + matcher stops pairing them.""" + data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.Eeg"} body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json() [row] = body["sample_rows"] assert row["id_registro_laboratorio"] == "LAB-778" assert row["paciente"] == "EXP-0042" assert row["fecha_estudio"] == "2024-01-15" - assert row["edad_meses"] == 56.0 - assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3) - assert "3 canales a 128 Hz" in row["descripcion_senal"] + assert row["canales"] == 3 + assert row["duracion_min"] == pytest.approx(8 / 60, abs=0.05) suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]} assert suggested["estudio"] == "eeg_estudio" assert suggested["fecha_estudio"] == "eeg_fecha_estudio" - assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia" + assert suggested["canales"] == "eeg_canales" -def test_several_edf_files_load_into_eeg_estudio_with_the_file(client): +def test_several_edf_files_load_into_eeg_with_the_file(client): + """Pins down: several EDF files commit as one `eeg` row each, keyed by the lab's study id (or the file name), + with the file stored. Fails if the commit drops the file or the key.""" source = { "source_type": "edf", - "target": "tea.EegEstudio", + "target": "tea.Eeg", "column_mapping": { "id_registro_laboratorio": "eeg_id_registro_laboratorio", "fecha_estudio": "eeg_fecha_estudio", "duracion_min": "eeg_duracion_min", - "ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia", + "canales": "eeg_canales", "estudio": "eeg_estudio", }, "payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]}, @@ -110,19 +114,21 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client): result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0] assert result["created"] == 2, result - from persistance.tea import eeg_estudio_repository + from persistance.tea import eeg_repository - stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()} + stored = {row.eeg_id_registro_laboratorio: row for row in eeg_repository.list()} assert set(stored) == {"LAB-778", "b"} + assert stored["LAB-778"].eeg_canales == 3 assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0" assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15) -def test_eeg_estudio_rejects_a_file_mne_cannot_read(): +def test_eeg_rejects_a_file_mne_cannot_read(): + """Pins down: `eeg_estudio` only takes a file MNE can open. Fails if the schema stops validating the EDF.""" from webapi.imports.schemas.service import validate_rows - from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema + from webapi.imports.schemas.tea.eeg import EegImportSchema - result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}]) + result = validate_rows(EegImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}]) [row] = result.rejected assert row.errors[0].field == "eeg_estudio" @@ -228,73 +234,48 @@ def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client): EEG_REPORT = text_pdf( - [ - ["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024", - "Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"], - ["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."], - ], - image_on_page=2, + [["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024"]], ) # A second study id, distinct from LAB-778 (already used by an earlier test # against this module-scoped client/database), for the merge test below. EEG_REPORT_2 = text_pdf( - [ - ["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024", - "Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"], - ["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."], - ], + [["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024"]], ) -def test_eeg_report_scattered_across_pages_merges_into_one_record(client): - """The report's demographics are on page 1, its conclusion on page 2 — - non-contiguous fields the same way a multi-file upload would be, just - without the file boundary. Proves the extractor merges by the lab's own - study id, not by page adjacency.""" +def test_an_eeg_report_gives_its_study_id_and_date(client): + """Pins down: a report read with NLP lands on `eeg` by the lab's own study id, with the study date. Fails if + the extractor stops keying EEG records by `eeg_id_registro_laboratorio` or stops reading the date.""" body = client.post( "/imports/sources/document/extract", - json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"}, + json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.Eeg"}, ).get_json() assert body["key_field"] == "eeg_id_registro_laboratorio" [record] = body["records"] assert record["key"] == "LAB-778" - assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}] - assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO" assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15" - assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"] - assert [image["page_number"] for image in record["images"]] == [2] -def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client): - """The EDF connector computes signal fields from the file itself; the - report PDF (read with NLP, across two pages) carries the clinician's - interpretation. Different sources, same study — `eeg_id_registro_ - laboratorio` (the lab's own code, read from the EDF header by one side - and from the report text by the other) is what lets them land on one - `eeg_estudio` row instead of two half-populated ones.""" +def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_row(client): + """Pins down: the EDF and its report, two sources of the same study, land on one `eeg` row through the lab's + study id (read from the EDF header by one and from the report text by the other). Fails if + `merge_duplicates` stops matching them on `eeg_id_registro_laboratorio`.""" edf_source = { "source_type": "edf", - "target": "tea.EegEstudio", + "target": "tea.Eeg", "label": "estudio.edf", "column_mapping": { "id_registro_laboratorio": "eeg_id_registro_laboratorio", - "fecha_estudio": "eeg_fecha_estudio", "duracion_min": "eeg_duracion_min", - "ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia", "estudio": "eeg_estudio", }, "payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]}, } document_source = _document_source( [("reporte.pdf", EEG_REPORT_2)], - "tea.EegEstudio", - { - "eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", - "eeg_simetria": "eeg_simetria", - "eeg_conclusion_texto": "eeg_conclusion_texto", - "eeg_medico_interpreta": "eeg_medico_interpreta", - }, + "tea.Eeg", + {"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", "eeg_fecha_estudio": "eeg_fecha_estudio"}, ) body = client.post( "/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True} @@ -303,16 +284,14 @@ def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client): assert edf_result["created"] == 1, body assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again - from persistance.tea import eeg_estudio_repository + from persistance.tea import eeg_repository - [row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900") + [row] = eeg_repository.list(eeg_id_registro_laboratorio="LAB-900") # From the EDF file itself: assert row.eeg_duracion_min is not None assert row.eeg_estudio[:8].strip() == b"0" - # From the scanned report, on the very same row: - assert row.eeg_simetria == "SIMETRICO" - assert "sin eventos epileptiformes" in row.eeg_conclusion_texto - assert row.eeg_medico_interpreta == "Dra. Ruiz" + # From the report, on the very same row: + assert row.eeg_fecha_estudio == date(2024, 2, 20) def test_citologia_table_and_scanned_report_merge_on_the_order_number(client): diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 63cde16..480e5cc 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -27,7 +27,7 @@ CONSULTA = text(""" -@pytest.fixture(scope="module", params=["cacu", "cama"]) +@pytest.fixture(scope="module", params=["cacu", "cama", "tea"]) def bases(request, tmp_path_factory): proyecto = request.param carpeta = tmp_path_factory.mktemp(proyecto) diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 9da68bd..dee138d 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -84,10 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.run("definitions")["definitions"] - # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata. - assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto] + # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata; TEA: the age group and its + # ten measures. + assert resumen["definitions"] == {"cacu": 10, "cama": 7, "tea": 11}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain + assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 7, "tea": 10}[base.proyecto] assert base.run("definitions")["definitions"]["borradas"] == 0 diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index e8ded34..df737f4 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -23,7 +23,7 @@ def antes(deps: dict[str, set[str]], paso: str) -> set[str]: return previos -@pytest.mark.parametrize("proyecto", ["cacu", "cama"]) +@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto): deps = dependencias(proyecto) assert deps["migrate"] == set() diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index 57d5940..ae67df9 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -26,6 +26,7 @@ from sqlmodel import select CAMBIO = { "cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"), "cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"), + "tea": ("mchat", "mch_puntaje", 19), } CORTE = date(2025, 12, 31) diff --git a/tests/test_orquestacion_regla_repositorios.py b/tests/test_orquestacion_regla_repositorios.py index 048a27d..0c82bb5 100644 --- a/tests/test_orquestacion_regla_repositorios.py +++ b/tests/test_orquestacion_regla_repositorios.py @@ -23,7 +23,7 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo): assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos" -@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)]) +@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)]) def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes): repos = repositories_of(proyecto) assert (repos.gold.cohorts is not None) == con_cohortes diff --git a/tests/test_schemas.py b/tests/test_schemas.py index d02f5fb..1881fe9 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -48,14 +48,15 @@ def test_tea_pacientes_schema_is_fully_optional(): assert schema.pac_id_hospital is None -def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict(): - schema = PacientesImportSchema(pac_sexo="f") - assert schema.pac_sexo == "F" +def test_tea_neuropediatrics_note_takes_icd10_with_or_without_the_dot(): + """Pins down: the note's ICD-10 is upper-cased and accepted with or without its dot; anything else is + rejected. Fails if the pattern of `neu_cie_codigo` changes.""" + from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema as Nota - -def test_tea_pacientes_schema_coerces_parentesco(): - schema = PacientesImportSchema(pac_parentesco="hijo") - assert schema.pac_parentesco == "HIJO" + assert Nota(neu_cie_codigo=" f84.0 ").neu_cie_codigo == "F84.0" + assert Nota(neu_cie_codigo="F840").neu_cie_codigo == "F840" + with pytest.raises(ValidationError): + Nota(neu_cie_codigo="autismo") def test_classify_error_missing(): @@ -243,5 +244,5 @@ def test_catalog_aliases_for_values_the_indicator_kit_uses(): cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO") assert cito.cit_celulas_escamosas == "NORMAL" assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA" - assert TeaOrdenes(ord_tipo_estudio="POTENCIALES_EVOCADOS").ord_tipo_estudio == "POTENCIALES_EVOCADOS_AUDITIVOS" - assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "EVALUACION_PSICOLOGICA_TEA" + assert TeaOrdenes(ord_tipo_estudio="electroencefalograma").ord_tipo_estudio == "EEG" + assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "ADOS2" diff --git a/tests/test_schemas_registry.py b/tests/test_schemas_registry.py index bdef2e5..fdccba4 100644 --- a/tests/test_schemas_registry.py +++ b/tests/test_schemas_registry.py @@ -5,7 +5,8 @@ from pydantic import ValidationError from webapi.imports.schemas.registry import ENTITY_REGISTRY from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema -from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema +from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema +from webapi.imports.schemas.tea.mchat import MchatImportSchema from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema @@ -48,11 +49,21 @@ def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio( assert schema.ord_tipo_estudio == "BIOPSIA_CHICA" -# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds -# a Catalog from the Enum alone, as in tea/pacientes.py. -def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict(): - schema = EegEstudioImportSchema(eeg_simetria="simetrico") - assert schema.eeg_simetria == "SIMETRICO" +def test_tea_ados2_coerces_module_and_classification_aliases(): + """Pins down: the ADOS-2's module comes from the bare enum and its classification takes the old spelling + `NO_TEA`. Fails if either catalog stops normalizing case or aliases.""" + schema = Ados2ImportSchema(ado_modulo="modulo_1", ado_clasificacion="no_tea") + assert (schema.ado_modulo, schema.ado_clasificacion) == ("MODULO_1", "NO_ESPECTRO") + + +@pytest.mark.parametrize(("schema", "field", "value"), [ + (MchatImportSchema, "mch_puntaje", 21), (Ados2ImportSchema, "ado_css", 0), (Ados2ImportSchema, "ado_sa_b1", 4), +]) +def test_tea_scores_out_of_their_range_are_rejected(schema, field, value): + """Pins down: an M-CHAT score above 20, a CSS below 1 and an ADOS-2 item above 3 are validation errors. Fails if + a bound of `Bounded` is dropped from the schemas.""" + with pytest.raises(ValidationError): + schema(**{field: value}) # CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS). diff --git a/tests/test_source_ids.py b/tests/test_source_ids.py index e8f2f2e..98c1556 100644 --- a/tests/test_source_ids.py +++ b/tests/test_source_ids.py @@ -76,31 +76,31 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client): sources = [ _json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"), _json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"), - _json([{"psi_id": "psi-1", "psi_ord_id": "ord-1", "psi_pac_id": 1}], "tea.EvaluacionPsicologica"), - _json([{"ins_psi_id": "psi-1", "ins_instrumento": "ADOS-2"}], "tea.InstrumentoAplicado"), - _json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.EegEstudio"), - _json([{"seg_eeg_id": "eeg-1", "seg_duracion_s": 30}], "tea.EegSegmento"), + _json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"), + _json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"), + _json([{"met_id": "met-1", "met_eeg_id": "eeg-1", "met_codigo": "RITMO_POSTERIOR", "met_valor": 5.5}], "tea.EegMetrica"), + _json([{"mel_met_id": "met-1", "mel_electrodo": "O1", "mel_valor": -1.2}], "tea.EegMetricaElectrodo"), ] body = tea_client.post("/imports/commit", json={"sources": sources}).get_json() assert all(r["rejected"] == 0 for r in body["results"]), body from persistance.tea import ( - eeg_estudio_repository, - eeg_segmento_repository, - evaluacion_psicologica_repository, - instrumento_aplicado_repository, + ados2_repository, + eeg_metrica_electrodo_repository, + eeg_metrica_repository, + eeg_repository, ) - assert eeg_estudio_repository.get(eeg_segmento_repository.list()[0].seg_eeg_id).eeg_id_registro_laboratorio == "L-1" - evaluacion = evaluacion_psicologica_repository.get(instrumento_aplicado_repository.list()[0].ins_psi_id) - assert evaluacion.psi_ord_id == "ord-1" + metrica = eeg_metrica_repository.get(eeg_metrica_electrodo_repository.list()[0].mel_met_id) + assert eeg_repository.get(metrica.met_eeg_id).eeg_id_registro_laboratorio == "L-1" + assert ados2_repository.get("ado-1").ado_ord_id == "ord-1" def test_tea_rows_without_a_source_id_get_one(tea_client): - eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio") + eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.Eeg") assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1 - from persistance.tea import eeg_estudio_repository + from persistance.tea import eeg_repository - [fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"] + [fila] = [e for e in eeg_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"] assert len(fila.eeg_id) == 36 diff --git a/tests/test_tea_measures.py b/tests/test_tea_measures.py new file mode 100644 index 0000000..6139462 --- /dev/null +++ b/tests/test_tea_measures.py @@ -0,0 +1,245 @@ +"""What this module covers: TEA's ten measures answered on request from dbt's semantic layer, on hand-written +expectations for the synthetic children of `staging.tea`, period by period: who each period counts (the children in +the screening during it, at their stage at its end, leaving after the period of their good EEG), the day counts, the +EEGs by quality and the alterations of each child's first good EEG. + +Fixtures: `base`, TEA's fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's +`manifest.json` (`DBT_MANIFEST`; skipped without it). The expectations are worked out by hand from the children's +dates in `staging/tea.py`; each test says which child makes each number. +""" + +import os +from dataclasses import replace +from datetime import date, datetime, timezone +from pathlib import Path + +import pytest +from sqlalchemy import text +from sqlmodel import select + +import staging.tea as fixture +from conftest import base_de +from core.tea.models import Eeg, EegMetrica +from webapi.compositions import answer_composition, composition_definitions +from webapi.durations import answer_duration, duration_definitions +from webapi.metrics import Question, answer, measure_definitions + +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@pytest.fixture(scope="module") +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture(scope="module") +def base(tmp_path_factory, manifest): + """The seven children of `staging.tea`, loaded once, with dbt's TEA views created.""" + base = base_de("tea", tmp_path_factory.mktemp("tea")) + base.run(*UNTIL_MODELS, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, allow_undecided=True)) + base.motor.dispose() + + +def repositories(base) -> dict: + d = base.dominio + return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, + "history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True} + + +def composition(base, manifest, measure_id, period, **question): + url = f"tea/{measure_id}" + result = answer_composition("tea", composition_definitions(manifest)[url], Question(url, period, **question), + **repositories(base)) + return {k: v for k, v in result.categories.items() if v} + + +def proportion(base, manifest, measure_id, period, **question): + url = f"tea/{measure_id}" + return answer("tea", measure_definitions(manifest)[url], Question(url, period, **question), **repositories(base)) + + +def duration(base, manifest, measure_id, period): + url = f"tea/{measure_id}" + return answer_duration("tea", duration_definitions(manifest)[url], Question(url, period), **repositories(base)) + + +STAGES = { + "2025-01": {"SOLO_MCHAT": 2}, + "2025-02": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2}, + "2025-03": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 1}, + "2025-04": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}, + "2025-05": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 1, "EEG": 1}, + "2025-06": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 1}, + "2025-07": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1}, + "2025-12": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1}, + "2025-S1": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2}, + "2025-S2": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1}, +} + + +@pytest.mark.parametrize("period", sorted(STAGES)) +def test_m28_counts_every_child_in_the_screening_at_its_stage_at_the_period_s_end(base, manifest, period): + """Pins down M28: a period counts every cohort child who entered by its end and hadn't finished before its start, + at the furthest step reached by its end, whether or not anything of theirs happened in it. Child 1 is at + psychology in February and March's stage moves with its note; it reaches EEG in May and is gone from June. Child 2 + stays at neuropediatrics all year; child 5 stays at M-CHAT (no ADOS-2); child 6 reaches EEG on its note's day, + 2 June; child 4 (39 months) never counts; child 7 (no birth date) counts from May. + + Fails if the population goes back to the children with a fact in the period, if a child stops leaving after the + period of its good EEG, or if a step stops needing the previous one.""" + assert composition(base, manifest, "M28_casos_por_estado", period) == STAGES[period] + + +def test_m28_an_event_cut_off_leaves_out_what_came_after_it(base, manifest): + """Pins down: facts dated after the event cut-off don't count. With a cut-off of 10 May, child 1's good EEG of + 20 May isn't there, so May counts it at neuropediatrics. Fails if the status rows stop applying the cut-off.""" + assert composition(base, manifest, "M28_casos_por_estado", "2025-05", event_cutoff=date(2025, 5, 10)) == { + "SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2} + + +RESULTS = { + "2025-01": {"EN_PROCESO": 2}, + "2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3}, + "2025-07": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3}, + "2025-S2": {"CONFIRMADO": 1, "EN_PROCESO": 2}, +} + + +@pytest.mark.parametrize("period", sorted(RESULTS)) +def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period): + """Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's + note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note + confirms it in July even without the ADOS-2. Fails if F84 counts as a confirmation or a note without F84.0 counts + as in process.""" + assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period] + + +@pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [ + ("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 1, 3, 1), ("2025-S1", 2, 5, 1), +]) +def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator, + excluded): + """Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion + from April. Fails if the denominator takes the children without TEA or the exclusion stops being counted.""" + result = proportion(base, manifest, "M24_confirmacion_diagnostico", period) + assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded) + + +def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest): + """Pins down: the age group is the child's at its first M-CHAT, one per child, the page's windows. In March, child + 1 (19 months) is confirmed, child 2 (26) and child 3 (35) are in process. Fails if the stratum goes back to the age + at the period's start or loses a window.""" + result = proportion(base, manifest, "M24_confirmacion_diagnostico", "2025-03") + strata = {v: (c.numerator, c.denominator) for v, c in result.strata["grupo_edad"].items()} + assert strata == {"16_23": (1, 1), "24_29": (0, 1), "30_36": (0, 1)} + + +@pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [ + ("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 1, 1), + ("2025-S1", 2, 0, 2), ("2025-S2", 0, 1, 1), +]) +def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg, + without_eeg, confirmed): + """Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG + by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5, confirmed in July, + has a good EEG but no ADOS-2, so its chain never reaches it. Fails if the EEG is read beyond the period's end or + outside the chain.""" + m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period) + m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period) + assert (m21.numerator, m21.denominator) == (with_eeg, confirmed) + assert (m22.numerator, m22.denominator) == (without_eeg, confirmed) + + +@pytest.mark.parametrize(("measure_id", "period", "initial", "n", "median"), [ + ("M26_dias_mchat_ados2", "2025-01", 2, 0, None), + ("M26_dias_mchat_ados2", "2025-02", 3, 2, 20.0), + ("M26_dias_mchat_ados2", "2025-03", 3, 3, 26.0), + ("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5), + ("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0), + ("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5), + ("M25_dias_mchat_diagnostico", "2025-S2", 4, 1, 16.0), +]) +def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period, + initial, n, median): + """Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval + ended by the period's end have days (repeated in each period that counts them), the rest count as without event. + In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of + 1 July gives 16 days in the second semester only. Fails if the value is read beyond the period's end or the + population goes back to the facts in the period.""" + result = duration(base, manifest, measure_id, period) + assert (result.initial, result.n, result.median) == (initial, n, median) + + +@pytest.mark.parametrize(("period", "expected"), [ + ("2025-04", {"MALO": 1}), ("2025-05", {"BUENO": 1}), ("2025-09", {"BUENO": 1}), + ("2025-S1", {"BUENO": 2, "MALO": 1}), ("2025-S2", {"BUENO": 2}), +]) +def test_m29_counts_the_period_s_eegs_good_or_bad(base, manifest, period, expected): + """Pins down M29: the EEGs of the cohort's children dated in the period, by exam, good or bad. Child 1's bad EEG of + April and its second good one of September count; so does child 5's, though its chain never reaches it. Fails if + M29 stops counting exams, or a bad EEG stops showing.""" + assert composition(base, manifest, "M29_calidad_eeg", period) == expected + + +@pytest.mark.parametrize(("period", "total", "ritmo_posterior"), [ + ("2025-05", (1, 1), (1, 1)), ("2025-06", (0, 1), (0, 1)), ("2025-S1", (1, 2), (1, 2)), ("2025-S2", (0, 1), (0, 1)), +]) +def test_m30_reads_the_alterations_of_each_child_s_first_good_eeg(base, manifest, period, total, ritmo_posterior): + """Pins down M30: of the children whose first good EEG falls in the period, those with an alteration in it, in + total and in one group per alteration. Child 1's EEG of 20 May has a slow posterior rhythm (3.2 Hz at 23 months, + against 4.5 to 7.0); its second good EEG of September doesn't count. Fails if a later EEG counts, or the groups + stop being answered one by one.""" + result = proportion(base, manifest, "M30_resultado_eeg", period) + assert (result.numerator, result.denominator) == total + assert (result.groups["ritmo_posterior"].numerator, result.groups["ritmo_posterior"].denominator) == ritmo_posterior + assert result.groups["husos_sueno_n2"].numerator == 0 + + +def test_m30_read_back_from_the_history_keeps_its_groups(base, manifest): + """Pins down: asking again reads the stored answer, groups included. Fails if a stored answer loses its groups or + counts every group's units in the total.""" + first = proportion(base, manifest, "M30_resultado_eeg", "2025-S1") + again = proportion(base, manifest, "M30_resultado_eeg", "2025-S1") + assert again.stored_before and (again.numerator, again.denominator) == (first.numerator, first.denominator) + assert again.groups == first.groups + + +def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest): + """Pins down: a step known after the knowledge cut-off doesn't move the child. Child 1's good EEG and its metrics + arrive in a second load; asked as of the first load, May still counts child 1 at neuropediatrics and it hasn't + left in June. Fails if the status rows stop applying the knowledge cut-off to the steps or to the exit.""" + def without_the_good_eeg(session): + fixture.insertar(session) + session.flush() + for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")): + for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")): + session.delete(row) + + base = base_de("tea", tmp_path, without_the_good_eeg) + try: + base.run(*UNTIL_MODELS, allow_undecided=True) + with base.motor.begin() as connection: + (first_load,) = connection.execute(text("select max(fin) from carga")).one() + known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc) + with base.staging() as session: + session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1, + eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0, + eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0, + eeg_ruido_linea_db=3.5)) + session.commit() + base.run("load", allow_undecided=True) + later = replace(base, ctx=replace(base.ctx, allow_undecided=True)) + assert composition(later, manifest, "M28_casos_por_estado", "2025-05", knowledge_cutoff=known) == { + "SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2} + assert composition(later, manifest, "M28_casos_por_estado", "2025-06", knowledge_cutoff=known)[ + "NEUROPEDIATRIA"] == 2 + assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1 + finally: + base.motor.dispose() diff --git a/uv.lock b/uv.lock index 64d1d40..a025434 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -768,6 +768,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/2a/101012d82931d9de3855384e1667e49c0e07a0048e3868f9fec1697293a9/fastapi-0.161.1-py3-none-any.whl", hash = "sha256:a1363080cf9aeedecd99f4e1a23669d7e77542227f6536f4d7bbd59f07ecaa94", size = 149049, upload-time = "2026-10-22T22:22:06.139Z" }, ] +[[package]] +name = "fhir-core" +version = "1.1.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f7/1b/0072a6ec7716df558bbcc134611df02d8ba22e286cbf64070fe6190f9d75/fhir_core-1.1.12.tar.gz", hash = "sha256:8f1674104ff575ff00dd2b4ff7ed6caf043d6d5a306990536e1b6ee2ccd06732", size = 40415, upload-time = "2026-10-18T20:20:47.011Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/22/4a118da089892195692b5e3519992708dc67fb84d49fddee5d9a1f3f43b4/fhir_core-1.1.12-py2.py3-none-any.whl", hash = "sha256:2ae218ed43b32705ce1c37150253942bd88350248a77f66e8ca2b6c3ed8263b2", size = 34264, upload-time = "2026-10-18T20:20:45.735Z" }, +] + +[[package]] +name = "fhir-resources" +version = "8.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fhir-core" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/06/331d78ad6db6903be6b912701c44b32af295279907b3a2e6ad6c2e2f97b1/fhir_resources-8.3.0.tar.gz", hash = "sha256:bdfd1c7bd1b89bfa269c1f435727771f6c632cd857e2848221713b3f8b9f46e8", size = 1617996, upload-time = "2026-07-03T15:23:54.01Z" } +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 = "flask" version = "3.1.3" @@ -3212,6 +3236,7 @@ sql-drivers = [ [package.dev-dependencies] dev = [ + { name = "fhir-resources" }, { name = "pytest" }, { name = "reportlab" }, ] @@ -3242,6 +3267,7 @@ provides-extras = ["sql-drivers"] [package.metadata.requires-dev] dev = [ + { name = "fhir-resources", specifier = ">=8" }, { name = "pytest", specifier = ">=8.0.0" }, { name = "reportlab", specifier = ">=4.0" }, ] diff --git a/webapi/__init__.py b/webapi/__init__.py index 9a68c32..c832bb5 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -78,11 +78,15 @@ def create_app() -> Flask: from importlib import import_module from pathlib import Path + from webapi.fhir import fhir_blueprint from webapi.kpis import kpis_blueprint - for domain in ("cacu", "cama"): - app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"), - Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}") + for domain in ("cacu", "cama", "tea"): + repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"]) + app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}") + # 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. from persistance import cacu as cacu_repositories diff --git a/webapi/compositions.py b/webapi/compositions.py index 91322b8..751ca0a 100644 --- a/webapi/compositions.py +++ b/webapi/compositions.py @@ -29,6 +29,7 @@ from webapi.metrics import ( MeasureQueries, Population, Question, + StatusAtEnd, Stratum, _population, _semantic_model_of, @@ -80,6 +81,8 @@ class CompositionDefinition: basis: str rules: dict[str, str] strata: tuple[Stratum, ...] + population: StatusAtEnd | None = None + meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) @property def measure_id(self) -> str: @@ -121,6 +124,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]: tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))), group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), + population=StatusAtEnd.of(meta.get("poblacion")), meta=meta, ) return definitions diff --git a/webapi/durations.py b/webapi/durations.py index 8c8ff95..b1d009b 100644 --- a/webapi/durations.py +++ b/webapi/durations.py @@ -6,7 +6,8 @@ cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`). -The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. +The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. With a population at +the period's end (`webapi.metrics.StatusAtEnd`), a unit's interval has a value only if it ended by the period's end. """ import dataclasses @@ -28,6 +29,7 @@ from webapi.metrics import ( MeasureQueries, Population, Question, + StatusAtEnd, _population, _semantic_model_of, key_of, @@ -90,6 +92,8 @@ class DurationDefinition: rules: dict[str, str] improvement_notation: str | None = None strata: tuple = () + population: StatusAtEnd | None = None + meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) @property def measure_id(self) -> str: @@ -127,7 +131,8 @@ def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]: rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"], int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None), group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), - improvement_notation=meta.get("improvement_notation"), + improvement_notation=meta.get("improvement_notation"), population=StatusAtEnd.of(meta.get("poblacion")), + meta=meta, ) return definitions @@ -145,6 +150,9 @@ class DurationQueries(MeasureQueries): o, q = self.d.observation, self.q conditions = [self._column(o.value).is_not(None)] conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at] + if self.status is not None: + # Counted at the period's end: the interval has to have ended by then. + conditions += [self._column(n) < self.events.c.periodo_fin for n in o.dated_at] if q.knowledge_cutoff is not None: conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at] return and_(*conditions) diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py new file mode 100644 index 0000000..c039626 --- /dev/null +++ b/webapi/fhir/__init__.py @@ -0,0 +1,360 @@ +"""A domain's FHIR R4 endpoint, `//fhir/`: its measures and, for TEA, its patients' screening. + + GET metadata CapabilityStatement + GET Measure, Measure/ the measures (dbt's definitions) + GET Measure//$evaluate-measure one period: periodStart and periodEnd, or `periodo` + GET MeasureReport?measure=&periodo=|period= several periods (one report each), with `tipo-periodo` + POST Measure/$recalcular queues the domain's recomputation + GET CodeSystem, CodeSystem/, ValueSet/ the project's code systems + GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only) + GET Patient//$resumen-tea TEA's patient summary (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`. +""" + +from collections.abc import Callable +from datetime import date, datetime, timedelta, timezone +from pathlib import Path + +from flask import Blueprint, request +from werkzeug.exceptions import HTTPException + +from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data +from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url +from webapi.fhir.terminology import code_systems, metric_value_set +from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of +from webapi.metrics import Question, UndecidedRule + +TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion") + + +def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: bool = False, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: + """The blueprint of a domain, to register with `url_prefix="//fhir"`. `repositories` is the domain's + `persistance.` module; `with_patients` adds TEA's patient routes (only in DEV).""" + blueprint = Blueprint(f"{project}_fhir", __name__) + titles = labels(manifest) + patients = with_patients and project == "tea" + + def definitions() -> dict: + """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" + every = {fhir_id(d): d for d in definitions_of(project, manifest).values()} + if project == "tea": + from webapi.fhir.tea import alterations_validated + + if not alterations_validated(): + every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")} + return every + + def definition_of(measure_id: str): + return definitions().get(measure_id.replace("_", "-")) + + def measure(definition) -> dict: + title, description = titles.get(definition.metric, (definition.measure_id, "")) + return measure_resource(definition, title, description) + + @blueprint.app_errorhandler(HTTPException) + def http_error(error: HTTPException): + """Under `//fhir/`, an error is an `OperationOutcome`, also for a route that doesn't exist there; + elsewhere, Flask's own answer.""" + if "/fhir/" not in request.path and not request.path.endswith("/fhir"): + return error + code = {404: "not-found", 405: "not-supported"}.get(error.code, "exception") + return outcome(error.code, code, error.description or error.name) + + @blueprint.get("/metadata") + def capability_statement(): + resources = [ + {"type": "Measure", "interaction": [{"code": "read"}, {"code": "search-type"}], + "operation": [{"name": "evaluate-measure", "definition": "http://hl7.org/fhir/OperationDefinition/Measure-evaluate-measure"}, + {"name": "recalcular", "definition": canonical("OperationDefinition/recalcular")}]}, + {"type": "MeasureReport", "interaction": [{"code": "search-type"}], + "searchParam": [{"name": n, "type": t} for n, t in (("measure", "reference"), ("period", "date"), + ("periodo", "token"), ("tipo-periodo", "token"))]}, + {"type": "CodeSystem", "interaction": [{"code": "read"}, {"code": "search-type"}]}, + ] + if patients: + resources += [ + {"type": "EpisodeOfCare", "interaction": [{"code": "search-type"}], + "searchParam": [{"name": n, "definition": canonical(f"SearchParameter/episode-{n}"), + "type": "date" if n in ("date", "fecha-etapa") else + "number" if n in ("mchat", "css") else "token"} for n in TEA_SEARCH], + "searchInclude": ["*"], + "operation": [{"name": "resumen-eeg", "definition": canonical("OperationDefinition/resumen-eeg")}]}, + {"type": "Patient", "operation": [{"name": "resumen-tea", + "definition": canonical("OperationDefinition/resumen-tea")}]}, + {"type": "ValueSet", "interaction": [{"code": "read"}]}, + ] + 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}, + "rest": [{"mode": "server", "resource": resources}]}) + + @blueprint.get("/Measure") + def measures(): + found = [measure(d) for _, d in sorted(definitions().items())] + if url := request.args.get("url"): + found = [m for m in found if m["url"] == url] + count, offset = page() + return fhir(searchset([entry(m) for m in found[offset:offset + count]], len(found), count, offset)) + + @blueprint.get("/Measure/") + def read_measure(measure_id: str): + definition = definition_of(measure_id) + if definition is None: + return outcome(404, "not-found", f"no hay un indicador {measure_id!r}") + return fhir(measure(definition)) + + def ask(definition, period, event_cutoff, knowledge_cutoff): + question = Question(definition.url, period.periodo_id, event_cutoff, knowledge_cutoff) + answer_of, _ = ANSWERS[scoring_of(definition)] + result = answer_of(project, definition, question, parameters=repositories.def_parametro_repository, + periods=repositories.dim_periodo_repository, history=repositories.history_repository, + queries=repositories.dbt_query_repository) + return measure_report(definition, question, result, period, now()) + + def cutoffs(): + return (_date(request.args.get("corte_evento")), + _datetime(request.args.get("corte_conocimiento")) or _last_load(repositories)) + + @blueprint.get("/Measure//$evaluate-measure") + def evaluate_measure(measure_id: str): + definition = definition_of(measure_id) + if definition is None: + return outcome(404, "not-found", f"no hay un indicador {measure_id!r}") + try: + event_cutoff, knowledge_cutoff = cutoffs() + period = _period_asked(repositories) + except ValueError as error: + return outcome(400, "invalid", str(error)) + except LookupError as error: + return outcome(404, "not-found", str(error)) + try: + return fhir(ask(definition, period, event_cutoff, knowledge_cutoff)) + except UndecidedRule as error: + return outcome(409, "business-rule", str(error)) + + @blueprint.get("/MeasureReport") + def measure_reports(): + asked = request.args.get("measure", "") + by_url = {measure_url(d): d for d in definitions().values()} + definition = by_url.get(asked.split("|")[0]) or definition_of(asked) + if definition is None: + return outcome(400, "required", "falta `measure` (el canónico o el id de un indicador)") + try: + event_cutoff, knowledge_cutoff = cutoffs() + periods = _periods_searched(repositories) + count, offset = page() + except ValueError as error: + return outcome(400, "invalid", str(error)) + except LookupError as error: + return outcome(404, "not-found", str(error)) + try: + reports = [ask(definition, p, event_cutoff, knowledge_cutoff) for p in periods[offset:offset + count]] + except UndecidedRule as error: + return outcome(409, "business-rule", str(error)) + return fhir(searchset([entry(r) for r in reports], len(periods), count, offset)) + + @blueprint.post("/Measure/$recalcular") + def recompute(): + from webapi.recomputation import RecomputationQueue + + RecomputationQueue().request_run(project) + return outcome(202, "informational", f"se pidió recalcular los indicadores de {project}", severity="information") + + @blueprint.get("/CodeSystem") + def code_system_search(): + systems = list(code_systems(project).values()) + return fhir(searchset([entry(s) for s in systems], len(systems), len(systems) or 1, 0)) + + @blueprint.get("/CodeSystem/") + def read_code_system(system_id: str): + system = code_systems(project).get(system_id) + return fhir(system) if system else outcome(404, "not-found", f"no hay un sistema de códigos {system_id!r}") + + if patients: + _patient_routes(blueprint, repositories, now) + return blueprint + + +def _period_asked(repositories): + """The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive).""" + if periodo := request.args.get("periodo"): + period = repositories.dim_periodo_repository.get(periodo) + if period is None: + raise LookupError(f"no hay un periodo {periodo!r}") + return period + start, end = request.args.get("periodStart"), request.args.get("periodEnd") + if not (start and end): + raise ValueError("falta el periodo: `periodStart` y `periodEnd`, o `periodo`") + start, end = date.fromisoformat(start), date.fromisoformat(end) + for period in repositories.dim_periodo_repository.list(limit=10000, inicio=start): + if period.fin - timedelta(days=1) == end: + return period + raise LookupError(f"no hay un periodo de {start} a {end}") + + +def _periods_searched(repositories) -> list: + """The periods of a `MeasureReport` search: `periodo` (comma-separated ids), or the periods of `tipo-periodo` + within `period=ge…` and `period=le…`.""" + if ids := [p for p in request.args.get("periodo", "").split(",") if p]: + periods = [repositories.dim_periodo_repository.get(i) for i in ids] + if missing := [i for i, p in zip(ids, periods) if p is None]: + raise LookupError(f"no hay un periodo {missing[0]!r}") + return periods + kind = request.args.get("tipo-periodo") + if not kind: + raise ValueError("falta `periodo` o `tipo-periodo` con `period`") + low, high = date.min, date.max + for value in request.args.getlist("period"): + if value.startswith("ge"): + low = date.fromisoformat(value[2:]) + elif value.startswith("le"): + high = date.fromisoformat(value[2:]) + else: + raise ValueError(f"`period` admite ge y le: {value!r}") + found = repositories.dim_periodo_repository.list(limit=10000, tipo=kind) + return sorted((p for p in found if p.inicio >= low and p.fin - timedelta(days=1) <= high), key=lambda p: p.inicio) + + +def _bound(name: str) -> tuple[float | None, float | None]: + """A number search parameter's bounds: `mchat=ge8&mchat=le20`, or one exact value.""" + low = high = None + for value in request.args.getlist(name): + if value.startswith("ge"): + low = float(value[2:]) + elif value.startswith("le"): + high = float(value[2:]) + else: + low = high = float(value) + return low, high + + +def _dates(name: str) -> tuple[date | None, date | None]: + low = high = None + for value in request.args.getlist(name): + if value.startswith("ge"): + low = date.fromisoformat(value[2:]) + elif value.startswith("le"): + high = date.fromisoformat(value[2:]) + else: + low = high = date.fromisoformat(value) + return low, high + + +def _patient_routes(blueprint: Blueprint, repositories, now) -> None: + from webapi.fhir import tea + + queries = repositories.dbt_query_repository + + def matching(): + """The episodes the search's parameters select, at its cut-off (`date=le…`, by default today).""" + unknown = [k for k in request.args if not k.startswith("_") and k not in TEA_SEARCH] + if unknown: + raise ValueError(f"parámetro de búsqueda no admitido: {unknown[0]!r}") + if request.args.get("alteracion") and not tea.alterations_validated(): + raise PermissionError("las alteraciones del EEG no se muestran hasta validar sus referencias") + since, cutoff = _dates("date") + cutoff = cutoff or now().date() + stage_from, stage_to = _dates("fecha-etapa") + mchat, css = _bound("mchat"), _bound("css") + + def within(value, bounds): + low, high = bounds + return value is not None and (low is None or value >= low) and (high is None or value <= high) + + found = [] + for e in tea.episodes(queries, cutoff): + stage = e.stage + if since is not None and e.finished and stage[1] < since: + continue + if (status := request.args.get("status")) and status != ("finished" if e.finished else "active"): + continue + if (etapa := request.args.get("etapa")) and (stage is None or stage[0] not in etapa.split(",")): + continue + if (stage_from or stage_to) and (stage is None or not within(stage[1].toordinal(), ( + stage_from and stage_from.toordinal(), stage_to and stage_to.toordinal()))): + continue + if (group := request.args.get("grupo-edad")) and e.child["grupo_edad"] not in group.split(","): + continue + if request.args.getlist("mchat") and not within(e.child["mchat"], mchat): + continue + if request.args.getlist("css") and not within(e.child["css_ados2"], css): + continue + if result := request.args.get("resultado-eeg"): + shown = e.eeg_result if tea.alterations_validated() else ( + "sin-eeg-valido" if e.eeg_result == "sin-eeg-valido" else "valido") + if shown not in result.split(","): + continue + if (alteration := request.args.get("alteracion")) and alteration not in e.alterations(): + continue + found.append(e) + return sorted(found, key=lambda e: e.pseudonym) + + @blueprint.get("/EpisodeOfCare") + def episodes_of_care(): + try: + found = matching() + count, offset = page() + except ValueError as error: + return tea_outcome(400, "invalid", error) + except PermissionError as error: + return tea_outcome(403, "forbidden", error) + simulated = simulated_data() + shown = found[offset:offset + count] + entries = [entry(tea.episode_of_care(e, simulated)) for e in shown] + if request.args.get("_include"): + entries += [entry(r, "include") for e in shown for r in _included(tea, queries, e, simulated)] + return fhir(searchset(entries, len(found), count, offset)) + + @blueprint.get("/EpisodeOfCare/$resumen-eeg") + def eeg_summary(): + try: + found = matching() + except ValueError as error: + return tea_outcome(400, "invalid", error) + except PermissionError as error: + return tea_outcome(403, "forbidden", error) + valid = [e for e in found if e.eeg_result != "sin-eeg-valido"] + parameters = [{"name": "con_eeg_valido", "valueInteger": len(valid)}, + {"name": "sin_eeg_valido", "valueInteger": len(found) - len(valid)}] + if tea.alterations_validated(): + by_alteration: dict[str, int] = {} + for e in valid: + for code in e.alterations(): + by_alteration[code] = by_alteration.get(code, 0) + 1 + parameters += [{"name": "normales", "valueInteger": sum(e.eeg_result == "normal" for e in valid)}, + {"name": "anormales", "valueInteger": sum(e.eeg_result == "anormal" for e in valid)}, + *({"name": "por_alteracion", "part": [{"name": "alteracion", "valueCode": code}, + {"name": "pacientes", "valueInteger": n}]} + for code, n in sorted(by_alteration.items()))] + return fhir({"resourceType": "Parameters", "parameter": parameters}) + + @blueprint.get("/Patient//$resumen-tea") + def patient_summary(pseudonym: str): + pac_id = tea.patient_of(queries, pseudonym) + if pac_id is None: + return outcome(404, "not-found", f"no hay un paciente {pseudonym!r}") + return fhir(tea.patient_summary(queries, pac_id, now().date(), simulated_data())) + + @blueprint.get("/ValueSet/tea-alteracion") + def alteration_types(): + return fhir(metric_value_set()) + + +def tea_outcome(status: int, code: str, error: Exception): + return outcome(status, code, str(error)) + + +def _included(tea, queries, e, simulated: bool) -> list[dict]: + """What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG.""" + from sqlalchemy import select + + persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"])) + resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated), + tea.care_plan(e, simulated)] + resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r] + if (eeg := e.study_eeg()) is not None: + resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated) + return resources diff --git a/webapi/fhir/common.py b/webapi/fhir/common.py new file mode 100644 index 0000000..4b01062 --- /dev/null +++ b/webapi/fhir/common.py @@ -0,0 +1,93 @@ +"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with +their paging links, the simulated-data tag and the project's canonical URLs.""" + +import json +import os +from urllib.parse import urlencode + +from flask import Response, request + +FHIR_VERSION = "4.0.1" +MEDIA_TYPE = "application/fhir+json" +BASE = "https://isssteleon.org/fhir" +CODE_SYSTEM = f"{BASE}/CodeSystem" +VALUE_SET = f"{BASE}/ValueSet" +STRUCTURE = f"{BASE}/StructureDefinition" +SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"} +MAX_COUNT = 200 +DEFAULT_COUNT = 50 + + +def fhir(resource: dict, status: int = 200) -> Response: + """A resource as the answer, in FHIR's JSON media type.""" + return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE) + + +def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response: + """An error as an `OperationOutcome` (`code` from FHIR's issue-type), with the HTTP status it goes with.""" + return fhir({"resourceType": "OperationOutcome", + "issue": [{"severity": severity, "code": code, "diagnostics": diagnostics}]}, status) + + +def canonical(path: str) -> str: + """The absolute canonical of a project resource: `Measure/`, `CodeSystem/`…""" + return f"{BASE}/{path}" + + +def coding(system: str, code: str, display: str | None = None) -> dict: + return {"system": system, "code": code, **({"display": display} if display else {})} + + +def concept(system: str, code: str, display: str | None = None, text: str | None = None) -> dict: + return {"coding": [coding(system, code, display)], **({"text": text} if text else {})} + + +def tagged(resource: dict, simulated: bool) -> dict: + """The resource with the simulated-data tag in its `meta`, when its data are simulated.""" + if simulated: + resource.setdefault("meta", {}).setdefault("tag", []).append(SIMULATED) + return resource + + +def simulated_data() -> bool: + """Patient data are simulated in the DEV deployment (`DEV_REVISION`), the only one that serves them.""" + return bool(os.environ.get("DEV_REVISION")) + + +def page() -> tuple[int, int]: + """`_count` (at most `MAX_COUNT`) and `_offset` of the search. `ValueError` if one isn't a number.""" + count = int(request.args.get("_count", DEFAULT_COUNT)) + offset = int(request.args.get("_offset", 0)) + if count < 0 or offset < 0: + raise ValueError("`_count` y `_offset` no pueden ser negativos") + return min(count, MAX_COUNT), offset + + +def searchset(entries: list[dict], total: int, count: int, offset: int) -> dict: + """A `searchset` Bundle with the page's entries, the total and the `self`, `next` and `previous` links.""" + def link(relation: str, at: int) -> dict: + args = [(k, v) for k, v in request.args.items(multi=True) if k not in ("_count", "_offset")] + return {"relation": relation, "url": f"{request.base_url}?{urlencode([*args, ('_count', count), ('_offset', at)])}"} + + links = [link("self", offset)] + if offset + count < total: + links.append(link("next", offset + count)) + if offset > 0: + links.append(link("previous", max(0, offset - count))) + return {"resourceType": "Bundle", "type": "searchset", "total": total, "link": links, "entry": entries} + + +def fhir_base() -> str: + """This request's FHIR endpoint, `…//fhir/`: what a `fullUrl` is relative to.""" + url = request.base_url + return url[:url.index("/fhir/") + len("/fhir/")] if "/fhir/" in url else url.rstrip("/") + "/" + + +def entry(resource: dict, mode: str | None = "match") -> dict: + """A Bundle entry: its `fullUrl` when the resource has an id, and its search mode in a searchset.""" + item = {"resource": resource} + if "id" in resource: + item = {"fullUrl": f"{fhir_base()}{resource['resourceType']}/{resource['id']}", **item} + if mode: + item["search"] = {"mode": mode} + return item diff --git a/webapi/fhir/measures.py b/webapi/fhir/measures.py new file mode 100644 index 0000000..0cd6e11 --- /dev/null +++ b/webapi/fhir/measures.py @@ -0,0 +1,194 @@ +"""A domain's measures as FHIR R4 `Measure` resources, and their answers as `MeasureReport`s. + +The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from +each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as +extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier +has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds +its category as a `component`. A duration reports the units without a value as their own population. +""" + +import json +from datetime import datetime, timedelta +from pathlib import Path + +from webapi.compositions import CompositionAnswer, CompositionDefinition +from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition +from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept +from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts + +SCORING_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-scoring" +IMPROVEMENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation" +GROUP_SYSTEM = f"{CODE_SYSTEM}/grupo-medida" +STRATIFIER_SYSTEM = f"{CODE_SYSTEM}/estratificador" +EXCLUDED = "measure-population-exclusion" +FIGURES = f"{STRUCTURE}/figuras" +PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo" +CATEGORY_LABEL = f"{STRUCTURE}/categoria" +CONTRACT = f"{STRUCTURE}/contrato" +REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion" +POPULATION_LABELS = { + "initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador", + "denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor", + EXCLUDED: "Unidades sin valor", +} + + +def scoring(definition) -> str: + """The FHIR scoring: a composition is a `cohort` (its categories are a stratifier).""" + if isinstance(definition, CompositionDefinition): + return "cohort" + return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion" + + +def labels(manifest: Path) -> dict[str, tuple[str, str]]: + """Each metric's (title, description) in the manifest: `meta.titulo` when the label had to differ.""" + metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() + return {m["name"]: (m["config"].get("meta", {}).get("titulo") or m["label"], (m.get("description") or "").strip()) + for m in metrics} + + +def fhir_id(definition) -> str: + """The measure's id as FHIR allows one (letters, digits, `-` and `.`): `M21_diagnosticados_con_eeg` -> + `M21-diagnosticados-con-eeg`.""" + return definition.measure_id.replace("_", "-") + + +def measure_url(definition) -> str: + return canonical(f"Measure/{fhir_id(definition)}") + + +def _populations(definition) -> list[dict]: + """Each population with the dbt metric that counts it as its criteria.""" + if scoring(definition) == "proportion": + metrics = {**{c: definition.denominator.metric for c in definition.denominator.codes}, + **{c: definition.numerator.metric for c in definition.numerator.codes}, + **({c: definition.exclusion.metric for c in definition.exclusion.codes} + if getattr(definition, "exclusion", None) else {})} + else: + codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION, + EXCLUDED] + metrics = {c: definition.metric for c in codes} + return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c), + "criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()] + + +def measure_resource(definition, title: str, description: str) -> dict: + """The `Measure` of a definition: one group per group it publishes, each with its populations and strata.""" + meta = getattr(definition, "meta", {}) or {} + strata = [{"code": concept(STRATIFIER_SYSTEM, s.name, text=s.spec.get("etiqueta", s.name))} + for s in definition.strata] + if isinstance(definition, CompositionDefinition): + strata.insert(0, {"code": concept(STRATIFIER_SYSTEM, definition.category.value)}) + groups = [{"code": concept(GROUP_SYSTEM, definition.group), "population": _populations(definition), + **({"stratifier": strata} if strata else {})}] + groups += [{"code": concept(GROUP_SYSTEM, g.name, g.label), "population": _populations(definition)} + for g in getattr(definition, "groups", ())] + extensions = [{"url": CONTRACT, "valueCode": meta.get("contrato", "")}, + *({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())), + *({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))] + category = meta.get("categoria", {}) + extensions += [{"url": CATEGORY_LABEL, "extension": [ + {"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]}, + {"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()] + if meta.get("requiere_validacion"): + extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]}) + resource = { + "resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition), + "version": definition.version, "name": definition.metric, "title": title, "status": "active", + "description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)], + "scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups, + } + if definition.basis: + resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis) + if definition.improvement_notation: + resource["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation) + return resource + + +def _count(code: str, n: int) -> dict: + return {"code": concept(POPULATION_SYSTEM, code), "count": n} + + +def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -> dict: + cells = {"population": [*(_count(c, counts.denominator) for c in definition.denominator.codes), + *(_count(c, counts.numerator) for c in definition.numerator.codes)]} + if excluded is not None and getattr(definition, "exclusion", None): + cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes] + if counts.proportion is not None: + cells["measureScore"] = {"value": counts.proportion} + return cells + + +def _label(spec: dict, value: str) -> str | None: + """A stratum value's label, when the stratum's `valores` maps values to labels.""" + labels_of = spec.get("valores") + return labels_of.get(value) if isinstance(labels_of, dict) else None + + +def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict: + return concept(f"{CODE_SYSTEM}/{stratifier.replace('_', '-')}", value, display) + + +def _groups(definition, result) -> list[dict]: + if isinstance(result, CompositionAnswer): + group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [_count("initial-population", + result.total)]} + labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()} + category = definition.category.value + stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [ + {"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]} + for c, n in sorted(result.categories.items())]}] + for name, by_value in result.strata.items(): + stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)], + "stratum": [{"component": [ + {"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)}, + {"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)}, + ], "population": [_count("initial-population", n)]} + for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]}) + group["stratifier"] = stratifiers + return [group] + if isinstance(result, DurationAnswer): + group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [ + _count("initial-population", result.initial), _count(OBSERVATION, result.n), + _count(EXCLUDED, result.excluded)]} + if result.median is not None: + group["measureScore"] = {"value": result.median, "unit": "d", "extension": [ + {"url": f"{STRUCTURE}/q1", "valueDecimal": result.q1}, + {"url": f"{STRUCTURE}/q3", "valueDecimal": result.q3}]} + return [group] + assert isinstance(result, Answer) + spec_of = {s.name: s.spec for s in definition.strata} + group = {"code": concept(GROUP_SYSTEM, definition.group), **_proportion_cells(definition, result.total, + result.excluded)} + if result.strata: + group["stratifier"] = [{"code": [concept(STRATIFIER_SYSTEM, name, text=spec_of[name].get("etiqueta"))], + "stratum": [{"value": _stratum_value(name, value, _label(spec_of[name], value)), + **_proportion_cells(definition, c)} + for value, c in sorted(values.items())]} + for name, values in result.strata.items()] + groups = [group] + labels_of = {g.name: g.label for g in getattr(definition, "groups", ())} + groups += [{"code": concept(GROUP_SYSTEM, name, labels_of.get(name)), **_proportion_cells(definition, counts)} + for name, counts in result.groups.items()] + return groups + + +def measure_report(definition, question, result, period, generated_at: datetime) -> dict: + """An answer as a FHIR R4 `MeasureReport` (summary), naming its measure by its absolute canonical.""" + cutoff = getattr(result, "event_cutoff", None) or question.event_cutoff + extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}] + if cutoff is not None: + extensions.append({"url": EVENT_CUTOFF, "valueDate": cutoff.isoformat()}) + if question.knowledge_cutoff is not None: + extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()}) + report = { + "resourceType": "MeasureReport", "id": f"{fhir_id(definition)}-{result.report_id}", "status": "complete", + "type": "summary", "measure": f"{measure_url(definition)}|{definition.version}", + "date": generated_at.isoformat(), + # FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`. + "period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()}, + "extension": extensions, "group": _groups(definition, result), + } + if definition.improvement_notation: + report["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation) + return report diff --git a/webapi/fhir/tea.py b/webapi/fhir/tea.py new file mode 100644 index 0000000..a16d3e8 --- /dev/null +++ b/webapi/fhir/tea.py @@ -0,0 +1,352 @@ +"""TEA's patients as FHIR R4 resources: the follow-up list as `EpisodeOfCare`s and the patient summary. + +Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, not states: every state here is taken +at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its +stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a +`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not +valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. + +Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`): +the alteration filter, the abnormal/normal split, and the metric and electrode observations. +""" + +import os +from dataclasses import dataclass +from datetime import date + +from sqlalchemy import column, select, table + +from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged +from webapi.follow_up.listing import seudonimo + +STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"), + ("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"), + ("EEG", "fecha_eeg", "EEG de buena calidad")) +CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"), + ("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"), + ("calidad_correlacion", "Baja correlación entre canales", "canales"), + ("calidad_sin_senal", "Canales planos o sin señal", "canales"), + ("calidad_linea", "Ruido de la línea eléctrica", "dB")) +ALTERED = ("aumentado", "disminuido") +INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation" +ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason" +ICD10 = "http://hl7.org/fhir/sid/icd-10" +CATALOG = f"{CODE_SYSTEM}/tea-catalogo" +STAGE_DATE = f"{STRUCTURE}/fecha-etapa" +AGE_GROUP = f"{STRUCTURE}/grupo-edad" +DEFAULT_SALT = "dev-simulado" + +FOLLOW_UP = table("tea_seguimiento", *map(column, ( + "pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2", + "fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg"))) +EEGS = table("tea_paciente_eegs", *map(column, ( + "procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido", + *(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno"))))) +METRICS = table("tea_paciente_eeg_metricas", *map(column, ( + "procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado"))) +ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo", + "valor"))) +ADOS2 = table("tea_paciente_ados2", *map(column, ( + "procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo", + "etiqueta", "puntaje", "puntaje_algoritmo"))) +PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento")) + + +def alterations_validated() -> bool: + """Whether the domain expert validated the reference ranges, effect texts and quality thresholds + (`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown.""" + return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si") + + +def salt() -> str: + return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT) + + +def _date(value) -> date | None: + if value is None or isinstance(value, date): + return value + return date.fromisoformat(str(value)[:10]) + + +def _rows(queries, query) -> list[dict]: + columns, rows = queries.rows(query) + return [dict(zip(columns, row)) for row in rows] + + +@dataclass +class Episode: + """A child's screening at the cut-off: its follow-up row, the steps reached, the study's EEG and its metrics.""" + + child: dict + cutoff: date + eegs: list[dict] + metrics: list[dict] + + @property + def pseudonym(self) -> str: + return seudonimo(self.child["pac_id"], salt()) + + def reached(self) -> list[tuple[str, date, str]]: + steps = [] + for code, field, label in STEPS: + when = _date(self.child[field]) + if when is None or when > self.cutoff: + break + steps.append((code, when, label)) + return steps + + @property + def stage(self) -> tuple[str, date] | None: + steps = self.reached() + return (steps[-1][0], steps[-1][1]) if steps else None + + @property + def finished(self) -> bool: + return any(code == "EEG" for code, _, _ in self.reached()) + + @property + def pending(self) -> list[str]: + done = {code for code, _, _ in self.reached()} + return [label for code, _, label in STEPS if code not in done] + + @property + def diagnosis(self) -> bool | None: + """True with a F84.0 note by the cut-off, False with only notes without it, None without a note.""" + if (_date(self.child["fecha_tea"]) or date.max) <= self.cutoff: + return True + if (_date(self.child["fecha_sin_tea"]) or date.max) <= self.cutoff: + return False + return None + + def study_eeg(self) -> dict | None: + """The first good EEG by the cut-off; without one, the latest by then (not valid).""" + known = sorted((e for e in self.eegs if (_date(e["fecha_eeg"]) or date.max) <= self.cutoff), + key=lambda e: (_date(e["fecha_eeg"]), e["procedimiento_id"])) + good = [e for e in known if e["valido"] == 1] + return good[0] if good else (known[-1] if known else None) + + def alterations(self) -> list[str]: + eeg = self.study_eeg() + if eeg is None or eeg["valido"] != 1: + return [] + return sorted(m["metrica"] for m in self.metrics + if m["procedimiento_id"] == eeg["procedimiento_id"] and m["estado"] in ALTERED) + + @property + def eeg_result(self) -> str: + eeg = self.study_eeg() + if eeg is None or eeg["valido"] != 1: + return "sin-eeg-valido" + return "anormal" if self.alterations() else "normal" + + +def episodes(queries, cutoff: date) -> list[Episode]: + """Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics.""" + eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS)) + by_child = {} + for child in _rows(queries, select(FOLLOW_UP)): + if (_date(child["fecha_mchat"]) or date.max) <= cutoff: + by_child[child["pac_id"]] = Episode(child, cutoff, [], []) + for eeg in eegs: + if eeg["pac_id"] in by_child: + by_child[eeg["pac_id"]].eegs.append(eeg) + for metric in metrics: + if metric["pac_id"] in by_child: + by_child[metric["pac_id"]].metrics.append(metric) + return list(by_child.values()) + + +def patient_of(queries, pseudonym: str) -> int | None: + """The `pac_id` behind a pseudonym, among the cohort's children.""" + for child in _rows(queries, select(FOLLOW_UP.c.pac_id)): + if seudonimo(child["pac_id"], salt()) == pseudonym: + return child["pac_id"] + return None + + +# --- resources ------------------------------------------------------------------------------------------------------- + + +def patient(pac_id: int, birth: date | None, simulated: bool) -> dict: + resource = {"resourceType": "Patient", "id": seudonimo(pac_id, salt())} + if birth is not None: + resource["birthDate"] = _date(birth).strftime("%Y-%m") + return tagged(resource, simulated) + + +def episode_of_care(e: Episode, simulated: bool) -> dict: + stage = e.stage + resource = { + "resourceType": "EpisodeOfCare", "id": e.pseudonym, "status": "finished" if e.finished else "active", + "patient": {"reference": f"Patient/{e.pseudonym}"}, + "period": {"start": _date(e.child["fecha_mchat"]).isoformat(), + **({"end": stage[1].isoformat()} if e.finished else {})}, + "extension": [{"url": AGE_GROUP, "valueCoding": {"system": f"{CODE_SYSTEM}/grupo-edad", + "code": e.child["grupo_edad"]}}], + } + if stage is not None: + resource["type"] = [concept(f"{CODE_SYSTEM}/paso", stage[0])] + resource["extension"].append({"url": STAGE_DATE, "valueDate": stage[1].isoformat()}) + return tagged(resource, simulated) + + +def care_plan(e: Episode, simulated: bool) -> dict: + """The episode's steps, each `completed` with its date or `not-started`.""" + done = {code: when for code, when, _ in e.reached()} + activities = [{"detail": { + "code": concept(f"{CODE_SYSTEM}/paso", code, text=label), + "status": "completed" if code in done else "not-started", + **({"scheduledString": done[code].isoformat()} if code in done else {})}} for code, _, label in STEPS] + return tagged({"resourceType": "CarePlan", "id": f"pasos-{e.pseudonym}", "status": "active" if not e.finished + else "completed", "intent": "plan", "subject": {"reference": f"Patient/{e.pseudonym}"}, + "extension": [{"url": f"{STRUCTURE}/episodio", "valueReference": { + "reference": f"EpisodeOfCare/{e.pseudonym}"}}], + "activity": activities}, simulated) + + +def mchat_observation(e: Episode, simulated: bool) -> dict | None: + if e.child["mchat"] is None: + return None + return tagged({"resourceType": "Observation", "id": f"mchat-{e.pseudonym}", "status": "final", + "code": concept(CATALOG, "mchat.puntaje", "M-CHAT-R/F: puntaje total"), + "subject": {"reference": f"Patient/{e.pseudonym}"}, + "effectiveDateTime": _date(e.child["fecha_mchat"]).isoformat(), + "valueInteger": int(e.child["mchat"])}, simulated) + + +def condition(e: Episode, simulated: bool) -> dict | None: + if not e.diagnosis: + return None + return tagged({"resourceType": "Condition", "id": f"tea-{e.pseudonym}", + "code": concept(ICD10, "F84.0", "Autismo en la niñez"), + "subject": {"reference": f"Patient/{e.pseudonym}"}, + "recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated) + + +def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]: + observations = [] + for name, label, unit in CRITERIA: + if eeg[name] is None: + continue + value = ({"valueInteger": int(eeg[name])} if unit == "canales" + else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}}) + observations.append(tagged({ + "resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}", + "status": "final", "code": concept(CATALOG, f"eeg.{name}", label), + "subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(), + **value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")], + }, simulated)) + return observations + + +def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str, + simulated: bool) -> list[dict]: + """One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or + why it couldn't be evaluated) and one per metric with a component per electrode.""" + from webapi.fhir.terminology import TEA_EEG + + observations = [] + for m in sorted((m for m in metrics if m["procedimiento_id"] == eeg["procedimiento_id"]), key=lambda m: m["metrica"]): + spec = TEA_EEG["metricas"].get(m["metrica"], {"etiqueta": m["metrica"], "unidad": ""}) + code = concept(f"{CODE_SYSTEM}/tea-eeg-metrica", m["metrica"], spec["etiqueta"]) + resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}", + "status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()} + if m["valor"] is None or m["valor_z"] is None: + resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown") + else: + resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]} + resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get( + m["estado"], "N"))] + resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"), + "valueQuantity": {"value": round(float(m["valor_z"]), 2)}}] + if m["ref_min"] is not None: + resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]}, + "high": {"value": float(m["ref_max"]), "unit": spec["unidad"]}, + "text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}] + observations.append(tagged(resource, simulated)) + at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]] + if at: + observations.append(tagged({ + "resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}", + "status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(), + "component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]), + "valueQuantity": {"value": float(x["valor"])}} + for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated)) + return observations + + +def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]: + """The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has + no result beyond its quality, and the alterations stay out until validated.""" + quality = quality_observations(eeg, pseudonym, simulated) + altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated) + if eeg["valido"] == 1 and alterations_validated() else []) + procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed", + "code": concept(CATALOG, "eeg", "Electroencefalograma"), + "subject": {"reference": f"Patient/{pseudonym}"}, + "performedDateTime": _date(eeg["fecha_eeg"]).isoformat()}, simulated) + report = {"resourceType": "DiagnosticReport", "id": f"eeg-{eeg['procedimiento_id']}", "status": "final", + "code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(), + "result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered], + "conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]} + if eeg["duracion_min"] is not None or eeg["canales"] is not None: + report["extension"] = [e for e in ( + {"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])} + if eeg["duracion_min"] is not None else None, + {"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None, + ) if e] + if eeg["valido"] != 1: + report["conclusion"] = "EEG de mala calidad: no es válido para el estudio." + return [procedure, tagged(report, simulated), *quality, *altered] + + +def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None: + """The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the + items, each item with its algorithm score.""" + if not rows: + return None + first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"])) + items = [r for r in rows if r["procedimiento_id"] == first["procedimiento_id"] and r["reactivo"]] + components = [] + if first["modulo"]: + components.append({"code": concept(CATALOG, "ados2.modulo", "Módulo"), + "valueCodeableConcept": concept(CATALOG, f"ados2.modulo.{first['modulo']}")}) + if first["algoritmo"]: + components.append({"code": concept(CATALOG, "ados2.algoritmo", "Algoritmo"), "valueString": first["algoritmo"]}) + if first["css"] is not None: + components.append({"code": concept(CATALOG, "ados2.css", "Puntaje de severidad (CSS)"), + "valueInteger": int(first["css"])}) + if first["clasificacion"]: + components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"), + "valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")}) + for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")): + total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain) + components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total}) + components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]), + "extension": [{"url": f"{STRUCTURE}/puntaje-algoritmo", "valueInteger": int(r["puntaje_algoritmo"])}, + {"url": f"{STRUCTURE}/dominio", "valueCode": r["dominio"]}]} + for r in sorted(items, key=lambda r: r["reactivo"])] + return tagged({"resourceType": "Observation", "id": f"ados2-{first['procedimiento_id']}", "status": "final", + "code": concept(CATALOG, "ados2", "ADOS-2"), "subject": {"reference": f"Patient/{pseudonym}"}, + "effectiveDateTime": _date(first["fecha_ados2"]).isoformat(), "component": components}, simulated) + + +def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict: + """The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today.""" + pseudonym = seudonimo(pac_id, salt()) + persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id)) + resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)] + ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated) + resources += [ados2] if ados2 else [] + (child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None] + if child is not None: + e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)), + _rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id))) + eeg = e.study_eeg() + if eeg is not None: + electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id)) + resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated) + return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]} diff --git a/webapi/fhir/tea_eeg.toml b/webapi/fhir/tea_eeg.toml new file mode 100644 index 0000000..709e3ae --- /dev/null +++ b/webapi/fhir/tea_eeg.toml @@ -0,0 +1,53 @@ +# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where +# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1). +# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`. + +[metricas.ritmo_posterior] +etiqueta = "Ritmo posterior" +unidad = "Hz" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."] + +[metricas.husos_sueno_n2] +etiqueta = "Husos de sueño N2" +unidad = "husos/min" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."] + +[metricas.husos_sueno_n3] +etiqueta = "Husos de sueño N3" +unidad = "husos/min" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."] + +[metricas.picos_paroxisticos] +etiqueta = "Picos paroxísticos" +unidad = "picos/min" +efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."] + +[metricas.gradiente_anteroposterior] +etiqueta = "Gradiente anteroposterior" +unidad = "razón posterior/anterior" +efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."] +efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."] + +[electrodos] +Fp1 = [-0.25, 0.77] +Fp2 = [0.25, 0.77] +F7 = [-0.65, 0.47] +F3 = [-0.33, 0.4] +Fz = [0.0, 0.38] +F4 = [0.33, 0.4] +F8 = [0.65, 0.47] +T3 = [-0.8, 0.0] +C3 = [-0.4, 0.0] +Cz = [0.0, 0.0] +C4 = [0.4, 0.0] +T4 = [0.8, 0.0] +T5 = [-0.65, -0.47] +P3 = [-0.33, -0.4] +Pz = [0.0, -0.38] +P4 = [0.33, -0.4] +T6 = [0.65, -0.47] +O1 = [-0.25, -0.77] +O2 = [0.25, -0.77] diff --git a/webapi/fhir/terminology.py b/webapi/fhir/terminology.py new file mode 100644 index 0000000..4259326 --- /dev/null +++ b/webapi/fhir/terminology.py @@ -0,0 +1,74 @@ +"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's +catalog (`core/catalogos/.toml`: studies, results and their values), TEA's screening stages and diagnostic +results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`).""" + +import tomllib +from pathlib import Path + +from webapi.fhir.common import CODE_SYSTEM, canonical +from webapi.orchestration.reference.catalogs import ruta_de_catalogo + +TEA_EEG = tomllib.loads((Path(__file__).parent / "tea_eeg.toml").read_text(encoding="utf-8")) +STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psicológica"), + ("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG")) +DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado")) +QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar")) + + +def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict: + resource = {"resourceType": "CodeSystem", "id": id_, "url": f"{CODE_SYSTEM}/{id_}", "name": id_.replace("-", "_"), + "title": title, "status": "active", "content": "complete", "concept": concepts} + if hierarchy: + resource["hierarchyMeaning"] = "part-of" + return resource + + +def catalog(domain: str) -> dict: + """The domain's catalog: each study, its results under it and each coded result's values under the result.""" + studies = tomllib.loads(ruta_de_catalogo(domain).read_text(encoding="utf-8")) + concepts = [] + for study_id, study in studies.items(): + results = [] + for name, result in study.get("resultados", {}).items(): + values = [{"code": f"{study_id}.{name}.{v['valor']}", "display": v["etiqueta"]} + for v in result.get("valores", ())] + results.append({"code": f"{study_id}.{name}", "display": result["etiqueta"], + **({"concept": values} if values else {})}) + concepts.append({"code": study_id, "display": study["etiqueta"], **({"concept": results} if results else {})}) + return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True) + + +def tea_code_systems() -> dict[str, dict]: + metrics = [{"code": code, "display": spec["etiqueta"], "property": [ + {"code": "unidad", "valueString": spec["unidad"]}, + *({"code": f"efecto-{state}", "valueString": text} for state, texts in spec.get("efectos", {}).items() + for text in texts)]} for code, spec in TEA_EEG["metricas"].items()] + systems = [ + _code_system("paso", "Etapa del tamizaje de TEA", [{"code": c, "display": d} for c, d in STAGES]), + _code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]), + _code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]), + {**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics), + "property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"}, + {"code": "efecto-disminuido", "type": "string"}]}, + _code_system("electrodo-10-20", "Electrodos del sistema 10-20", + [{"code": e, "display": e} for e in TEA_EEG["electrodos"]]), + _code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [ + {"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"}, + {"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]), + ] + return {s["id"]: s for s in systems} + + +def code_systems(domain: str) -> dict[str, dict]: + """Every code system the domain's FHIR endpoint serves, by id.""" + systems = {f"{domain}-catalogo": catalog(domain)} + if domain == "tea": + systems.update(tea_code_systems()) + return systems + + +def metric_value_set() -> dict: + """The alteration types: the EEG metrics' `ValueSet`.""" + return {"resourceType": "ValueSet", "id": "tea-alteracion", "url": canonical("ValueSet/tea-alteracion"), + "name": "tea_alteracion", "title": "Tipos de alteración del EEG", "status": "active", + "compose": {"include": [{"system": f"{CODE_SYSTEM}/tea-eeg-metrica"}]}} diff --git a/webapi/imports/connectors/edf.py b/webapi/imports/connectors/edf.py index d132f00..cd2dfa8 100644 --- a/webapi/imports/connectors/edf.py +++ b/webapi/imports/connectors/edf.py @@ -1,4 +1,3 @@ -from datetime import date, timedelta from pathlib import PurePath from typing import Any @@ -11,15 +10,12 @@ from webapi.imports.connectors.errors import ConnectorError from webapi.imports.connectors.registry import register_connector from webapi.imports.connectors.tabular import FileConnector -MAX_LISTED_EVENTS = 20 - @register_connector class EdfConnector(FileConnector): - """EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`: - patient and dates from the header, an estimated background rhythm from - the posterior channels, a text summary of the recording, and the file - itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`).""" + """EEG recordings (`.edf`), one row per file, shaped for `tea.Eeg`: the laboratory's study id, the patient + and the study date from the header, the channels and duration of the recording, and the file itself (column + `estudio`, stored in `eeg.eeg_estudio`). The quality criteria, sleep and metrics are the EEG analysis'.""" kind = "edf" label = "EEG (EDF)" @@ -57,49 +53,12 @@ class EdfConnector(FileConnector): eeg = EegRecording.read(raw) except ExtractionError as exc: raise ConnectorError(f"{name}: {exc}") from exc - patient = eeg.patient - study_date = eeg.start.date() if eeg.start else None - rhythm = eeg.background_rhythm() return { "id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem, - "paciente": patient.code, - "sexo": patient.sex, - "fecha_nacimiento_declarada": patient.birthdate, - "edad_meses": age_in_months(patient.birthdate, study_date), - "fecha_estudio": study_date, - "duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None, - "ritmo_base_frecuencia": rhythm["frequency_hz"], - "ritmo_base_amplitud": rhythm["amplitude_uv"], - "descripcion_senal": describe(eeg), + "paciente": eeg.patient.code, + "fecha_estudio": eeg.start.date() if eeg.start else None, + "canales": len(eeg.channels), + "duracion_min": round(eeg.duration_seconds / 60, 1) if eeg.duration_seconds else None, "archivo": name, "estudio": raw, } - - -def describe(eeg: EegRecording) -> str: - channels = eeg.channels - parts = [ - f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant, - f"duración {timedelta(seconds=round(eeg.duration_seconds))}", - "montaje: " + ", ".join(c.label for c in channels), - ] - fields = eeg.recording_fields - if fields["equipment"]: - parts.append(f"equipo: {fields['equipment']}") - if fields["technician"]: - parts.append(f"técnico: {fields['technician']}") - events = eeg.annotations() - if events: - listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS]) - more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else "" - parts.append(f"eventos: {listed}{more}") - return ". ".join(parts) + "." - - -def age_in_months(birthdate: date | None, on: date | None) -> float | None: - if birthdate is None or on is None or on < birthdate: - return None - months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month) - if on.day < birthdate.day: - months -= 1 - return float(months) diff --git a/webapi/imports/schemas/coercion.py b/webapi/imports/schemas/coercion.py index 6b07a43..c84e929 100644 --- a/webapi/imports/schemas/coercion.py +++ b/webapi/imports/schemas/coercion.py @@ -7,7 +7,7 @@ from datetime import date, datetime from enum import Enum from typing import Annotated, Any, Optional, Type -from pydantic import BeforeValidator, StringConstraints, ValidationInfo +from pydantic import BeforeValidator, Field, StringConstraints, ValidationInfo from core.columns import HOSPITAL_ID_LENGTH from extraction import ExtractionError @@ -140,7 +140,7 @@ CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")] def edf_file(v: Any) -> Any: - """`eeg_estudio.eeg_estudio`: an EDF file MNE can open (TEA amendment). + """`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment). JSON sources may carry it base64-encoded.""" if v is None or (isinstance(v, str) and not v.strip()): return None @@ -168,3 +168,9 @@ FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)] RequiredDate = Annotated[date, BeforeValidator(required_date)] PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)] EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)] + + +def Bounded(kind: type, low: float | None = None, high: float | None = None): # noqa: N802 (used like a type) + """An optional number within [low, high], either bound open when None: a score or a count out of range is a + validation error, not a stored value.""" + return Optional[Annotated[kind, Field(ge=low, le=high)]] diff --git a/webapi/imports/schemas/registry.py b/webapi/imports/schemas/registry.py index a8d546f..b22ca32 100644 --- a/webapi/imports/schemas/registry.py +++ b/webapi/imports/schemas/registry.py @@ -24,18 +24,14 @@ from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_ from persistance.cama import paciente_repository as cama_paciente_repository from persistance.repository import Repository from webapi.imports.schemas.base import ImportSchema -from persistance.tea import antecedentes_maternos_gestacion_repository as tea_antecedentes_maternos_gestacion_repository -from persistance.tea import eeg_estudio_repository as tea_eeg_estudio_repository -from persistance.tea import eeg_segmento_repository as tea_eeg_segmento_repository -from persistance.tea import evaluacion_psicologica_repository as tea_evaluacion_psicologica_repository -from persistance.tea import instrumento_aplicado_repository as tea_instrumento_aplicado_repository -from persistance.tea import nota_medica_repository as tea_nota_medica_repository +from persistance.tea import ados2_repository as tea_ados2_repository +from persistance.tea import eeg_metrica_electrodo_repository as tea_eeg_metrica_electrodo_repository +from persistance.tea import eeg_metrica_repository as tea_eeg_metrica_repository +from persistance.tea import eeg_repository as tea_eeg_repository +from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluacion_neuropediatrica_repository +from persistance.tea import mchat_repository as tea_mchat_repository from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository from persistance.tea import pacientes_repository as tea_pacientes_repository -from persistance.tea import parto_neonatal_repository as tea_parto_neonatal_repository -from persistance.tea import ( - potenciales_evocados_auditivos_repository as tea_potenciales_evocados_auditivos_repository, -) from webapi.imports.schemas.cacu.biometria_hematica import ( BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema, ) @@ -62,22 +58,16 @@ from webapi.imports.schemas.cama.ordenes_estudio import ( OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema, ) from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema -from webapi.imports.schemas.tea.antecedentes_maternos_gestacion import ( - AntecedentesMaternosGestacionImportSchema, -) -from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema -from webapi.imports.schemas.tea.eeg_segmento import EegSegmentoImportSchema -from webapi.imports.schemas.tea.evaluacion_psicologica import EvaluacionPsicologicaImportSchema -from webapi.imports.schemas.tea.instrumento_aplicado import InstrumentoAplicadoImportSchema -from webapi.imports.schemas.tea.nota_medica import NotaMedicaImportSchema as TeaNotaMedicaImportSchema +from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema +from webapi.imports.schemas.tea.eeg import EegImportSchema +from webapi.imports.schemas.tea.eeg_metrica import EegMetricaImportSchema +from webapi.imports.schemas.tea.eeg_metrica_electrodo import EegMetricaElectrodoImportSchema +from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema +from webapi.imports.schemas.tea.mchat import MchatImportSchema from webapi.imports.schemas.tea.ordenes_estudio import ( OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema, ) from webapi.imports.schemas.tea.pacientes import PacientesImportSchema -from webapi.imports.schemas.tea.parto_neonatal import PartoNeonatalImportSchema -from webapi.imports.schemas.tea.potenciales_evocados_auditivos import ( - PotencialesEvocadosAuditivosImportSchema, -) @dataclass(frozen=True) @@ -131,8 +121,7 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = { "cacu.EpisodioClinico": EntitySpec( schema=CacuEpisodioClinicoImportSchema, repository=cacu_episodio_clinico_repository, - # No hospital-visible identifier of its own, like EvaluacionPsicologica - # or PartoNeonatal; a patient can have several episodes. + # No hospital-visible identifier of its own; a patient can have several episodes. conflict_fields=None, ), "cama.Paciente": EntitySpec( @@ -175,48 +164,37 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = { repository=tea_ordenes_estudio_repository, conflict_fields=("ord_id_hospital",), ), - "tea.NotaMedica": EntitySpec( - schema=TeaNotaMedicaImportSchema, - repository=tea_nota_medica_repository, - conflict_fields=("nm_id_hospital",), + "tea.Mchat": EntitySpec( + schema=MchatImportSchema, + repository=tea_mchat_repository, + conflict_fields=("mch_id",), ), - "tea.EvaluacionPsicologica": EntitySpec( - schema=EvaluacionPsicologicaImportSchema, - repository=tea_evaluacion_psicologica_repository, - conflict_fields=None, + "tea.Ados2": EntitySpec( + schema=Ados2ImportSchema, + repository=tea_ados2_repository, + conflict_fields=("ado_id",), ), - "tea.PotencialesEvocadosAuditivos": EntitySpec( - schema=PotencialesEvocadosAuditivosImportSchema, - repository=tea_potenciales_evocados_auditivos_repository, - conflict_fields=None, + "tea.EvaluacionNeuropediatrica": EntitySpec( + schema=EvaluacionNeuropediatricaImportSchema, + repository=tea_evaluacion_neuropediatrica_repository, + conflict_fields=("neu_id",), ), - "tea.EegEstudio": EntitySpec( - schema=EegEstudioImportSchema, - repository=tea_eeg_estudio_repository, - # The EDF file and its scanned report describe the same study; both - # the `edf` connector (from the file's own admin code) and a - # `document` source (read from the report text) populate this field, - # so merge_duplicates/on_conflict=upsert can land them on one row. + "tea.Eeg": EntitySpec( + schema=EegImportSchema, + repository=tea_eeg_repository, + # The EDF file and its report describe the same study; the `edf` connector (from the file's own admin + # code) and a `document` source both fill this field, so merge_duplicates/on_conflict=upsert land them on + # one row. conflict_fields=("eeg_id_registro_laboratorio",), ), - "tea.EegSegmento": EntitySpec( - schema=EegSegmentoImportSchema, - repository=tea_eeg_segmento_repository, - conflict_fields=None, + "tea.EegMetrica": EntitySpec( + schema=EegMetricaImportSchema, + repository=tea_eeg_metrica_repository, + conflict_fields=("met_id",), ), - "tea.InstrumentoAplicado": EntitySpec( - schema=InstrumentoAplicadoImportSchema, - repository=tea_instrumento_aplicado_repository, - conflict_fields=None, - ), - "tea.AntecedentesMaternosGestacion": EntitySpec( - schema=AntecedentesMaternosGestacionImportSchema, - repository=tea_antecedentes_maternos_gestacion_repository, - conflict_fields=None, - ), - "tea.PartoNeonatal": EntitySpec( - schema=PartoNeonatalImportSchema, - repository=tea_parto_neonatal_repository, - conflict_fields=None, + "tea.EegMetricaElectrodo": EntitySpec( + schema=EegMetricaElectrodoImportSchema, + repository=tea_eeg_metrica_electrodo_repository, + conflict_fields=("mel_id",), ), } diff --git a/webapi/imports/schemas/tea/ados2.py b/webapi/imports/schemas/tea/ados2.py new file mode 100644 index 0000000..973ce22 --- /dev/null +++ b/webapi/imports/schemas/tea/ados2.py @@ -0,0 +1,55 @@ +"""Import schema for `core.tea.models.Ados2`: module, algorithm, CSS, classification and the 28 algorithm items. + +The domain subtotals and the total aren't imported: they're sums of the items' algorithm scores.""" +from typing import Optional + +from core.tea.enums import CLASIFICACION_ADOS2_ALIAS, ClasificacionAdos2, ModuloAdos2 +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, FlexDate, OptionalStr, SourceId + +_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2) +_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS) +_ITEM = Bounded(int, 0, 3) + + +class Ados2ImportSchema(ImportSchema): + ado_id: SourceId = None + ado_pac_id: Optional[int] = None + ado_ord_id: OptionalStr = None + ado_fecha: FlexDate = None + ado_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None + ado_algoritmo: OptionalStr = None + ado_css: Bounded(int, 1, 10) = None + ado_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None + + # Social affect (SA) + ado_sa_a2: _ITEM = None + ado_sa_a6: _ITEM = None + ado_sa_a7: _ITEM = None + ado_sa_a8: _ITEM = None + ado_sa_b1: _ITEM = None + ado_sa_b2: _ITEM = None + ado_sa_b3: _ITEM = None + ado_sa_b4: _ITEM = None + ado_sa_b5: _ITEM = None + ado_sa_b6: _ITEM = None + ado_sa_b7: _ITEM = None + ado_sa_b8: _ITEM = None + ado_sa_b9: _ITEM = None + ado_sa_b10: _ITEM = None + ado_sa_b11: _ITEM = None + ado_sa_b12: _ITEM = None + ado_sa_b13: _ITEM = None + ado_sa_b14: _ITEM = None + ado_sa_b15: _ITEM = None + ado_sa_b16b: _ITEM = None + ado_sa_b18: _ITEM = None + + # Restricted and repetitive behaviour (RRB) + ado_rrb_a3: _ITEM = None + ado_rrb_a4: _ITEM = None + ado_rrb_a5: _ITEM = None + ado_rrb_d1: _ITEM = None + ado_rrb_d2: _ITEM = None + ado_rrb_d4: _ITEM = None + ado_rrb_d5: _ITEM = None diff --git a/webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py b/webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py deleted file mode 100644 index 7e34450..0000000 --- a/webapi/imports/schemas/tea/antecedentes_maternos_gestacion.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Import schema for `core.tea.models.AntecedentesMaternosGestacion`. All fields -optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - CategoriaPesoMaterno, - FuenteAntecedenteMaterno, - TipoEmbarazo, - TrastornoHipertensivoGestacion, - VolumenLiquidoAmniotico, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr - -_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno) -_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno) -_TIPO_EMBARAZO_CATALOG = Catalog(TipoEmbarazo) -_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG = Catalog(TrastornoHipertensivoGestacion) -_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico) - - -class AntecedentesMaternosGestacionImportSchema(ImportSchema): - amg_pac_id: Optional[int] = None - amg_id_madre_seudonimo: OptionalStr = None - amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None - amg_flag_vinculo_verificado: Optional[int] = None - amg_imc_pregestacional: Optional[float] = None - amg_categoria_peso_materno: CatalogValue(_CATEGORIA_PESO_MATERNO_CATALOG) = None - amg_tabaquismo_gestacion: Optional[int] = None - amg_acido_folico_preconcepcional: Optional[int] = None - amg_intervalo_intergenesico_meses: Optional[int] = None - amg_antecedente_aborto: Optional[int] = None - amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None - amg_infeccion_gestacion: Optional[int] = None - amg_infeccion_tipo: OptionalStr = None - amg_infeccion_hospitalizacion: Optional[int] = None - amg_diabetes_gestacional: Optional[int] = None - amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None - amg_hipotiroidismo: Optional[int] = None - amg_hipertiroidismo: Optional[int] = None - amg_incompatibilidad_rh: Optional[int] = None - amg_crisis_convulsivas: Optional[int] = None - amg_proceso_proinflamatorio: Optional[int] = None - amg_enfermedad_autoinmune: Optional[int] = None - amg_migrana: Optional[int] = None - amg_asma: Optional[int] = None - amg_hipoxia_materna: Optional[int] = None - amg_estres_agudo: Optional[int] = None - amg_trastorno_neurologico: Optional[int] = None - amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None - amg_medicamentos_gestacion: OptionalStr = None - amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None - amg_observaciones: OptionalStr = None - amg_ocr_confianza: Optional[float] = None - amg_nlp_version: OptionalStr = None diff --git a/webapi/imports/schemas/tea/eeg.py b/webapi/imports/schemas/tea/eeg.py new file mode 100644 index 0000000..ddcaf12 --- /dev/null +++ b/webapi/imports/schemas/tea/eeg.py @@ -0,0 +1,26 @@ +"""Import schema for `core.tea.models.Eeg`: the study, its EDF and what the EEG analysis writes back (sleep, +channels, duration and the five quality criteria).""" +from typing import Optional + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Bounded, EdfFile, FlexDate, OptionalStr, SourceId + +_CHANNELS = Bounded(int, 0, None) + + +class EegImportSchema(ImportSchema): + # The source's own id, kept so the metrics that reference it still point at this record. + eeg_id: SourceId = None + eeg_pac_id: Optional[int] = None + eeg_ord_id: OptionalStr = None + eeg_id_registro_laboratorio: OptionalStr = None + eeg_fecha_estudio: FlexDate = None + eeg_con_sueno: Bounded(int, 0, 1) = None + eeg_canales: Bounded(int, 1, 256) = None + eeg_duracion_min: Bounded(float, 0, None) = None + eeg_canales_amplitud: _CHANNELS = None + eeg_canales_alta_frecuencia: _CHANNELS = None + eeg_canales_correlacion: _CHANNELS = None + eeg_canales_sin_senal: _CHANNELS = None + eeg_ruido_linea_db: Bounded(float, 0, None) = None + eeg_estudio: EdfFile = None diff --git a/webapi/imports/schemas/tea/eeg_estudio.py b/webapi/imports/schemas/tea/eeg_estudio.py deleted file mode 100644 index 26e621e..0000000 --- a/webapi/imports/schemas/tea/eeg_estudio.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Import schema for `core.tea.models.EegEstudio`. All fields optional, like TEA's -Core; system-managed `eeg_created_at`/`eeg_updated_at` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - CalidadTecnicaEeg, - ConclusionEeg, - DistribucionAnormalidad, - EstadoRegistroEeg, - FuenteInterpretacionEeg, - Lentificacion, - RespuestaFotoestimulacion, - Simetria, - TipoGrafoelemento, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId - -_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg) -_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg) -_CALIDAD_TECNICA_EEG_CATALOG = Catalog(CalidadTecnicaEeg) -_SIMETRIA_CATALOG = Catalog(Simetria) -_TIPO_GRAFOELEMENTO_CATALOG = Catalog(TipoGrafoelemento) -_DISTRIBUCION_ANORMALIDAD_CATALOG = Catalog(DistribucionAnormalidad) -_LENTIFICACION_CATALOG = Catalog(Lentificacion) -_RESPUESTA_FOTOESTIMULACION_CATALOG = Catalog(RespuestaFotoestimulacion) -_CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg) - - -class EegEstudioImportSchema(ImportSchema): - # The source's own id, kept so rows that reference it by id still point at this record. - eeg_id: SourceId = None - eeg_ord_id: OptionalStr = None - eeg_pac_id: Optional[int] = None - eeg_reporte_disponible: Optional[int] = None - eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None - eeg_fecha_nacimiento_archivo: FlexDate = None - eeg_edad_meses: Optional[float] = None - eeg_fecha_estudio: FlexDate = None - eeg_fecha_reporte: FlexDate = None - eeg_dias_respuesta: Optional[int] = None - eeg_medico_interpreta: OptionalStr = None - eeg_estado_registro: CatalogValue(_ESTADO_REGISTRO_EEG_CATALOG) = None - eeg_privacion_sueno: Optional[int] = None - eeg_sedacion: Optional[int] = None - eeg_sedacion_farmaco: OptionalStr = None - eeg_duracion_min: Optional[float] = None - eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None - eeg_descripcion_senal: OptionalStr = None - eeg_ritmo_base_frecuencia: Optional[float] = None - eeg_ritmo_base_amplitud: Optional[int] = None - eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None - eeg_anormalidad_presente: Optional[int] = None - eeg_actividad_epileptiforme: Optional[int] = None - eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None - eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None - eeg_localizacion: OptionalStr = None - eeg_activacion_sueno: Optional[int] = None - eeg_lentificacion: CatalogValue(_LENTIFICACION_CATALOG) = None - eeg_crisis_registradas: Optional[int] = None - eeg_respuesta_fotoestimulacion: CatalogValue(_RESPUESTA_FOTOESTIMULACION_CATALOG) = None - eeg_conclusion_texto: OptionalStr = None - eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None - eeg_id_registro_laboratorio: OptionalStr = None - eeg_pdf_ruta: OptionalStr = None - eeg_ocr_confianza: Optional[float] = None - eeg_nlp_version: OptionalStr = None - eeg_utilizable: Optional[int] = None - eeg_estudio: EdfFile = None diff --git a/webapi/imports/schemas/tea/eeg_metrica.py b/webapi/imports/schemas/tea/eeg_metrica.py new file mode 100644 index 0000000..95b798c --- /dev/null +++ b/webapi/imports/schemas/tea/eeg_metrica.py @@ -0,0 +1,16 @@ +"""Import schema for `core.tea.models.EegMetrica`: a metric the EEG analysis measured. A blank value is a metric +that can't be evaluated.""" +from typing import Optional + +from core.tea.enums import MetricaEeg +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr, SourceId + +_METRICA_CATALOG = Catalog(MetricaEeg) + + +class EegMetricaImportSchema(ImportSchema): + met_id: SourceId = None + met_eeg_id: OptionalStr = None + met_codigo: CatalogValue(_METRICA_CATALOG) = None + met_valor: Optional[float] = None diff --git a/webapi/imports/schemas/tea/eeg_metrica_electrodo.py b/webapi/imports/schemas/tea/eeg_metrica_electrodo.py new file mode 100644 index 0000000..9a91ee9 --- /dev/null +++ b/webapi/imports/schemas/tea/eeg_metrica_electrodo.py @@ -0,0 +1,12 @@ +"""Import schema for `core.tea.models.EegMetricaElectrodo`: a metric's z-score at one 10-20 electrode.""" +from typing import Optional + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import OptionalStr, SourceId + + +class EegMetricaElectrodoImportSchema(ImportSchema): + mel_id: SourceId = None + mel_met_id: OptionalStr = None + mel_electrodo: OptionalStr = None + mel_valor: Optional[float] = None diff --git a/webapi/imports/schemas/tea/eeg_segmento.py b/webapi/imports/schemas/tea/eeg_segmento.py deleted file mode 100644 index ee93850..0000000 --- a/webapi/imports/schemas/tea/eeg_segmento.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Import schema for `core.tea.models.EegSegmento`. All fields optional, like -TEA's Core.""" -from typing import Optional - -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import OptionalStr - - -class EegSegmentoImportSchema(ImportSchema): - seg_eeg_id: OptionalStr = None - seg_estado: OptionalStr = None - seg_inicio_s: Optional[float] = None - seg_fin_s: Optional[float] = None - seg_duracion_s: Optional[float] = None - seg_fuente: OptionalStr = None - seg_frecuencia_flash_hz: Optional[float] = None - seg_n_destellos: Optional[int] = None - seg_cobertura: Optional[float] = None - seg_rms_uv: Optional[float] = None - seg_emg: Optional[float] = None - seg_p2p_max_uv: Optional[float] = None diff --git a/webapi/imports/schemas/tea/evaluacion_neuropediatrica.py b/webapi/imports/schemas/tea/evaluacion_neuropediatrica.py new file mode 100644 index 0000000..ed5cf49 --- /dev/null +++ b/webapi/imports/schemas/tea/evaluacion_neuropediatrica.py @@ -0,0 +1,27 @@ +"""Import schema for `core.tea.models.EvaluacionNeuropediatrica`: the note and its ICD-10 diagnosis.""" +from typing import Annotated, Optional + +from pydantic import BeforeValidator, StringConstraints + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import FlexDate, OptionalStr, SourceId, optional_str + + +def _upper(v): + v = optional_str(v) + return v.strip().upper() if isinstance(v, str) else v + + +# A letter, two digits and optionally a dot with one or two more (F84.0); the dot may be missing (F840). +_CIE10 = Annotated[ + Optional[Annotated[str, StringConstraints(pattern=r"^[A-Z][0-9]{2}(\.?[0-9]{1,2})?$")]], + BeforeValidator(_upper), +] + + +class EvaluacionNeuropediatricaImportSchema(ImportSchema): + neu_id: SourceId = None + neu_pac_id: Optional[int] = None + neu_ord_id: OptionalStr = None + neu_fecha: FlexDate = None + neu_cie_codigo: _CIE10 = None diff --git a/webapi/imports/schemas/tea/evaluacion_psicologica.py b/webapi/imports/schemas/tea/evaluacion_psicologica.py deleted file mode 100644 index 0cfeb9b..0000000 --- a/webapi/imports/schemas/tea/evaluacion_psicologica.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Import schema for `core.tea.models.EvaluacionPsicologica`, including the 28 -ADOS-2 item columns. All fields optional, like TEA's Core; system-managed `psi_created_at`/`psi_updated_at` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - ClasificacionAdos2, - InstrumentoTamizaje, - ModuloAdos2, - NivelRiesgoTamizaje, - VentanaMadurativa, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId - -_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa) -_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje) -_NIVEL_RIESGO_TAMIZAJE_CATALOG = Catalog(NivelRiesgoTamizaje) -_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2) -_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2) - - -class EvaluacionPsicologicaImportSchema(ImportSchema): - # The source's own id, kept so rows that reference it by id still point at this record. - psi_id: SourceId = None - psi_ord_id: OptionalStr = None - psi_pac_id: Optional[int] = None - psi_fecha_entrevista_inicial: FlexDate = None - psi_fecha_ados2: FlexDate = None - psi_fecha_evaluacion: FlexDate = None - psi_psicologo: OptionalStr = None - psi_edad_meses: Optional[float] = None - psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None - psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None - psi_tamizaje_puntaje: Optional[int] = None - psi_tamizaje_riesgo: CatalogValue(_NIVEL_RIESGO_TAMIZAJE_CATALOG) = None - psi_ados2_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None - - # Items ADOS-2, dominio SA (Interaccion Social Reciproca) - psi_ados2_sa_a2: Optional[int] = None - psi_ados2_sa_a6: Optional[int] = None - psi_ados2_sa_a7: Optional[int] = None - psi_ados2_sa_a8: Optional[int] = None - psi_ados2_sa_b1: Optional[int] = None - psi_ados2_sa_b2: Optional[int] = None - psi_ados2_sa_b3: Optional[int] = None - psi_ados2_sa_b4: Optional[int] = None - psi_ados2_sa_b5: Optional[int] = None - psi_ados2_sa_b6: Optional[int] = None - psi_ados2_sa_b7: Optional[int] = None - psi_ados2_sa_b8: Optional[int] = None - psi_ados2_sa_b9: Optional[int] = None - psi_ados2_sa_b10: Optional[int] = None - psi_ados2_sa_b11: Optional[int] = None - psi_ados2_sa_b12: Optional[int] = None - psi_ados2_sa_b13: Optional[int] = None - psi_ados2_sa_b14: Optional[int] = None - psi_ados2_sa_b15: Optional[int] = None - psi_ados2_sa_b16b: Optional[int] = None - psi_ados2_sa_b18: Optional[int] = None - - # Items ADOS-2, dominio RRB (Conductas Restringidas y Repetitivas) - psi_ados2_rrb_a3: Optional[int] = None - psi_ados2_rrb_a4: Optional[int] = None - psi_ados2_rrb_a5: Optional[int] = None - psi_ados2_rrb_d1: Optional[int] = None - psi_ados2_rrb_d2: Optional[int] = None - psi_ados2_rrb_d4: Optional[int] = None - psi_ados2_rrb_d5: Optional[int] = None - - psi_ados2_sa: Optional[int] = None - psi_ados2_rrb: Optional[int] = None - psi_ados2_total: Optional[int] = None - psi_ados2_css: Optional[int] = None - psi_ados2_css_sa: Optional[int] = None - psi_ados2_css_rrb: Optional[int] = None - psi_ados2_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None - psi_rgd: Optional[int] = None - psi_cociente_desarrollo: Optional[float] = None - psi_css_umbral_aplicado: Optional[int] = None - psi_caso_confirmado: Optional[int] = None - psi_cars_total: Optional[float] = None - psi_otros_instrumentos: OptionalStr = None - psi_regresion_desarrollo: Optional[int] = None - psi_diagnostico_texto: OptionalStr = None - psi_ocr_confianza: Optional[float] = None - psi_nlp_version: OptionalStr = None diff --git a/webapi/imports/schemas/tea/instrumento_aplicado.py b/webapi/imports/schemas/tea/instrumento_aplicado.py deleted file mode 100644 index 1025946..0000000 --- a/webapi/imports/schemas/tea/instrumento_aplicado.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields -optional, like TEA's Core.""" - -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import OptionalStr - - -class InstrumentoAplicadoImportSchema(ImportSchema): - ins_psi_id: OptionalStr = None - ins_instrumento: OptionalStr = None - ins_informante: OptionalStr = None - ins_area: OptionalStr = None - ins_interpretacion: OptionalStr = None diff --git a/webapi/imports/schemas/tea/mchat.py b/webapi/imports/schemas/tea/mchat.py new file mode 100644 index 0000000..444fd0c --- /dev/null +++ b/webapi/imports/schemas/tea/mchat.py @@ -0,0 +1,13 @@ +"""Import schema for `core.tea.models.Mchat`: one M-CHAT-R/F and its total score.""" +from typing import Optional + +from webapi.imports.schemas.base import ImportSchema +from webapi.imports.schemas.coercion import Bounded, FlexDate, OptionalStr, SourceId + + +class MchatImportSchema(ImportSchema): + mch_id: SourceId = None + mch_pac_id: Optional[int] = None + mch_ord_id: OptionalStr = None + mch_fecha: FlexDate = None + mch_puntaje: Bounded(int, 0, 20) = None diff --git a/webapi/imports/schemas/tea/nota_medica.py b/webapi/imports/schemas/tea/nota_medica.py deleted file mode 100644 index 5e06694..0000000 --- a/webapi/imports/schemas/tea/nota_medica.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's -Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded.""" -from typing import Optional - -from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr - -_TIPO_NOTA_CATALOG = Catalog(TipoNota) -_ESPECIALIDAD_CATALOG = Catalog(Especialidad) -_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa) -_PRONOSTICO_CATALOG = Catalog(Pronostico) - - -class NotaMedicaImportSchema(ImportSchema): - nm_pac_id: Optional[int] = None - nm_id_hospital: OptionalStr = None - nm_nota_previa_id: OptionalStr = None - nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None - nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None - nm_fecha: FlexDate = None - nm_edad_meses: Optional[float] = None - nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None - nm_medico_tratante: OptionalStr = None - nm_motivo_consulta: OptionalStr = None - nm_interrogatorio: OptionalStr = None - nm_regresion_referida: Optional[int] = None - nm_antecedente_familiar_tea: Optional[int] = None - nm_perimetro_cefalico: Optional[float] = None - nm_diagnostico_texto: OptionalStr = None - nm_cie_codigo: OptionalStr = None - nm_cie_descripcion: OptionalStr = None - nm_tratamiento_texto: OptionalStr = None - nm_receta: OptionalStr = None - nm_plan_estudios: OptionalStr = None - nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None - nm_observaciones: OptionalStr = None - nm_masa_corporal: Optional[float] = None - nm_talla: Optional[float] = None - nm_imc_visita: Optional[float] = None - nm_frecuencia_cardiaca: Optional[int] = None - nm_frecuencia_respiratoria: Optional[int] = None - nm_presion_arterial_sistolica: Optional[int] = None - nm_presion_arterial_diastolica: Optional[int] = None - nm_temperatura: Optional[float] = None - nm_pdf_ruta: OptionalStr = None diff --git a/webapi/imports/schemas/tea/ordenes_estudio.py b/webapi/imports/schemas/tea/ordenes_estudio.py index cbe6714..72c18ae 100644 --- a/webapi/imports/schemas/tea/ordenes_estudio.py +++ b/webapi/imports/schemas/tea/ordenes_estudio.py @@ -1,37 +1,17 @@ -"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like -TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded.""" +"""Import schema for `core.tea.models.OrdenesEstudio`: the order of an ADOS-2, a neuropediatrics note or an EEG.""" from typing import Optional -from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa +from core.tea.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio from webapi.imports.schemas.base import ImportSchema from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId -_ESPECIALIDAD_CATALOG = Catalog(Especialidad) _TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS) -_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio) -_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa) class OrdenesEstudioImportSchema(ImportSchema): # The source's own id, kept so rows that reference it by id still point at this record. ord_id: SourceId = None ord_pac_id: Optional[int] = None - ord_nota_medica_id: OptionalStr = None ord_id_hospital: OptionalStr = None - ord_fecha: FlexDate = None - ord_medico_solicitante: OptionalStr = None - ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None - ord_diagnostico_asignado: OptionalStr = None - ord_cie_asignado: OptionalStr = None - ord_dias_vigencia: Optional[int] = None - ord_fecha_vencimiento: FlexDate = None ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None - ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None - ord_fecha_realizacion: FlexDate = None - ord_fecha_resultado: FlexDate = None - ord_dias_espera: Optional[int] = None - ord_proveedor: OptionalStr = None - ord_edad_meses: Optional[float] = None - ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None - ord_pdf_ruta: OptionalStr = None - ord_observaciones: OptionalStr = None + ord_fecha: FlexDate = None diff --git a/webapi/imports/schemas/tea/pacientes.py b/webapi/imports/schemas/tea/pacientes.py index 5b899d0..c4c110c 100644 --- a/webapi/imports/schemas/tea/pacientes.py +++ b/webapi/imports/schemas/tea/pacientes.py @@ -1,24 +1,14 @@ -"""Import schema for `core.tea.models.Pacientes`. All fields optional, like TEA's -Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are excluded. +"""Import schema for `core.tea.models.Pacientes`. -`pac_id` is importable: every other TEA table references the patient by the -source system's integer id, so it has to be kept, not renumbered.""" +`pac_id` is importable: every other TEA table references the patient by the source system's integer id, so it is +kept, not renumbered.""" from typing import Optional -from core.tea.enums import Parentesco, SexoBiologico from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr - -_SEXO_CATALOG = Catalog(SexoBiologico) -_PARENTESCO_CATALOG = Catalog(Parentesco) +from webapi.imports.schemas.coercion import FlexDate, OptionalStr class PacientesImportSchema(ImportSchema): pac_id: Optional[int] = None pac_id_hospital: OptionalStr = None - pac_id_titular: OptionalStr = None - pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None pac_fecha_nacimiento: FlexDate = None - pac_sexo: CatalogValue(_SEXO_CATALOG) = None - pac_codigo_postal_vigente: OptionalStr = None - pac_dependencia: OptionalStr = None diff --git a/webapi/imports/schemas/tea/parto_neonatal.py b/webapi/imports/schemas/tea/parto_neonatal.py deleted file mode 100644 index 29274ec..0000000 --- a/webapi/imports/schemas/tea/parto_neonatal.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Import schema for `core.tea.models.PartoNeonatal`. All fields optional, like -TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded.""" -from typing import Optional - -from core.tea.enums import ( - ClasificacionEdadGestacional, - ComplicacionIntraparto, - FuenteAntecedenteNeonatal, - TamanoParaEdadGestacional, - TipoParto, -) -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr - -_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal) -_TIPO_PARTO_CATALOG = Catalog(TipoParto) -_COMPLICACION_INTRAPARTO_CATALOG = Catalog(ComplicacionIntraparto) -_CLASIFICACION_EDAD_GESTACIONAL_CATALOG = Catalog(ClasificacionEdadGestacional) -_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG = Catalog(TamanoParaEdadGestacional) - - -class PartoNeonatalImportSchema(ImportSchema): - pnn_pac_id: Optional[int] = None - pnn_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_NEONATAL_CATALOG) = None - pnn_tipo_parto: CatalogValue(_TIPO_PARTO_CATALOG) = None - pnn_complicaciones_intraparto: Optional[int] = None - pnn_complicacion_tipo: CatalogValue(_COMPLICACION_INTRAPARTO_CATALOG) = None - pnn_peso_nacer_g: Optional[int] = None - pnn_talla_nacer_cm: Optional[float] = None - pnn_perimetro_cefalico_nacer_cm: Optional[float] = None - pnn_edad_gestacional_sem: Optional[float] = None - pnn_clasificacion_eg: CatalogValue(_CLASIFICACION_EDAD_GESTACIONAL_CATALOG) = None - pnn_tamano_para_eg: CatalogValue(_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG) = None - pnn_peso_nacer_zscore: Optional[float] = None - pnn_apgar_1min: Optional[int] = None - pnn_apgar_5min: Optional[int] = None - pnn_ingreso_ucin: Optional[int] = None - pnn_dias_ucin: Optional[int] = None - pnn_encefalopatia_hipoxico_isquemica: Optional[int] = None - pnn_hipotermia_nacer: Optional[int] = None - pnn_hiperbilirrubinemia: Optional[int] = None - pnn_fototerapia: Optional[int] = None - pnn_hipoglucemia_neonatal: Optional[int] = None - pnn_anoxia: Optional[int] = None - pnn_sindrome_congenito: Optional[int] = None - pnn_sindrome_congenito_desc: OptionalStr = None - pnn_flag_riesgo_neonatal: Optional[int] = None - pnn_observaciones: OptionalStr = None - pnn_ocr_confianza: Optional[float] = None - pnn_nlp_version: OptionalStr = None diff --git a/webapi/imports/schemas/tea/potenciales_evocados_auditivos.py b/webapi/imports/schemas/tea/potenciales_evocados_auditivos.py deleted file mode 100644 index e71e09e..0000000 --- a/webapi/imports/schemas/tea/potenciales_evocados_auditivos.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields -optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded.""" -from typing import Optional - -from core.tea.enums import GradoHipoacusia -from webapi.imports.schemas.base import ImportSchema -from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr - -_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia) - - -class PotencialesEvocadosAuditivosImportSchema(ImportSchema): - pea_ord_id: OptionalStr = None - pea_pac_id: Optional[int] = None - pea_fecha_estudio: FlexDate = None - pea_medico_interpreta: OptionalStr = None - pea_umbral_od: Optional[int] = None - pea_umbral_oi: Optional[int] = None - pea_latencia_v_od: Optional[float] = None - pea_latencia_v_oi: Optional[float] = None - pea_interpico_i_v_od: Optional[float] = None - pea_interpico_i_v_oi: Optional[float] = None - pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None - pea_conclusion_texto: OptionalStr = None - pea_flag_diferencial_auditivo: Optional[int] = None - pea_ocr_confianza: Optional[float] = None diff --git a/webapi/metrics.py b/webapi/metrics.py index 23b3574..7baf63c 100644 --- a/webapi/metrics.py +++ b/webapi/metrics.py @@ -30,6 +30,7 @@ from sqlalchemy import ( case, cast, column, + desc, distinct, func, literal, @@ -37,6 +38,7 @@ from sqlalchemy import ( select, table, text, + true, ) AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read @@ -45,6 +47,8 @@ NO_DATA = "sin_dato" AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo" TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" OF_THE_CHOSEN = "del_elegido" +COLUMN = "columna" +STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo" class UndecidedRule(ValueError): @@ -56,7 +60,8 @@ class Population: """A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates. `dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the - dates the knowledge cut-off applies to. + dates the knowledge cut-off applies to. `at_end`, with a status at the period's end: dates that must have (or must + not have) been reached by the period's end, each with when it became known. """ metric: str @@ -65,6 +70,53 @@ class Population: codes: tuple[str, ...] dated_at: tuple[str, ...] known_at: tuple[str, ...] + at_end: tuple["ReachedByEnd", ...] = () + + +@dataclasses.dataclass(frozen=True) +class ReachedByEnd: + """A date reached by the period's end (`reached`) or not: dated before the period's end and the event cut-off, + and known by the knowledge cut-off.""" + + date: str + known_at: str | None + reached: bool + + +@dataclasses.dataclass(frozen=True) +class StatusAtEnd: + """Who a period counts and with which row: every unit that entered (`entry`) on or before the period's end and + hadn't left (`exit`, known at `exit_known`) before its start, whether or not it has a fact in the period. Each + unit is counted with its row of highest `order` dated on or before the period's end (its status then) and known + by the cut-offs (`known_at`). With no `order`, the model has one row per unit.""" + + entry: str + exit: str + exit_known: str | None + order: str | None + known_at: tuple[str, ...] + + @classmethod + def of(cls, spec: dict | None) -> "StatusAtEnd | None": + if spec is None: + return None + if spec["tipo"] != STATUS_AT_PERIOD_END: + raise NotImplementedError(f"populations of kind {spec['tipo']!r} aren't answered") + return cls(spec["ingreso"], spec["salida"], spec.get("salida_conocida_en"), spec.get("orden"), + tuple(spec.get("conocida_en", ()))) + + def columns(self) -> set[str]: + return {self.entry, self.exit, *((self.exit_known,) if self.exit_known else ()), + *((self.order,) if self.order else ()), *self.known_at} + + +@dataclasses.dataclass(frozen=True) +class Group: + """One of several groups of a measure: its numerator is the measure's own with this filter instead.""" + + name: str + label: str + filter_sql: str @dataclasses.dataclass(frozen=True) @@ -76,7 +128,8 @@ class Stratum: `fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a timeline `tipo` to whether there was one; - - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category. + - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category; + - `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null. """ name: str @@ -89,7 +142,7 @@ class Stratum: @classmethod def of(cls, name: str, spec: dict) -> "Stratum": - if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN): + if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN, COLUMN): raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered") return cls(name, spec["tipo"], spec) @@ -112,11 +165,26 @@ class MeasureDefinition: rules: dict[str, str] strata: tuple[Stratum, ...] improvement_notation: str | None = None + population: StatusAtEnd | None = None + groups: tuple[Group, ...] = () + exclusion: Population | None = None + meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False) @property def measure_id(self) -> str: return self.url.rsplit("/", 1)[-1] + def for_group(self, group: Group) -> "MeasureDefinition": + """The definition as one of its groups: the denominator's units, filtered by the group.""" + numerator = dataclasses.replace(self.denominator, metric=f"{self.numerator.metric}:{group.name}", + codes=self.numerator.codes, filter_sql=_both(self.denominator.filter_sql, + group.filter_sql)) + return dataclasses.replace(self, numerator=numerator, group=group.name, groups=(), strata=(), exclusion=None) + + +def _both(first: str | None, second: str | None) -> str | None: + return " and ".join(f"({c})" for c in (first, second) if c) or None + def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]: """The ratio metrics of the manifest that declare a `measure_url`, by that url.""" @@ -143,10 +211,20 @@ def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]: group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})), strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()), improvement_notation=meta.get("improvement_notation"), + population=StatusAtEnd.of(meta.get("poblacion")), + groups=tuple(Group(g["grupo"], g.get("etiqueta", g["grupo"]), _unraw(g["filtro"])) + for g in meta.get("grupos", ())), + exclusion=_population(metrics[meta["exclusion"]], model) if "exclusion" in meta else None, + meta=meta, ) return definitions +def _unraw(template: str) -> str: + """A `meta` template as written, without the `{% raw %}` that keeps dbt from rendering it.""" + return template.replace("{% raw %}", "").replace("{% endraw %}", "") + + def _semantic_model_of(metric: dict, semantic: dict) -> dict: measure = metric["type_params"]["measure"]["name"] for model in semantic.values(): @@ -167,6 +245,8 @@ def _population(metric: dict, model: dict) -> Population: filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None, codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())), known_at=tuple(meta.get("conocida_en", ())), + at_end=tuple(ReachedByEnd(a["fecha"], a.get("conocida_en"), bool(a.get("alcanzada", True))) + for a in meta.get("al_fin", ())), ) @@ -195,12 +275,20 @@ class MeasureQueries: names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr} # When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in. known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at} + known |= {definition.dimensions[a.known_at] for p in (definition.numerator, definition.denominator) + for a in p.at_end if a.known_at} for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)): known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())} + self.status = getattr(definition, "population", None) + if self.status is not None: + names |= {definition.dimensions[n] for n in self.status.columns()} + known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n} self.events = table(definition.relation, *( column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) if name.isidentifier())) self.periods = period_table + if self.status is not None: + self.events = self._status_rows() self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio") self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD)) @@ -223,9 +311,56 @@ class MeasureQueries: if self.q.knowledge_cutoff is not None: conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at] conditions += [self._column(name).is_not(None) for name in population.known_at] + for date in population.at_end: + reached = self._reached_by_end(date.date, date.known_at) + conditions.append(reached if date.reached else case((reached, 0), else_=1) == 1) return and_(*conditions) if conditions else None + def _reached_by_end(self, date: str, known_at: str | None): + """The date is reached by the period's end: dated before it and by the event cut-off, known by the + knowledge cut-off. Only with a status at the period's end, whose rows carry the period's bounds.""" + if self.status is None: + raise ValueError(f"{self.d.url}: `al_fin` needs a population at the period's end") + value = self._column(date) + conditions = [value.is_not(None), value < self.events.c.periodo_fin] + if self.q.event_cutoff is not None: + conditions.append(value <= self.q.event_cutoff.isoformat()) + if known_at is not None and self.q.knowledge_cutoff is not None: + conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff] + return and_(*conditions) + + def _status_rows(self): + """Each unit the period counts, with its row of highest order: a subquery with the model's name, so the + rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds. + + A unit is in when it entered by the period's end and hadn't left before its start; a later exit, or one not + yet dated or known by the cut-offs, doesn't count. Its rows are those dated before the period's end and by + the event cut-off, and known by the knowledge cut-off. + """ + rule, base, p = self.status, self.events, self.periods.c + col = lambda name: base.c[self.d.dimensions[name]] # noqa: E731 + when, unit = base.c[self.d.time_dimension], base.c[self.d.numerator.measure_expr] + conditions = [p.periodo_id == self.q.period_id, when.is_not(None), when < p.fin, col(rule.entry) < p.fin] + left = [col(rule.exit).is_not(None), col(rule.exit) < p.inicio] + if self.q.event_cutoff is not None: + conditions.append(when <= self.q.event_cutoff.isoformat()) + left.append(col(rule.exit) <= self.q.event_cutoff.isoformat()) + if self.q.knowledge_cutoff is not None: + conditions += [col(n) <= self.q.knowledge_cutoff for n in rule.known_at] + if rule.exit_known: + left += [col(rule.exit_known).is_not(None), col(rule.exit_known) <= self.q.knowledge_cutoff] + conditions.append(case((and_(*left), 1), else_=0) == 0) + order = [desc(col(rule.order))] if rule.order else [desc(when)] + ranked = (select(*base.c, p.periodo_id.label("periodo_id"), p.inicio.label("periodo_inicio"), + p.fin.label("periodo_fin"), + func.row_number().over(partition_by=unit, order_by=order).label("lugar_al_fin")) + .select_from(base.join(self.periods, true())).where(*conditions).subquery("al_fin_del_periodo")) + return (select(*(c for c in ranked.c if c.name != "lugar_al_fin")).where(ranked.c.lugar_al_fin == 1) + .subquery(self.d.relation)) + def _in_question(self): + if self.status is not None: + return self.events.c.periodo_id == self.q.period_id when, p = self.events.c[self.d.time_dimension], self.periods.c conditions = [p.periodo_id == self.q.period_id] if self.q.event_cutoff is not None: @@ -233,12 +368,16 @@ class MeasureQueries: return and_(*conditions) def _from(self, *, with_strata: bool): + if self.status is not None: + if with_strata and any(s.kind not in (COLUMN, OF_THE_CHOSEN) for s in self.d.strata): + raise NotImplementedError(f"{self.d.url}: a status at the period's end takes column strata only") + return self.events when, p = self.events.c[self.d.time_dimension], self.periods.c joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin)) if not with_strata: return joined for stratum in self.d.strata: - if stratum.kind == OF_THE_CHOSEN: + if stratum.kind in (OF_THE_CHOSEN, COLUMN): continue if stratum.kind == AGE_AT_PERIOD_START: joined = (joined @@ -283,6 +422,8 @@ class MeasureQueries: return func.coalesce(self.age_groups.c.etiqueta, NO_DATA) if stratum.kind == OF_THE_CHOSEN: return self._column(stratum.spec["valor"]) + if stratum.kind == COLUMN: + return func.coalesce(self._column(stratum.spec["columna"]), NO_DATA) had = self._timeline(stratum).c def holds(alternative: dict): @@ -306,9 +447,15 @@ class MeasureQueries: return (select(value, *self._cells()).select_from(self._from(with_strata=True)) .where(self._in_question()).group_by(value)) + def excluded(self) -> Select: + """The units of the measure's exclusion (`meta.exclusion`): in the period, but out of its denominator.""" + unit, condition = self.events.c[self.d.exclusion.measure_expr], self._filter(self.d.exclusion) + counted = unit if condition is None else case((condition, unit)) + return select(func.count(distinct(counted))).select_from(self._from(with_strata=False)).where(self._in_question()) + def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]: """What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum.""" - for population in (self.d.denominator, self.d.numerator): + for population in (self.d.denominator, self.d.numerator, *((self.d.exclusion,) if self.d.exclusion else ())): unit = self.events.c[population.measure_expr] condition = self._filter(population) where = self._in_question() if condition is None else and_(self._in_question(), condition) @@ -372,6 +519,8 @@ class Answer: total: Counts strata: dict[str, dict[str, Counts]] stored_before: bool + groups: dict[str, Counts] = dataclasses.field(default_factory=dict) # by group, for a measure with several + excluded: int | None = None # the units of its exclusion, when it has one @property def numerator(self) -> int: @@ -397,7 +546,8 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p key, key_sha = key_of(definition, question, values) stored = history.find(definition.url, key_sha) if stored is not None: - return _from_counts(definition, stored, history.counts(stored)) + return _from_counts(definition, stored, history.counts(stored), + history.group_counts(stored) if definition.groups else {}) period = periods.get(question.period_id) if period is None: @@ -408,6 +558,13 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p for stratum in definition.strata: _, cells = queries.rows(sql.counts_by_stratum(stratum)) strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells} + excluded = queries.rows(sql.excluded())[1][0][0] if definition.exclusion else None + group_sql, groups = [], {} + for group in definition.groups: + g = MeasureQueries(definition.for_group(group), question, values, periods.model.__table__) + _, ((n, d),) = queries.rows(g.counts()) + groups[group.name] = Counts(n, d) + group_sql.append(g) models = import_module(f"core.{project}.indicadores.models") (any_rule,) = parameters.list(limit=1) report = models.MeasureReport( @@ -418,15 +575,21 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc), agregacion_version=AGGREGATION_VERSION, huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted( - (s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode() + (s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items()), + excluded, sorted((g, c.numerator, c.denominator) for g, c in groups.items())]).encode() ).hexdigest(), ) - report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad, - models.MeasureReportUnidadEstrato)) - return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False) + + def rows(rid): + for queries_of in (sql, *group_sql): + yield from queries_of.rows(rid, models.MeasureReportUnidad, models.MeasureReportUnidadEstrato) + + report_id = history.record(report, rows) + return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False, groups=groups, + excluded=excluded) -def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer: +def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by_group: dict | None = None) -> Answer: numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0], definition.denominator.codes[0])) cells: dict[tuple[str, str], list[int]] = {} @@ -440,7 +603,19 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> for (stratum, value), (n, d) in cells.items(): if stratum != TOTAL: strata.setdefault(stratum, {})[value] = Counts(n, d) - return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True) + excluded = None + if definition.exclusion is not None: + code = f"{definition.measure_id}.{definition.exclusion.codes[0]}" + excluded = sum(n for (stratum, _, resultado, _), n in counts.items() if stratum == TOTAL and resultado == code) + groups = {} + if definition.groups: + by_group = by_group or {} + groups = {g.name: Counts(by_group.get((g.name, numerator), 0), by_group.get((g.name, denominator), 0)) + for g in definition.groups} + totals = Counts(by_group.get((definition.group, numerator), 0), by_group.get((definition.group, denominator), 0)) + else: + totals = Counts(*cells.get((TOTAL, TOTAL), (0, 0))) + return Answer(report_id, totals, strata, stored_before=True, groups=groups, excluded=excluded) # --- the contract -------------------------------------------------------------------------------------------------- diff --git a/webapi/orchestration/__main__.py b/webapi/orchestration/__main__.py index b6dca89..f45d65e 100644 --- a/webapi/orchestration/__main__.py +++ b/webapi/orchestration/__main__.py @@ -15,7 +15,7 @@ from pathlib import Path from webapi.orchestration.context import Context from webapi.orchestration.runner import run -PROJECTS = ("cacu", "cama") +PROJECTS = ("cacu", "cama", "tea") def main(argv: list[str] | None = None) -> None: diff --git a/webapi/orchestration/reference/parametros.toml b/webapi/orchestration/reference/parametros.toml index 776275d..f55b478 100644 --- a/webapi/orchestration/reference/parametros.toml +++ b/webapi/orchestration/reference/parametros.toml @@ -51,12 +51,6 @@ valor = 1 estado = "provisional" fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)" -[tea.riesgos.horizonte_banda] -# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses). -valor = 4 -estado = "provisional" -fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)" - [comun.catalogos.banda_riesgo] # Las bandas del resumen de riesgos, de menor a mayor. valor = [ @@ -90,10 +84,10 @@ estado = "provisional" fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar" # =========================================================================== -# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8) +# TEA · the screening's indicators (M21 to M30) # -# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la -# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses". +# The key is the dotted path: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses". +# The measures read their rules from dbt's var `tea` (Transformation/dbt_project.yml), which holds the same values. # Las listas y tablas se guardan en def_parametro como JSON. # El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga. # Documentos citados (repositorio analisis-tea, carpeta docs/): @@ -102,9 +96,10 @@ fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-1 # =========================================================================== [tea.cohorte.edad_min_meses] +# The cohort: children whose first M-CHAT was at 16 to 36 completed months. valor = 16 estado = "confirmado" -fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)" +fuente = "Responsable del proyecto, 2026-11-11: edad cumplida al primer M-CHAT, de 16 a 36 meses" [tea.cohorte.edad_max_meses] valor = 36 @@ -117,97 +112,23 @@ valor = 30.4375 estado = "confirmado" fuente = "analisis-tea/tea/comun.py, edad_meses" -[tea.cohorte.plazo_ados2_eeg_dias] -# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo. -valor = 30 -estado = "confirmado" -fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)" - [tea.cohorte.ventanas] -# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos. +# Age groups, by completed months at the first M-CHAT, without gaps: the windows of the TEA page. valor = [ - { clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" }, - { clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" }, - { clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" }, + { clave = "16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" }, + { clave = "24_29", desde = 24, hasta = 29, etiqueta = "24 a 29 meses", color = "#5E93CC" }, + { clave = "30_36", desde = 30, hasta = 36, etiqueta = "30 a 36 meses", color = "#1B4A80" }, ] estado = "confirmado" -fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)" - -[tea.instrumentos.informantes_ramos] -# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre. -valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"] -estado = "confirmado" -fuente = "contexto §1 (equipo); psicología no registra al cuidador principal" - -[tea.instrumentos.informantes_otros] -valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"] -estado = "confirmado" -fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21" - -[tea.ramos.areas] -# «TOTAL» no cuenta como área. -valor = [ - { clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" }, - { clave = "LINGUISTICO", etiqueta = "Lingüístico" }, - { clave = "FISICO", etiqueta = "Físico" }, - { clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" }, - { clave = "ADAPTATIVO", etiqueta = "Adaptativo" }, -] -estado = "confirmado" -fuente = "spec v2, catálogo de ins_area; contexto §1" - -[tea.poblacion.css_min_tea] -# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor. -valor = 3 -estado = "confirmado" -fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo" +fuente = "Responsable del proyecto, 2026-11-10: las ventanas de la página de TEA. Colores: paleta de ejemplo (provisional)" [tea.diagnostico.cie_tea] -# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840). +# M21 to M25: ICD-10 codes of the neuropediatrics note that confirm the diagnosis, without the dot (F84.0 -> F840). +# F84 without its subcode doesn't count. valor = ["F840"] estado = "confirmado" fuente = "usuario (2026-10-15): solo F84.0 (autismo)" -[tea.diagnostico.instrumentos_mchat] -# M25: valores de psi_instrumento_tamizaje que son un M-CHAT. -valor = ["M_CHAT_R", "M_CHAT_RF"] -estado = "confirmado" -fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)" - -[tea.atencion.plazo_referencia_evaluacion_dias] -# K1: inicio de la evaluación a más tardar este número de días después de la referencia. -valor = 90 -estado = "confirmado" -fuente = "estandares: NICE QS51, enunciado 1 (3 meses)" - -[tea.parto.apgar_corte] -# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10). -valor = 7 -estado = "confirmado" -fuente = "lista, M17: menor de 7, 7, y 8 a 10" - -# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar: -# un cambio pide volver a cargar. -[tea.antecedentes_maternos.no_registrado] -valor = "NO_REGISTRADO" -estado = "confirmado" -fuente = "spec v2: NO_REGISTRADO = sin dato" - -[tea.antecedentes_maternos.hipertension_ninguno] -valor = "NINGUNO" -estado = "confirmado" -fuente = "spec v2, catálogo de amg_hipertension_preeclampsia" - -[tea.antecedentes_maternos.embarazo_no_unico] -valor = ["GEMELAR", "TRIPLE_O_MAS"] -estado = "confirmado" -fuente = "spec v2, catálogo de amg_embarazo_multiple" - -[tea.antecedentes_maternos.liquido_anormal] -valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"] -estado = "confirmado" -fuente = "spec v2, catálogo de amg_liquido_amniotico" - [tea.supresion.activa] # Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se # suprime nada, aunque comun.umbral_supresion tenga valor. @@ -232,54 +153,6 @@ valor = { etiqueta = "Sin dato", color = "#C9CDD2" } estado = "confirmado" fuente = "lista: «sin dato» siempre se muestra como categoría propia" -[tea.catalogos.sexo] -valor = [ - { clave = "F", etiqueta = "Femenino", color = "#E0A030" }, - { clave = "M", etiqueta = "Masculino", color = "#2F6DB3" }, - { clave = "I", etiqueta = "Indeterminado", color = "#8A9199" }, -] -estado = "provisional" -fuente = "spec v2, pac_sexo; colores provisionales" - -[tea.catalogos.resultado_mchat] -valor = [ - { clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" }, - { clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" }, - { clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" }, -] -estado = "provisional" -fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales" - -[tea.catalogos.interpretacion_ramos] -valor = [ - { clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" }, - { clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" }, - { clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" }, -] -estado = "provisional" -fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales" - -[tea.catalogos.grado_hipoacusia] -valor = [ - { clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" }, - { clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" }, - { clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" }, - { clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" }, - { clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" }, - { clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" }, -] -estado = "provisional" -fuente = "spec v2, pea_grado_hipoacusia; colores provisionales" - -[tea.catalogos.apgar_5min] -valor = [ - { clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" }, - { clave = "SIETE", etiqueta = "7", color = "#E8C28E" }, - { clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" }, -] -estado = "provisional" -fuente = "lista, M17; colores provisionales" - # =========================================================================== # CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml) # =========================================================================== diff --git a/webapi/orchestration/semantic_layer.py b/webapi/orchestration/semantic_layer.py index 9642c57..3ba3604 100644 --- a/webapi/orchestration/semantic_layer.py +++ b/webapi/orchestration/semantic_layer.py @@ -25,8 +25,9 @@ def event_views(manifest: Path, project: str) -> list: """`drop view if exists` and `create view … as ` for every model the project's measures read, parents first. - Those are the project's models semantic models count over (`models//…`) and the timelines its strata - read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined + Those are the project's models semantic models count over (`models//…`), the timelines its strata + read (`meta.estratos.*.linea`) and the views the WebApi reads (`meta.lee_la_webapi`), with the non-ephemeral + models they're built on; an ephemeral one is already inlined in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here. """ m = json.loads(manifest.read_text(encoding="utf-8")) @@ -37,6 +38,9 @@ def event_views(manifest: Path, project: str) -> list: roots |= {by_name[spec["linea"]] for metric in m["metrics"].values() if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/") for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec} + # The views the WebApi reads directly (a follow-up list, a patient summary). + roots |= {uid for uid, n in nodes.items() if n["resource_type"] == "model" and n["fqn"][1] == project + and n["config"].get("meta", {}).get("lee_la_webapi")} ordered: list[str] = [] def visit(uid: str) -> None: @@ -69,10 +73,14 @@ def catalog_layers(project: str, manifest: Path) -> list[list]: contract = CONTRACTS[scoring_of(d)] measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric], contrato=contract, unidad=d.basis)) - codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()))) + exclusion = getattr(d, "exclusion", None) + codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()), + *(exclusion.codes if exclusion else ()))) children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c, etiqueta=c) for c in codes] children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0)) + children += [t.CatMeasureGrupo(measure_id=d.measure_id, grupo=g.name, etiqueta=g.label, orden=i) + for i, g in enumerate(getattr(d, "groups", ()), 1)] children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata] stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata] return [stratum_rows + measures, children] diff --git a/webapi/orchestration/silver/procedures.py b/webapi/orchestration/silver/procedures.py index 9946a2d..1412ad8 100644 --- a/webapi/orchestration/silver/procedures.py +++ b/webapi/orchestration/silver/procedures.py @@ -14,6 +14,7 @@ llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`, from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field +from types import SimpleNamespace from typing import NamedTuple from webapi.orchestration.reference.catalogs import Catalogo @@ -59,6 +60,16 @@ class Hija: resultados: Mapping[str, str] = field(default_factory=dict) +@dataclass(frozen=True) +class Junta: + """Another staging row whose columns the row's content takes: the row of `staging` whose `llave` equals the + row's column `columna` (an electrode value takes its metric's code and EEG). Without a match, they're null.""" + + staging: type + llave: str + columna: str + + @dataclass(frozen=True) class DeStaging: """Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c). @@ -72,6 +83,10 @@ class DeStaging: no es un reporte); no es un descarte. - `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en `descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging. + - `juntas`: rows of other staging tables whose columns join the content before the derived ones. + - `observa_en`: the row gives no procedure of its own; its observations go on the procedure this parent key + names (a metric of an EEG is a result of the EEG's recording). `clase` is unused then. + A result's template can name the content's columns (`eeg.{metrica}`) besides `{estudio}`. Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada. Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17). @@ -92,6 +107,8 @@ class DeStaging: paciente: str | None = "pac_id" solo_si: Callable | None = None descartar: Callable | None = None + juntas: tuple[Junta, ...] = () + observa_en: Padre | None = None class LotePlata(NamedTuple): @@ -124,6 +141,7 @@ def plata_desde_staging( pacientes = set(pacientes) tipos, vigentes = _tipos_y_vigentes(catalogo) procedimientos, observaciones, descartes = [], [], {} + indices: dict[tuple[str, str], dict] = {} for c in correspondencias: tabla = c.staging.__tablename__ for fila in filas.get(tabla, ()): @@ -133,7 +151,13 @@ def plata_desde_staging( continue if c.solo_si is not None and not c.solo_si(fila): continue - contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}} + contenido = fila.model_dump() + if c.juntas: + for junta in c.juntas: + unida = _junta(junta, filas, indices).get(contenido.get(junta.columna)) + contenido = {**(unida or dict.fromkeys(junta.staging.model_fields)), **contenido} + fila = SimpleNamespace(**contenido) + contenido = {**contenido, **{nombre: f(fila) for nombre, f in c.derivadas.items()}} contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente) contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()}) _repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital, @@ -168,6 +192,14 @@ def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]: return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3]))) +def _junta(junta: Junta, filas: Mapping[str, Iterable], indices: dict) -> dict: + """The rows of the joined table by their key, as dictionaries; built once per batch.""" + clave = (junta.staging.__tablename__, junta.llave) + if clave not in indices: + indices[clave] = {getattr(f, junta.llave): f.model_dump() for f in filas.get(clave[0], ())} + return indices[clave] + + def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]: tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados} vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"} @@ -183,6 +215,11 @@ def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, col motivo = f"{nombre}: {c.estudio_de} fuera de catálogo" descartes[motivo] = descartes.get(motivo, 0) + 1 return + if c.observa_en is not None: + dueno = _parent(c.observa_en, contenido) + if dueno is not None: + observaciones += _observaciones(dueno, contenido, c.resultados, c.fuentes, tipos, vigentes) + return llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase) procedimientos.append({ "llave": llave, @@ -225,7 +262,9 @@ def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str], tipos: dict, vigentes: set) -> list[dict]: filas = [] for columna, plantilla in resultados.items(): - resultado_id = plantilla.format(estudio=llave[2]) + resultado_id = plantilla.format_map({**contenido, "estudio": llave[2]}) + if resultado_id not in tipos and "{" in plantilla.replace("{estudio}", ""): + continue # a value of the row names a result the catalog doesn't have (an unknown metric) filas.append({ "procedimiento": llave, "pac_id": contenido.get("pac_id"), diff --git a/webapi/orchestration/silver/tea.py b/webapi/orchestration/silver/tea.py new file mode 100644 index 0000000..10b58fb --- /dev/null +++ b/webapi/orchestration/silver/tea.py @@ -0,0 +1,120 @@ +"""TEA in the two-table silver: what each staging row gives, as `DESDE_STAGING` (read by `carga_desde_staging`). + +- an order is an `orden` of the study it asks for (`ord_tipo_estudio`, in Core's code or one of its aliases); +- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each + hangs from its order when it has one; +- an EEG metric is a result of its EEG's recording, not a procedure; a metric's electrode value is a `parte` of the + EEG (`codigo_fuente` the electrode) with the metric's result. Both find their EEG through the metric's row. +""" + +from core.tea.enums import ( + CLASIFICACION_ADOS2_ALIAS, + TIPO_ESTUDIO_ALIAS, + ClasificacionAdos2, + ModuloAdos2, + TipoEstudio, +) +from core.tea.models import ( + ADOS2_ITEMS, + Ados2, + Eeg, + EegMetrica, + EegMetricaElectrodo, + EvaluacionNeuropediatrica, + Mchat, + OrdenesEstudio, + Pacientes, +) + +from webapi.orchestration.silver.procedures import DeStaging, Junta, Padre +from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio + +PACIENTES = Pacientes # where persons come from +ORDENES = OrdenesEstudio.__tablename__ +EEG = Eeg.__tablename__ + + +def _codigo(columna: str, enum, alias: dict | None = None): + codigos = {e.value for e in enum} + return lambda f: codigo_de_especialidad(getattr(f, columna), alias or {}, codigos) + + +def _su_orden(estudio_id: str, columna: str) -> Padre: + """The order a study row names by its `*_ord_id`.""" + return Padre(estudio_id=estudio_id, clase="orden", fuente_id=columna, tabla=ORDENES) + + +def _metrica(f) -> str | None: + """A metric's result in the catalog: its code in lower case (`RITMO_POSTERIOR` -> `ritmo_posterior`).""" + codigo = texto_limpio(f.met_codigo) + return None if codigo is None else codigo.lower() + + +SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG) + + +DESDE_STAGING = ( + DeStaging( + OrdenesEstudio, "ord_id", "orden", estudio_de="tipo_estudio", fecha="ord_fecha", paciente="ord_pac_id", + derivadas={ + "tipo_estudio": _codigo("ord_tipo_estudio", TipoEstudio, TIPO_ESTUDIO_ALIAS), + "intencion": lambda f: INTENCION, + }, + columnas={"id_hospital": "ord_id_hospital", "codigo_fuente": "ord_tipo_estudio"}, + resultados={"intencion": "orden.intencion"}, + ), + DeStaging( + Mchat, "mch_id", "toma", estudio_id="mchat", fecha="mch_fecha", paciente="mch_pac_id", + padres=(_su_orden("mchat", "mch_ord_id"),), + resultados={"mch_puntaje": "mchat.puntaje"}, + ), + DeStaging( + Ados2, "ado_id", "encuentro", estudio_id="ados2", fecha="ado_fecha", paciente="ado_pac_id", + padres=(_su_orden("ados2", "ado_ord_id"),), + derivadas={ + "modulo": _codigo("ado_modulo", ModuloAdos2), + "clasificacion": _codigo("ado_clasificacion", ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS), + "algoritmo": lambda f: texto_limpio(f.ado_algoritmo), + }, + resultados={ + "modulo": "ados2.modulo", + "algoritmo": "ados2.algoritmo", + "clasificacion": "ados2.clasificacion", + "ado_css": "ados2.css", + **{f"ado_{item}": f"ados2.{item}" for item in ADOS2_ITEMS}, + }, + fuentes={"modulo": "ado_modulo", "clasificacion": "ado_clasificacion"}, + ), + DeStaging( + EvaluacionNeuropediatrica, "neu_id", "encuentro", estudio_id="evaluacion_neuropediatrica", + fecha="neu_fecha", paciente="neu_pac_id", padres=(_su_orden("evaluacion_neuropediatrica", "neu_ord_id"),), + derivadas={"cie_codigo": lambda f: cie(f.neu_cie_codigo)}, + resultados={"cie_codigo": "evaluacion_neuropediatrica.diagnostico"}, + ), + DeStaging( + Eeg, "eeg_id", "toma", estudio_id="eeg", fecha="eeg_fecha_estudio", paciente="eeg_pac_id", + padres=(_su_orden("eeg", "eeg_ord_id"),), columnas={"id_hospital": "eeg_id_registro_laboratorio"}, + resultados={ + "eeg_con_sueno": "eeg.con_sueno", + "eeg_canales": "eeg.canales", + "eeg_duracion_min": "eeg.duracion_min", + "eeg_canales_amplitud": "eeg.calidad_amplitud", + "eeg_canales_alta_frecuencia": "eeg.calidad_alta_frecuencia", + "eeg_canales_correlacion": "eeg.calidad_correlacion", + "eeg_canales_sin_senal": "eeg.calidad_sin_senal", + "eeg_ruido_linea_db": "eeg.calidad_linea", + }, + ), + DeStaging( + EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG, + derivadas={"metrica": _metrica}, + resultados={"met_valor": "eeg.{metrica}"}, + ), + DeStaging( + EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None, + juntas=(Junta(EegMetrica, "met_id", "mel_met_id"),), padres=(SU_EEG,), + derivadas={"metrica": _metrica}, + columnas={"codigo_fuente": "mel_electrodo"}, + resultados={"mel_valor": "eeg.{metrica}"}, + ), +) diff --git a/webapi/orchestration/tables/__init__.py b/webapi/orchestration/tables/__init__.py index fd15b32..0a14336 100644 --- a/webapi/orchestration/tables/__init__.py +++ b/webapi/orchestration/tables/__init__.py @@ -14,7 +14,7 @@ from importlib import import_module from sqlmodel import SQLModel -PROJECTS = ("cacu", "cama") +PROJECTS = ("cacu", "cama", "tea") @dataclass(frozen=True) diff --git a/webapi/orchestration/tables/tea.py b/webapi/orchestration/tables/tea.py new file mode 100644 index 0000000..3bd5e07 --- /dev/null +++ b/webapi/orchestration/tables/tea.py @@ -0,0 +1,75 @@ +"""TEA's tables: in `Core`, in the domain's registry. + +`TABLAS` is what the shared code receives to work with this project; TEA's person adds nothing (its `sexo` stays null). +""" + +from core.tea.indicadores.models import ( + CatMeasure, + CatMeasureResultado, + CatMeasureValor, + CatMeasureGrupo, + CatEstrato, + CatEstratoValor, + CatMeasureEstrato, + MeasureReportUnidad, + MeasureReportUnidadEstrato, + CatEstudio, + CatResultado, + CatValor, + Observacion, + Procedimiento, + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, + Carga, + DefParametro, + DimFecha, + DimGrupoEdad, + DimPeriodo, + MeasureReport, + PeriodoObservacion, + Persona, +) + +from core.indicadores.cohortes import TablasCohorte +from webapi.orchestration.tables import TablasKit + +__all__ = ["TABLAS", "COHORTES"] + +TABLAS = TablasKit( + Persona=Persona, + PeriodoObservacion=PeriodoObservacion, + Carga=Carga, + DefParametro=DefParametro, + DimPeriodo=DimPeriodo, + DimFecha=DimFecha, + DimGrupoEdad=DimGrupoEdad, + MeasureReport=MeasureReport, + CatEstudio=CatEstudio, + CatResultado=CatResultado, + CatValor=CatValor, + Procedimiento=Procedimiento, + Observacion=Observacion, + CatMeasure=CatMeasure, + CatMeasureResultado=CatMeasureResultado, + CatMeasureValor=CatMeasureValor, + CatMeasureGrupo=CatMeasureGrupo, + CatEstrato=CatEstrato, + CatEstratoValor=CatEstratoValor, + CatMeasureEstrato=CatMeasureEstrato, + MeasureReportUnidad=MeasureReportUnidad, + MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, +) + +# Cohorts for models and their risk estimates: TEA builds none yet, the tables are the domain's. +COHORTES = TablasCohorte( + CohorteArmado=CohorteArmado, + CohorteMiembro=CohorteMiembro, + CohorteExclusion=CohorteExclusion, + CohorteVariable=CohorteVariable, + EvaluacionRiesgoLote=EvaluacionRiesgoLote, + EvaluacionRiesgo=EvaluacionRiesgo, +) diff --git a/webapi/recomputation.py b/webapi/recomputation.py index 77f4b40..39fda58 100644 --- a/webapi/recomputation.py +++ b/webapi/recomputation.py @@ -26,7 +26,7 @@ from typing import Any from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message -DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes +DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) -- 2.53.0 From 7d5c79f520afd2c2b2c3f3ba8cd9d92d4d855912 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 12 Nov 2026 19:47:19 -0600 Subject: [PATCH 13/24] TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too --- tests/staging/tea.py | 2 +- tests/test_fhir_tea.py | 10 +++++++ tests/test_tea_measures.py | 56 ++++++++++++++++++++++++++++---------- webapi/fhir/__init__.py | 8 +----- webapi/kpis.py | 23 +++++++++++++--- webapi/metrics.py | 20 ++++++++++++++ 6 files changed, 93 insertions(+), 26 deletions(-) diff --git a/tests/staging/tea.py b/tests/staging/tea.py index 8bb82ce..531b13e 100644 --- a/tests/staging/tea.py +++ b/tests/staging/tea.py @@ -12,7 +12,7 @@ with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first stays at psychology. - 4, H-T04, 39 months: out of the cohort, never counted. - 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in - order, so it stays at M-CHAT. + order, so it stays at M-CHAT and in process. - 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG step is dated by the note, so it reaches EEG on 2 Jun and leaves after June. - 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else. diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py index 03b8789..61533db 100644 --- a/tests/test_fhir_tea.py +++ b/tests/test_fhir_tea.py @@ -82,6 +82,16 @@ def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monke assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} +def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch): + """Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both + with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation.""" + assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()} + assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404 + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()} + assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200 + + def test_a_measure_carries_what_the_page_needs(client): """Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category labels. Fails if the page's catalog fields stop reaching the Measure.""" diff --git a/tests/test_tea_measures.py b/tests/test_tea_measures.py index 6139462..3f1f890 100644 --- a/tests/test_tea_measures.py +++ b/tests/test_tea_measures.py @@ -19,7 +19,7 @@ from sqlmodel import select import staging.tea as fixture from conftest import base_de -from core.tea.models import Eeg, EegMetrica +from core.tea.models import Ados2, Eeg, EegMetrica, Mchat from webapi.compositions import answer_composition, composition_definitions from webapi.durations import answer_duration, duration_definitions from webapi.metrics import Question, answer, measure_definitions @@ -106,9 +106,9 @@ RESULTS = { "2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2}, "2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2}, "2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3}, - "2025-07": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-07": {"EN_PROCESO": 3}, "2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3}, - "2025-S2": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-S2": {"EN_PROCESO": 3}, } @@ -116,18 +116,19 @@ RESULTS = { def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period): """Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note - confirms it in July even without the ADOS-2. Fails if F84 counts as a confirmation or a note without F84.0 counts - as in process.""" + of July doesn't confirm it without the ADOS-2: it stays in process. Fails if F84 counts as a confirmation, if a + note without F84.0 counts as in process, or if a note counts before the psychology step.""" assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period] @pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [ - ("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 1, 3, 1), ("2025-S1", 2, 5, 1), + ("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 0, 3, 1), ("2025-S1", 2, 5, 1), ]) def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator, excluded): """Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion - from April. Fails if the denominator takes the children without TEA or the exclusion stops being counted.""" + from April. In July child 5's F84.0 note, without the ADOS-2, leaves it in process. Fails if the denominator takes + the children without TEA, the exclusion stops being counted, or a note confirms without the psychology step.""" result = proportion(base, manifest, "M24_confirmacion_diagnostico", period) assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded) @@ -142,15 +143,15 @@ def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest): @pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [ - ("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 1, 1), - ("2025-S1", 2, 0, 2), ("2025-S2", 0, 1, 1), + ("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 0, 0), + ("2025-S1", 2, 0, 2), ("2025-S2", 0, 0, 0), ]) def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg, without_eeg, confirmed): """Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG - by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5, confirmed in July, - has a good EEG but no ADOS-2, so its chain never reaches it. Fails if the EEG is read beyond the period's end or - outside the chain.""" + by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5 has a F84.0 note and + a good EEG in July but no ADOS-2, so it isn't confirmed and July has nobody. Fails if the EEG is read beyond the + period's end, or the note or the EEG count outside the chain.""" m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period) m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period) assert (m21.numerator, m21.denominator) == (with_eeg, confirmed) @@ -164,14 +165,14 @@ def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, ("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5), ("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0), ("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5), - ("M25_dias_mchat_diagnostico", "2025-S2", 4, 1, 16.0), + ("M25_dias_mchat_diagnostico", "2025-S2", 4, 0, None), ]) def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period, initial, n, median): """Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval ended by the period's end have days (repeated in each period that counts them), the rest count as without event. In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of - 1 July gives 16 days in the second semester only. Fails if the value is read beyond the period's end or the + 1 July gives no days without the ADOS-2. Fails if the value is read beyond the period's end or the population goes back to the facts in the period.""" result = duration(base, manifest, measure_id, period) assert (result.initial, result.n, result.median) == (initial, n, median) @@ -243,3 +244,30 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest): assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1 finally: base.motor.dispose() + + +def test_a_knowledge_cut_off_keeps_what_was_known_when_an_earlier_fact_arrives_later(tmp_path, manifest): + """Pins down: an answer as of a load doesn't change when a later load brings an earlier-dated fact. A second load + adds an ADOS-2 of 20 Feb for child 3 (its known one is of 28 Feb) and an M-CHAT of 1 Apr for child 7 (its known + one is of 1 May). Asked as of the first load, March still counts child 3 at psychology and May still counts + child 7; asked as of now, child 7 is in the screening from April. Fails if a child's first fact is chosen among + every load's facts and then dropped for being known after the cut-off.""" + base = base_de("tea", tmp_path) + try: + base.run(*UNTIL_MODELS, allow_undecided=True) + with base.motor.begin() as connection: + (first_load,) = connection.execute(text("select max(fin) from carga")).one() + known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc) + with base.staging() as session: + session.add(Ados2(ado_id="ado-3-earlier", ado_pac_id=3, ado_fecha=date(2025, 2, 20), ado_modulo="MODULO_2", + ado_css=2)) + session.add(Mchat(mch_id="mch-7-earlier", mch_pac_id=7, mch_fecha=date(2025, 4, 1), mch_puntaje=7)) + session.commit() + base.run("load", allow_undecided=True) + later = replace(base, ctx=replace(base.ctx, allow_undecided=True)) + for period in ("2025-03", "2025-05"): + assert composition(later, manifest, "M28_casos_por_estado", period, knowledge_cutoff=known) == STAGES[period] + assert composition(later, manifest, "M28_casos_por_estado", "2025-04") == { + "SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2} + finally: + base.motor.dispose() diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index c039626..eaeb72f 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -39,13 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: def definitions() -> dict: """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" - every = {fhir_id(d): d for d in definitions_of(project, manifest).values()} - if project == "tea": - from webapi.fhir.tea import alterations_validated - - if not alterations_validated(): - every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")} - return every + return {fhir_id(d): d for d in definitions_of(project, manifest).values()} def definition_of(measure_id: str): return definitions().get(measure_id.replace("_", "-")) diff --git a/webapi/kpis.py b/webapi/kpis.py index abf497e..61941e8 100644 --- a/webapi/kpis.py +++ b/webapi/kpis.py @@ -10,6 +10,7 @@ durations (`webapi.durations`; without `corte_evento`, the day of the last load) import json from collections.abc import Callable from datetime import date, datetime, timezone +from functools import lru_cache from pathlib import Path from core.indicadores.tipos import FechaHoraUTC @@ -24,28 +25,42 @@ LOADS = table("carga", column("inicio", FechaHoraUTC)) def definitions_of(project: str, manifest: Path) -> dict: - """Every measure the manifest defines for the domain, by its id (the end of its url).""" + """Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for + a validation (`meta.requiere_validacion`) is left out until it's given.""" + return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)} + + +@lru_cache +def _defined(project: str, manifest: Path) -> dict: every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)} return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")} +def _awaits_validation(definition) -> bool: + """TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them.""" + if not definition.meta.get("requiere_validacion"): + return False + from webapi.fhir.tea import alterations_validated + + return not alterations_validated() + + def kpis_blueprint(project: str, repositories, manifest: Path, *, now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: """The blueprint of a domain, to register with `url_prefix="/"`. `repositories` is the domain's `persistance.` module.""" blueprint = Blueprint(f"{project}_kpis", __name__) - definitions = definitions_of(project, manifest) @blueprint.get("/indicadores") def list_kpis(): """The measures answered on request: id, url, version and scoring.""" return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)} - for i, d in sorted(definitions.items())]) + for i, d in sorted(definitions_of(project, manifest).items())]) @blueprint.get("/indicadores/") def get_kpi(measure_id: str): """A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history.""" - definition = definitions.get(measure_id) + definition = definitions_of(project, manifest).get(measure_id) if definition is None: return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404 try: diff --git a/webapi/metrics.py b/webapi/metrics.py index 7baf63c..efb8c65 100644 --- a/webapi/metrics.py +++ b/webapi/metrics.py @@ -49,6 +49,7 @@ TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" OF_THE_CHOSEN = "del_elegido" COLUMN = "columna" STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo" +KNOWN_VERSION = "version_conocida" class UndecidedRule(ValueError): @@ -283,10 +284,15 @@ class MeasureQueries: if self.status is not None: names |= {definition.dimensions[n] for n in self.status.columns()} known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n} + version = (getattr(definition, "meta", None) or {}).get(KNOWN_VERSION) + if version is not None: + known.add(definition.dimensions[version]) self.events = table(definition.relation, *( column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) if name.isidentifier())) self.periods = period_table + if version is not None: + self.events = self._known_version(definition.dimensions[version]) if self.status is not None: self.events = self._status_rows() self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") @@ -329,6 +335,20 @@ class MeasureQueries: conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff] return and_(*conditions) + def _known_version(self, version: str): + """Each unit's rows as they were known at the knowledge cut-off, for a model with one set of rows per unit + and knowledge version (`meta.version_conocida`, the column that dates each version): the unit's latest + version by the cut-off, or its latest of all without one. A subquery with the model's name, read as the + model is.""" + base = self.events + latest = func.rank().over(partition_by=base.c[self.d.numerator.measure_expr], order_by=desc(base.c[version])) + versions = select(*base.c, latest.label("lugar_de_version")) + if self.q.knowledge_cutoff is not None: + versions = versions.where(base.c[version] <= self.q.knowledge_cutoff) + versions = versions.subquery("versiones") + return (select(*(c for c in versions.c if c.name != "lugar_de_version")) + .where(versions.c.lugar_de_version == 1).subquery(self.d.relation)) + def _status_rows(self): """Each unit the period counts, with its row of highest order: a subquery with the model's name, so the rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds. -- 2.53.0 From 9775a22c57ad87abc16130247947fe6e02dcd050 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 11:55:17 -0600 Subject: [PATCH 14/24] CaMa's silver load reads results from the reports' text, mapped by the catalog How: `silver.extracted.DesdeTexto` turns the catalog's `etiquetas_fuente` and each value's `alias` into Extraction's field specs and into derived columns of a `DeStaging`. CaMa reads density and lesion size from the mammography interpretation, histology, grade, receptors, HER2 and Ki-67 from the pathology PDF's text layer (no OCR at load time), and the clinical stage from the note's texts. `resultados_extraibles` reads and checks the new keys: captions are a non-empty list, aliases need captions, and no spelling names two values. Implications: a code comes with the spelling it matched as `valor_fuente`; an unknown spelling is kept as `valor_fuente` with no code, counted as out of catalog, and becomes a code on the next load once its alias is in the catalog. Nothing is renamed in the stored data and no table or column changes. The synthetic CaMa staging gains a mammography text, a pathology PDF and a note with a stage. --- tests/staging/cama.py | 44 ++++- tests/test_extracted_results.py | 178 ++++++++++++++++++ webapi/orchestration/reference/catalogs.py | 60 ++++++ webapi/orchestration/silver/cama.py | 27 ++- webapi/orchestration/silver/extracted.py | 119 ++++++++++++ .../orchestration/silver/orders_and_notes.py | 12 +- 6 files changed, 433 insertions(+), 7 deletions(-) create mode 100644 tests/test_extracted_results.py create mode 100644 webapi/orchestration/silver/extracted.py diff --git a/tests/staging/cama.py b/tests/staging/cama.py index 1b56465..42b3d27 100644 --- a/tests/staging/cama.py +++ b/tests/staging/cama.py @@ -20,12 +20,18 @@ reporte y grado, y una solicitada que todavía no lo tiene. Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico (`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`). +Texts the silver load reads results from (`TEXTOS`, `INFORME_DE_PATOLOGIA`, `DIAGNOSTICO_DE_NOTA`): +H-003's B4A carries density C and a 14 mm lesion, its biopsy a PDF with an invasive ductal carcinoma, grade 2, +ER+ 90 %, PR- 0 %, HER2 3+ and Ki-67 25 %, and its oncology note stage IIA. H-101's first mammography says +density "tipo E", which the catalog doesn't know: it stays as source text, out of catalog. + H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`: lo único común entre los dos sistemas es `pac_id_hospital`. Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio. """ +import io from datetime import date, timedelta from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente @@ -69,6 +75,39 @@ NOTAS = ( ("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta ) +# Index in MASTOGRAFIAS -> the radiologist's interpretation. +TEXTOS = { + 0: "Densidad mamaria: tipo E\nSin hallazgos.", + 4: "Densidad mamaria: heterogéneamente densas (C).\nNódulo irregular en CSE.\nTamaño de la lesión: 14 mm.", +} +# Index in BIOPSIAS -> the lines of its pathology report, as a PDF with a text layer. +INFORME_DE_PATOLOGIA = { + 1: ( + "DIAGNÓSTICO: Carcinoma ductal infiltrante", + "Grado histológico: 2 (moderadamente diferenciado)", + "Receptores de estrógeno: Positivo (90%)", + "Receptores de progesterona: Negativo (0%)", + "HER2: 3+", + "Ki-67: 25%", + ), +} +# Patient -> the diagnosis text of their note. +DIAGNOSTICO_DE_NOTA = {"H-003": "Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)"} + + +def pdf_de(lineas) -> bytes: + """A one-page PDF with these lines as its text layer.""" + from reportlab.lib.pagesizes import letter + from reportlab.pdfgen import canvas + + buffer = io.BytesIO() + hoja = canvas.Canvas(buffer, pagesize=letter) + for i, linea in enumerate(lineas): + hoja.drawString(72, 720 - 18 * i, linea) + hoja.save() + return buffer.getvalue() + + # Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital). # La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía. ORDENES = ( @@ -141,11 +180,12 @@ def insertar(sesion: Session) -> None: mast_calidad_imagen=calidad, mast_birads=birads, mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7), + mast_interpretacion=TEXTOS.get(indice), ) ) sesion.add_all(mastografias) sesion.flush() - for indice, solicitud, reporte, grado in BIOPSIAS: + for numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS): mastografia = mastografias[indice] sesion.add( BiopsiaMama( @@ -155,6 +195,7 @@ def insertar(sesion: Session) -> None: bx_fecha_solicitud=solicitud, bx_fecha_reporte=reporte, bx_grado_histologico=grado, + bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[numero]) if numero in INFORME_DE_PATOLOGIA else None, ) ) sesion.add_all( @@ -165,6 +206,7 @@ def insertar(sesion: Session) -> None: nm_fecha=fecha, nm_cie_codigo=cie, nm_especialidad=especialidad, + nm_diagnostico_texto=DIAGNOSTICO_DE_NOTA.get(hospital) if especialidad == ONCOLOGIA else None, ) for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1) ) diff --git a/tests/test_extracted_results.py b/tests/test_extracted_results.py new file mode 100644 index 0000000..8dd938e --- /dev/null +++ b/tests/test_extracted_results.py @@ -0,0 +1,178 @@ +"""What this module covers: catalog results read from a staging row's text (`silver.extracted`). The catalog's +`etiquetas_fuente` and `alias` checked when it's read; a report's text, a PDF's text layer and a note turned into +codes, numbers and their sources; a spelling the catalog doesn't know kept as text and turned into a code by a +catalog change alone; and CaMa's load putting them in silver and dbt's timeline. + +Fixtures: `catalogo_en`, a copy of CaMa's catalog in `tmp_path` that the catalog functions read instead of Core's; +`cargada`, the CaMa fixture database (`staging/cama.py`: H-003's texts and pathology PDF, H-101's unknown density) +loaded, with dbt's views when `DBT_MANIFEST` is set. +""" + +import os +from types import SimpleNamespace + +import pytest +from sqlalchemy import text +from staging.cama import INFORME_DE_PATOLOGIA, pdf_de +from webapi.orchestration.reference import catalogs +from webapi.orchestration.reference.catalogs import CatalogoInvalido, catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.silver import cama +from webapi.orchestration.silver.extracted import DesdeTexto +from webapi.orchestration.tables import tablas_de + +DENSIDAD = """ +[mastografia] +etiqueta = "Mastografía" + +[mastografia.resultados.densidad] +etiqueta = "Densidad" +tipo_valor = "codigo" +etiquetas_fuente = ["Densidad mamaria"] +valores = [ + { valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C"] }, + { valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D"] }, +] +""" + + +@pytest.fixture +def catalogo_en(tmp_path, monkeypatch): + """Writes a catalog for `cama` in `tmp_path` and points the catalog functions at it. Returns a writer.""" + ruta = tmp_path / "cama.toml" + monkeypatch.setattr(catalogs, "ruta_de_catalogo", lambda proyecto: ruta) + + def escribir(contenido: str): + ruta.write_text(contenido, encoding="utf-8") + return ruta + + return escribir + + +@pytest.fixture +def proyecto(): + return "cama" + + +@pytest.fixture +def cargada(base): + pasos = ("catalogs", "load", "event_models") if os.environ.get("DBT_MANIFEST") else ("catalogs", "load") + base.run(*pasos) + return base + + +def observaciones(base, resultado_prefijo: str) -> dict[str, tuple]: + """`resultado_id` -> (valor_id, valor_numerico, valor_fuente) of the observations whose result starts so.""" + with base.motor.connect() as con: + filas = con.execute(text( + "SELECT resultado_id, valor_id, valor_numerico, valor_fuente FROM observacion_clinica " + "WHERE resultado_id LIKE :p AND (valor_id IS NOT NULL OR valor_numerico IS NOT NULL OR valor_fuente IS NOT NULL)" + ), {"p": resultado_prefijo + "%"}).all() + return {f.resultado_id: (f.valor_id, f.valor_numerico, f.valor_fuente) for f in filas} + + +# --- the catalog --- + +def test_the_catalog_lists_cama_s_extractable_results_as_provisional(): + """Pins down: every CaMa result with captions is extractable and marked provisional, and the catalog still + loads with them. Fails if `resultados_extraibles` drops a result or the new keys break `catalogo_desde_toml`.""" + extraibles = catalogs.resultados_extraibles("cama") + assert set(extraibles) >= {"mastografia.densidad", "biopsia.her2", "nota_medica.estadio_clinico"} + assert all(e.provisional for e in extraibles.values()) + catalogo = catalogo_desde_toml(ruta_de_catalogo("cama"), tablas=tablas_de("cama")) + assert {r.resultado_id for r in catalogo.resultados} >= set(extraibles) + + +@pytest.mark.parametrize("cambio, error", [ + (('alias = ["Tipo D"]', 'alias = ["Tipo C"]'), "se escribe igual"), + (('etiquetas_fuente = ["Densidad mamaria"]', 'etiquetas_fuente = []'), "lista de textos"), + (('etiquetas_fuente = ["Densidad mamaria"]\n', ''), "solo sirven con etiquetas_fuente"), +]) +def test_an_ambiguous_or_incomplete_mapping_is_rejected(catalogo_en, cambio, error): + """Pins down: one spelling on two values, empty captions, or aliases without captions stop the catalog from + loading. Fails if a check is dropped and an alias could turn into either of two codes.""" + ruta = catalogo_en(DENSIDAD.replace(*cambio)) + with pytest.raises(CatalogoInvalido, match=error): + catalogo_desde_toml(ruta, tablas=tablas_de("cama")) + + +# --- reading text --- + +def test_a_report_s_text_gives_codes_with_their_spelling_and_numbers(): + """Pins down: a caption followed by a known spelling gives its code and that spelling as source; a number + after its caption gives the number. Fails if the catalog's aliases stop reaching Extraction's field specs.""" + leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace( + mast_interpretacion="Densidad mamaria: heterogéneamente densas (C).\nTamaño de la lesión: 14 mm.")) + assert leido == {"mastografia.densidad": ("C", "heterogéneamente densas"), "mastografia.tamano_lesion_mm": (14.0, None)} + + +def test_an_unknown_spelling_is_kept_as_its_source_without_a_code(): + """Pins down: what follows a caption that matches no alias is kept as source text, with no code. Fails if it's + dropped (it couldn't be found and mapped later) or forced into a code.""" + leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E")) + assert leido["mastografia.densidad"] == (None, "tipo E") + + +def test_a_stage_is_found_in_a_note_without_a_caption(): + """Pins down: a result marked `buscar_en_texto` is found as a mention in narrative text. Fails if the flag + stops reaching `scan_free_text`.""" + leido = cama.DE_LA_NOTA.leer(SimpleNamespace( + nm_diagnostico_texto="Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)", nm_pronostico=None)) + assert leido["nota_medica.estadio_clinico"] == ("EIIA", "estadio clínico IIA") + + +def test_a_pathology_pdf_s_text_layer_gives_its_results(): + """Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop + going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor.""" + leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1]))) + assert {r: v for r, (v, _) in leido.items()} == { + "biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2", + "biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0, + "biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0, + "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, + } + + +def test_no_text_gives_no_values(): + """Pins down: a row without text (or a PDF that can't be read) gives every result empty. Fails if an empty + text or broken bytes raise during a load.""" + assert set(cama.DE_LA_NOTA.leer(SimpleNamespace(nm_diagnostico_texto=None, nm_pronostico=None)).values()) == {(None, None)} + assert set(cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=b"not a pdf")).values()) == {(None, None)} + + +def test_adding_an_alias_maps_the_same_text_on_the_next_read(catalogo_en): + """Pins down: an unknown spelling becomes a code by adding it to the catalog, with nothing else changed. Fails + if the mapping is cached across catalog reads or lives anywhere but the catalog.""" + fila = SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E") + catalogo_en(DENSIDAD) + antes = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila) + catalogo_en(DENSIDAD.replace('alias = ["Tipo D"]', 'alias = ["Tipo D", "Tipo E"]')) + despues = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila) + assert antes["mastografia.densidad"] == (None, "tipo E") + assert despues["mastografia.densidad"] == ("D", "tipo E") + + +# --- the load --- + +def test_the_load_puts_the_extracted_results_in_silver(cargada): + """Pins down: CaMa's load writes the results read from the interpretation, the pathology PDF and the note, and + an unknown spelling as an out-of-catalog source. Fails if `cama.DESDE_STAGING` stops wiring a `DesdeTexto`.""" + with cargada.motor.connect() as con: + densidades = sorted(con.execute(text( + "SELECT coalesce(valor_id, '?') || ':' || valor_fuente FROM observacion_clinica " + "WHERE resultado_id = 'mastografia.densidad' AND valor_fuente IS NOT NULL")).scalars()) + assert densidades == ["?:tipo E", "C:heterogéneamente densas"] + assert observaciones(cargada, "biopsia.her2") == {"biopsia.her2": ("H3", None, "3+")} + assert observaciones(cargada, "biopsia.ki67_pct") == {"biopsia.ki67_pct": (None, 25.0, None)} + assert observaciones(cargada, "nota_medica.estadio_clinico") == { + "nota_medica.estadio_clinico": ("EIIA", None, "estadio clínico IIA")} + + +def test_the_timeline_carries_the_extracted_results(cargada): + """Pins down: the timeline declares the new results, so H-003's stage, receptors and density are rows of it. + Fails if a source line is missing from `cama_linea_de_tiempo.yml`.""" + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + filas = cargada.ctx.repos.silver.timeline.read() + valores = {(f["tipo"], f["valor_codigo"] or f["valor_numerico"]) for f in filas} + assert {("estadio_clinico", "EIIA"), ("her2", "H3"), ("receptor_estrogeno_pct", 90.0), + ("densidad_mamaria", "C"), ("densidad_mamaria", "tipo E")} <= valores diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py index afb0798..3a59dc3 100644 --- a/webapi/orchestration/reference/catalogs.py +++ b/webapi/orchestration/reference/catalogs.py @@ -15,6 +15,7 @@ from pathlib import Path from typing import NamedTuple import core +from extraction.nlp.text import fold from core.indicadores.catalogos import TIPOS_DE_VALOR from sqlmodel import SQLModel @@ -54,6 +55,7 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo: for nombre, resultado in estudio.get("resultados", {}).items(): resultado_id = f"{estudio_id}.{nombre}" tipo_valor = _tipo_de_valor(resultado, resultado_id) + _claves_de_extraccion(resultado, resultado_id) resultados.append( tablas.CatResultado( resultado_id=resultado_id, @@ -93,6 +95,64 @@ def codigos_hospital(proyecto: str) -> dict[str, str]: return codigos +class ResultadoExtraible(NamedTuple): + """A result read from a document's text: the captions it's printed under and, if coded, each value's spellings.""" + + resultado_id: str + tipo_valor: str + etiquetas_fuente: tuple[str, ...] + alias: dict[str, tuple[str, ...]] # valor -> its spellings, the label included + buscar_en_texto: bool # also as a mention anywhere in the text, without a caption + provisional: bool + + +def resultados_extraibles(proyecto: str) -> dict[str, ResultadoExtraible]: + """`resultado_id` -> how it's found in a document, for every result of the catalog with `etiquetas_fuente`. + + The mapping lives in the catalog so that a new caption or spelling from the laboratory is one line there: + the next load reads it, and nothing already stored is renamed. + """ + extraibles = {} + for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items(): + for nombre, resultado in estudio.get("resultados", {}).items(): + resultado_id = f"{estudio_id}.{nombre}" + _claves_de_extraccion(resultado, resultado_id) + if "etiquetas_fuente" not in resultado: + continue + extraibles[resultado_id] = ResultadoExtraible( + resultado_id=resultado_id, + tipo_valor=resultado["tipo_valor"], + etiquetas_fuente=tuple(resultado["etiquetas_fuente"]), + alias={v["valor"]: (v["etiqueta"], *v.get("alias", ())) for v in resultado.get("valores", ())}, + buscar_en_texto=bool(resultado.get("buscar_en_texto", False)), + provisional=bool(resultado.get("provisional", False)), + ) + return extraibles + + +def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None: + """The extraction keys of a result: captions as a non-empty list of texts, and no spelling on two values.""" + etiquetas = resultado.get("etiquetas_fuente") + if etiquetas is not None and (not isinstance(etiquetas, list) or not etiquetas + or not all(isinstance(e, str) and e.strip() for e in etiquetas)): + raise CatalogoInvalido(f"{resultado_id}: etiquetas_fuente es una lista de textos, no vacía.") + if etiquetas is None and ("buscar_en_texto" in resultado or any("alias" in v for v in resultado.get("valores", ()))): + raise CatalogoInvalido(f"{resultado_id}: alias y buscar_en_texto solo sirven con etiquetas_fuente.") + if etiquetas is not None and resultado.get("tipo_valor") not in ("codigo", "numero", "fecha", "texto"): + raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo {resultado.get('tipo_valor')} no se extrae de texto.") + if resultado.get("buscar_en_texto") and resultado.get("tipo_valor") != "codigo": + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo se busca como mención en el texto.") + de: dict[str, str] = {} + for valor in resultado.get("valores", ()): + for forma in (valor.get("etiqueta", ""), *valor.get("alias", ())): + clave = " ".join(fold(forma).split()) + if de.get(clave, valor["valor"]) != valor["valor"]: + raise CatalogoInvalido( + f"{resultado_id}: {forma!r} se escribe igual para {de[clave]!r} y {valor['valor']!r}." + ) + de[clave] = valor["valor"] + + def _leer(ruta: Path) -> dict: return tomllib.loads(Path(ruta).read_text(encoding="utf-8")) diff --git a/webapi/orchestration/silver/cama.py b/webapi/orchestration/silver/cama.py index e81acba..4716e56 100644 --- a/webapi/orchestration/silver/cama.py +++ b/webapi/orchestration/silver/cama.py @@ -7,6 +7,7 @@ derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`). from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad +from webapi.orchestration.silver.extracted import DesdeTexto from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre @@ -23,6 +24,23 @@ def _biopsia_que_pasa(fila) -> bool: return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None +# Results read from text, with how the catalog says each is printed (`etiquetas_fuente`, `alias`): the +# radiologist's interpretation, the pathology report's text layer, and the note's diagnosis and prognosis. +DE_LA_INTERPRETACION = DesdeTexto( + "cama", ("mastografia.densidad", "mastografia.tamano_lesion_mm"), texto=lambda f: f.mast_interpretacion, +) +DEL_REPORTE_DE_PATOLOGIA = DesdeTexto( + "cama", + ("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno", + "biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct", + "biopsia.her2", "biopsia.ki67_pct"), + texto=lambda f: f.bx_pdf_blob, +) +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), +) + DESDE_STAGING = ( DeStaging( Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma", @@ -33,14 +51,17 @@ 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,), - resultados={"mast_birads": "mastografia.birads"}, + derivadas=DE_LA_INTERPRETACION.derivadas, + resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados}, + fuentes=DE_LA_INTERPRETACION.fuentes, ), 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, hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte", - resultados={"bx_grado_histologico": "biopsia.grado"}),), + resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),), ), orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES), - nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES), + nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA), ) diff --git a/webapi/orchestration/silver/extracted.py b/webapi/orchestration/silver/extracted.py new file mode 100644 index 0000000..dee3604 --- /dev/null +++ b/webapi/orchestration/silver/extracted.py @@ -0,0 +1,119 @@ +"""Results of the catalog read from a staging row's text: a report's interpretation, a note, a PDF's text layer. + +The catalog says how each result is printed (`etiquetas_fuente`, each value's `alias`; +`reference.catalogs.resultados_extraibles`); `DesdeTexto` turns that into Extraction's field specs and into the +derived columns, results and sources of a `DeStaging`. A coded value comes out as its `valor_id` when one of its +spellings matches, and always with what was read as `valor_fuente`: a spelling the catalog doesn't know yet stays +stored as text, counted as out of catalog by the silver check, and becomes a code on the next load after its alias +is added. Nothing extracted is written anywhere but silver's two tables. +""" + +from collections.abc import Callable +from dataclasses import dataclass, field +from functools import lru_cache + +from extraction import BBox, ExtractionError, FieldKind, FieldSpec, Line, read_document +from extraction.nlp.extractors import RecordExtractor, SegmentLine + +from webapi.orchestration.reference.catalogs import ResultadoExtraible, resultados_extraibles + +# A value read after a caption, kept as its source when the catalog doesn't know it: enough to recognize it. +LARGO_DE_FUENTE = 120 +TIPOS = {"codigo": FieldKind.CHOICE, "numero": FieldKind.DECIMAL, "fecha": FieldKind.DATE, "texto": FieldKind.TEXT} +SUFIJO_DE_TEXTO = "#texto" # the plain-text twin of a coded field: what follows its caption, matched or not + + +def especificaciones(resultado: ResultadoExtraible) -> tuple[FieldSpec, ...]: + """Extraction's fields for one result: the result itself and, if coded, the text after its caption.""" + choices = {forma: valor for valor, formas in resultado.alias.items() for forma in formas} + campo = FieldSpec( + resultado.resultado_id, TIPOS[resultado.tipo_valor], labels=resultado.etiquetas_fuente, + choices=choices, scan_free_text=resultado.buscar_en_texto, + ) + if resultado.tipo_valor != "codigo": + return (campo,) + return campo, FieldSpec(resultado.resultado_id + SUFIJO_DE_TEXTO, FieldKind.TEXT, labels=resultado.etiquetas_fuente) + + +def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]: + """A plain text as the lines of one page, as a reader would give them.""" + renglones = [r for r in texto.splitlines() if r.strip()] + alto = 1 / max(len(renglones), 1) + return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)] + + +def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]: + """The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines.""" + try: + documento = read_document("documento.pdf", contenido, ocr_mode="never") + except ExtractionError: + return [] + return [SegmentLine(documento.name, p.number, linea) for p in documento.pages for linea in p.lines] + + +@dataclass(frozen=True) +class DesdeTexto: + """Catalog results read from what `texto` gives for a row: a text, a PDF's bytes, or nothing. + + `derivadas`, `resultados` and `fuentes` go into the `DeStaging` (or its `Hija`) as they are. The row is read + once for all its results. + """ + + proyecto: str + resultado_ids: tuple[str, ...] + texto: Callable[[object], str | bytes | None] + _extraer: Callable = field(init=False, repr=False, compare=False) + + def __post_init__(self): + extraibles = resultados_extraibles(self.proyecto) + faltan = [r for r in self.resultado_ids if r not in extraibles] + if faltan: + raise ValueError(f"Sin etiquetas_fuente en el catálogo de {self.proyecto}: {', '.join(faltan)}.") + tipos = {r: extraibles[r].tipo_valor for r in self.resultado_ids} + extractor = RecordExtractor([e for r in self.resultado_ids for e in especificaciones(extraibles[r])]) + + @lru_cache(maxsize=256) + def extraer(contenido: str | bytes) -> dict[str, tuple]: + lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido) + leidos = extractor.extract(lineas) + return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos} + + object.__setattr__(self, "_extraer", extraer) + + def leer(self, fila) -> dict[str, tuple]: + """`resultado_id` -> (value, source) read from the row; (None, None) when it isn't there.""" + contenido = self.texto(fila) + if not contenido or (isinstance(contenido, str) and not contenido.strip()): + return dict.fromkeys(self.resultado_ids, (None, None)) + return self._extraer(contenido) + + @property + def derivadas(self) -> dict[str, Callable]: + columnas = {} + for r in self.resultado_ids: + columnas[_columna(r)] = lambda f, r=r: self.leer(f)[r][0] + columnas[_columna(r) + "_fuente"] = lambda f, r=r: self.leer(f)[r][1] + return columnas + + @property + def resultados(self) -> dict[str, str]: + return {_columna(r): r for r in self.resultado_ids} + + @property + def fuentes(self) -> dict[str, str]: + return {_columna(r): _columna(r) + "_fuente" for r in self.resultado_ids} + + +def _columna(resultado_id: str) -> str: + return "extraido:" + resultado_id + + +def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple: + """A coded value with the spelling it matched, or, unmatched, with what followed its caption; others as read.""" + if tipo_valor != "codigo": + return (None, None) if leido is None else (leido.value, None) + if leido is not None: + return leido.value, leido.raw + if texto is not None and str(texto.value).strip(): + return None, str(texto.value).strip()[:LARGO_DE_FUENTE] + return None, None diff --git a/webapi/orchestration/silver/orders_and_notes.py b/webapi/orchestration/silver/orders_and_notes.py index f7ecde6..3c20ba5 100644 --- a/webapi/orchestration/silver/orders_and_notes.py +++ b/webapi/orchestration/silver/orders_and_notes.py @@ -9,11 +9,13 @@ da sus tablas y su catálogo de especialidades. Es la normalización que hacían como llegó; - el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`; - el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b), - sin normalizarlos (I-K61). + sin normalizarlos (I-K61); +- the catalog results a project reads from the note's texts (`extraidos`, CaMa's clinical stage). """ from collections.abc import Collection, Mapping +from webapi.orchestration.silver.extracted import DesdeTexto from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio from webapi.orchestration.silver.procedures import DeStaging @@ -52,22 +54,26 @@ def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collectio def nota_medica( - staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False + staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False, + extraidos: DesdeTexto | None = None, ) -> DeStaging: textos = { "motivo": lambda f: texto_limpio(f.nm_motivo_consulta), "diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto), } if con_textos else {} + leidos = extraidos.derivadas if extraidos else {} return DeStaging( staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha", columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional) derivadas={ "cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos, + **leidos, }, resultados={ "cie_codigo": "nota_medica.diagnostico", "especialidad": "nota_medica.especialidad", **({f: f"nota_medica.{f}" for f in textos}), + **(extraidos.resultados if extraidos else {}), }, - fuentes={"especialidad": "especialidad_fuente"}, + fuentes={"especialidad": "especialidad_fuente", **(extraidos.fuentes if extraidos else {})}, ) -- 2.53.0 From f183e495fb2696674eab0a0c5017a158c29ae5b5 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 12:07:58 -0600 Subject: [PATCH 15/24] A timeline stratum read by the event cut-off, and labels for a timeline stratum's values How: `linea_de_tiempo_al_corte` is `linea_de_tiempo_al_inicio_del_periodo` with what the timeline held by the question's event cut-off (all of it without one) instead of before the period's start. FHIR's `_label` reads a timeline stratum's labels from its `valores` entries and `resto_etiqueta`. Tests cover CaMa's tumour stratifiers: the facts dbt derives, the surrogate subtype's rules, CAMA_BIRADS_CANCER_INVASOR broken down by them, and the cut-off. Implications: a patient's characteristic learned after the fact that put her in the period (a cancer's stage or subtype, written after its biopsy) can stratify a measure, and stays reproducible through the cut-offs. CaMa publishes eight measures and five strata. --- tests/test_cama_stratifiers.py | 116 +++++++++++++++++++++++++++++++++ tests/test_fhir_measures.py | 2 +- tests/test_orquestacion_oro.py | 8 +-- webapi/fhir/measures.py | 10 ++- webapi/metrics.py | 15 ++++- 5 files changed, 141 insertions(+), 10 deletions(-) create mode 100644 tests/test_cama_stratifiers.py diff --git a/tests/test_cama_stratifiers.py b/tests/test_cama_stratifiers.py new file mode 100644 index 0000000..219a318 --- /dev/null +++ b/tests/test_cama_stratifiers.py @@ -0,0 +1,116 @@ +"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata. +dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as +timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the +labels a timeline stratum's values carry into FHIR. + +Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database +(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on +2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA. +""" + +import os +from dataclasses import replace +from datetime import date +from pathlib import Path + +import pytest +from conftest import base_de +from sqlalchemy import text +from webapi.compositions import answer_composition, composition_definitions +from webapi.fhir.measures import _label +from webapi.metrics import Question + +URL = "cama/CAMA_BIRADS_CANCER_INVASOR" +UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture +def base(tmp_path, sin_supresion, manifest): + base = base_de("cama", tmp_path) + base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True) + yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True)) + base.motor.dispose() + + +def answered(base, manifest, period: str, event_cutoff: date | None = None): + d = base.dominio + definition = composition_definitions(manifest)[URL] + return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff), + parameters=d.def_parametro_repository, periods=d.dim_periodo_repository, + history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True) + + +def stratifiers(base) -> set[str]: + with base.motor.connect() as con: + return set(con.execute(text("select tipo from cama_estratificadores")).scalars()) + + +def test_the_stratifiers_come_from_h003_s_reports(base): + """Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology + report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in + `vars.cama.estratos` or a timeline `tipo` it reads changes.""" + assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"} + + +def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest): + """Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to + it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the + category or a stratum's values drift.""" + assert answered(base, manifest, "2025-S1").categories == {} + result = answered(base, manifest, "2025-S2") + assert result.categories == {"B4A": 1} + assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}}, + "etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}}, + "tamano": {"T1": {"B4A": 1}}} + + +def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest): + """Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype + (report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's + start (H-003 would have nothing) or ignores the cut-off (she'd have her stage).""" + strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata + assert strata["clasificacion"] == {"HER2": {"B4A": 1}} + assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}} + + +SUBTIPOS = [ + ({"her2": "H3"}, "subtipo_her2"), + ({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"), + ({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"), + ({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"), + ({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"), + ({"her2": "H0", "ki67_pct": None}, None), + ({"her2": "H2"}, None), +] + + +@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS) +def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo): + """Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both + receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and + progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's + report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise. + Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes.""" + valores = {"receptor_progesterona": "POSITIVO", **cambios} + with base.motor.begin() as con: + for nombre, valor in valores.items(): + columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id" + con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"), + {"v": valor, "r": f"biopsia.{nombre}"}) + assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set()) + + +def test_a_timeline_stratum_s_values_carry_their_labels(): + """Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from + `resto_etiqueta`. Fails if `_label` reads labels only from a map.""" + spec = {"valores": [{"valor": "II", "etiqueta": "Estadio II", "si": []}], "resto": "SIN_DATO", + "resto_etiqueta": "Sin dato"} + assert (_label(spec, "II"), _label(spec, "SIN_DATO"), _label(spec, "IV")) == ("Estadio II", "Sin dato", None) diff --git a/tests/test_fhir_measures.py b/tests/test_fhir_measures.py index f842703..c601cb6 100644 --- a/tests/test_fhir_measures.py +++ b/tests/test_fhir_measures.py @@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client): with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape.""" domain, client = domain_client measures = valid(client.get(f"/{domain}/fhir/Measure").get_json()) - assert measures["total"] == 7 + assert measures["total"] == {"cacu": 7, "cama": 8}[domain] for item in measures["entry"]: response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1") assert response.status_code in (200, 409), response.get_json() diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index dee138d..2a6698c 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.run("definitions")["definitions"] - # CaCu: three strata and its seven measures; CaMa: its seven measures, without strata; TEA: the age group and its - # ten measures. - assert resumen["definitions"] == {"cacu": 10, "cama": 7, "tea": 11}[base.proyecto] + # CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers and its eight measures; + # TEA: the age group and its ten measures. + assert resumen["definitions"] == {"cacu": 10, "cama": 13, "tea": 11}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 7, "tea": 10}[base.proyecto] + assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto] assert base.run("definitions")["definitions"]["borradas"] == 0 diff --git a/webapi/fhir/measures.py b/webapi/fhir/measures.py index 0cd6e11..2981340 100644 --- a/webapi/fhir/measures.py +++ b/webapi/fhir/measures.py @@ -120,9 +120,15 @@ def _proportion_cells(definition, counts: Counts, excluded: int | None = None) - def _label(spec: dict, value: str) -> str | None: - """A stratum value's label, when the stratum's `valores` maps values to labels.""" + """A stratum value's label: from `valores` as a map of values to labels, or as a list of entries with `etiqueta` + (a timeline stratum's), or `resto_etiqueta` for its `resto`.""" labels_of = spec.get("valores") - return labels_of.get(value) if isinstance(labels_of, dict) else None + if isinstance(labels_of, dict): + return labels_of.get(value) + if isinstance(labels_of, list): + found = [v.get("etiqueta") for v in labels_of if isinstance(v, dict) and v.get("valor") == value] + return found[0] if found else (spec.get("resto_etiqueta") if value == spec.get("resto") else None) + return None def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict: diff --git a/webapi/metrics.py b/webapi/metrics.py index efb8c65..d015d10 100644 --- a/webapi/metrics.py +++ b/webapi/metrics.py @@ -46,6 +46,7 @@ TOTAL = "total" NO_DATA = "sin_dato" AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo" TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" +TIMELINE_BY_CUTOFF = "linea_de_tiempo_al_corte" OF_THE_CHOSEN = "del_elegido" COLUMN = "columna" STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo" @@ -129,6 +130,9 @@ class Stratum: `fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a timeline `tipo` to whether there was one; + - `linea_de_tiempo_al_corte`: the same, with what the timeline held by the question's event cut-off (all of it + without one) instead of before the period's start: a patient's characteristic learned after the fact that + put her in the period, such as the stage of a cancer whose biopsy the period counts; - `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category; - `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null. """ @@ -143,7 +147,7 @@ class Stratum: @classmethod def of(cls, name: str, spec: dict) -> "Stratum": - if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN, COLUMN): + if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, TIMELINE_BY_CUTOFF, OF_THE_CHOSEN, COLUMN): raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered") return cls(name, spec["tipo"], spec) @@ -411,7 +415,8 @@ class MeasureQueries: return joined def _timeline(self, stratum: Stratum): - """Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start. + """Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start + (or, for `linea_de_tiempo_al_corte`, by the event cut-off). Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped by on every engine. @@ -422,7 +427,11 @@ class MeasureQueries: line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"), column("conocida_en", FechaHoraUTC)) period = self.periods.alias(f"periodo_{stratum.name}") - conditions = [line.c.tipo.in_(kinds), line.c.fecha < period.c.inicio] + conditions = [line.c.tipo.in_(kinds)] + if stratum.kind == TIMELINE_AT_PERIOD_START: + conditions.append(line.c.fecha < period.c.inicio) + elif self.q.event_cutoff is not None: + conditions.append(line.c.fecha <= self.q.event_cutoff.isoformat()) if self.q.knowledge_cutoff is not None: conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff) had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds)) -- 2.53.0 From 113b792a7b8115514ae5c3482c31543c5055b299 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 15:23:45 -0600 Subject: [PATCH 16/24] The import's catalog matching and commit read the WebApi's catalog, silver batch and table maps; add_resultado moves here How: `catalog_matching`, `catalog_commit_service` and the imports blueprint import `Catalogo`, `catalogo_desde_toml`, `ruta_de_catalogo`, `CatalogoInvalido`, `LotePlata`, `valor_de_observacion` and `tablas_de` from `webapi.orchestration`; the commit writes through `carga_repository.save_load` and `catalog_repository.sync`. `add_resultado` and its tests come over unchanged from the indicator kit. Implications: the import path no longer needs the indicator kit, which isn't a dependency. --- tests/test_catalog_commit_service.py | 6 +- tests/test_catalog_matching.py | 6 +- tests/test_catalogo_add_resultado.py | 77 +++++++++++++++++++ tests/test_document_sql_source.py | 2 +- webapi/blueprints/imports.py | 2 +- webapi/imports/schemas/catalog_matching.py | 4 +- .../services/catalog_commit_service.py | 12 +-- webapi/orchestration/reference/catalogs.py | 34 ++++++++ 8 files changed, 127 insertions(+), 16 deletions(-) create mode 100644 tests/test_catalogo_add_resultado.py diff --git a/tests/test_catalog_commit_service.py b/tests/test_catalog_commit_service.py index 1604242..edd0473 100644 --- a/tests/test_catalog_commit_service.py +++ b/tests/test_catalog_commit_service.py @@ -9,8 +9,8 @@ from datetime import date import pytest from sqlmodel import select -from indicadores_kit.registry import catalogos -from indicadores_kit.tablas import tablas_de +from webapi.orchestration.reference import catalogs as catalogos +from webapi.orchestration.tables import tablas_de from extraction import ExtractedRecord from extraction.nlp import DiscoveredField, Evidence @@ -27,7 +27,7 @@ def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord: @pytest.fixture def cacu_catalog(tmp_path, monkeypatch): - """`add_resultado`/`sincronizar` write real rows and a real file: + """`add_resultado`/`sync` write real rows and a real file: kept off the checked-in `cacu.toml` and off any other domain's data.""" monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path) (tmp_path / "cacu.toml").write_text( diff --git a/tests/test_catalog_matching.py b/tests/test_catalog_matching.py index 09df815..5ce176f 100644 --- a/tests/test_catalog_matching.py +++ b/tests/test_catalog_matching.py @@ -6,9 +6,9 @@ and silently drops its value instead. from datetime import date import pytest -from indicadores_kit.registry import catalogos -from indicadores_kit.registry.catalogos import Catalogo -from indicadores_kit.tablas import tablas_de +from webapi.orchestration.reference import catalogs as catalogos +from webapi.orchestration.reference.catalogs import Catalogo +from webapi.orchestration.tables import tablas_de from extraction.nlp import DiscoveredField, Evidence from webapi.imports.schemas.catalog_matching import match_or_mint diff --git a/tests/test_catalogo_add_resultado.py b/tests/test_catalogo_add_resultado.py new file mode 100644 index 0000000..9b92dc8 --- /dev/null +++ b/tests/test_catalogo_add_resultado.py @@ -0,0 +1,77 @@ +"""`add_resultado`: adds a new field to a project's catalog TOML file on +disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a +field no catalog entry matches closely enough. Each test pins down one +rule of that append; fails if any of them regresses into losing data or +duplicating an entry that's already there. +""" +import pytest + +from webapi.orchestration.reference import catalogs as catalogos + + +@pytest.fixture +def catalogo_file(tmp_path, monkeypatch): + monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path) + + def escribir(contenido: str) -> None: + (tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8") + + return escribir + + +def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file): + catalogo_file('[citologia]\netiqueta = "Citología"\n') + + resultado_id = catalogos.add_resultado( + "prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto" + ) + + assert resultado_id == "citologia.nuevo_campo" + leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba")) + assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives + assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"} + + +def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file): + catalogo_file("") + + catalogos.add_resultado( + "prueba", + estudio_id="documento_externo", + nombre="campo", + etiqueta="Campo", + tipo_valor="fecha", + estudio_etiqueta="Documento externo", + ) + + leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba")) + assert leido["documento_externo"]["etiqueta"] == "Documento externo" + assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha" + + +def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file): + """Fails if re-discovering the same field on a later row duplicates it + or rewrites what a human already edited in the file.""" + original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n' + catalogo_file(original) + + catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero") + + assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original + + +def test_an_unknown_tipo_valor_is_rejected(catalogo_file): + catalogo_file("") + with pytest.raises(catalogos.CatalogoInvalido): + catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe") + + +def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file): + """Fails if a caption or label read off a document (arbitrary text) + produces TOML the next `catalogo_desde_toml` can't parse.""" + catalogo_file("") + catalogos.add_resultado( + "prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto" + ) + leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba")) + assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"' diff --git a/tests/test_document_sql_source.py b/tests/test_document_sql_source.py index 56b8132..debe4ec 100644 --- a/tests/test_document_sql_source.py +++ b/tests/test_document_sql_source.py @@ -131,7 +131,7 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl from sqlalchemy import create_engine, text as sa_text from sqlmodel import select - from indicadores_kit.registry import catalogos + from webapi.orchestration.reference import catalogs as catalogos from core.cacu.paciente.model import Paciente from persistance.cacu import carga_repository, paciente_repository diff --git a/webapi/blueprints/imports.py b/webapi/blueprints/imports.py index e3ded7c..8cc8f40 100644 --- a/webapi/blueprints/imports.py +++ b/webapi/blueprints/imports.py @@ -8,11 +8,11 @@ from sqlalchemy.exc import SQLAlchemyError from extraction import BBox, ExtractionError from extraction.readers import reader_for -from indicadores_kit.registry.catalogos import CatalogoInvalido from webapi.imports import audit as import_audit from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename from webapi.imports.connectors.base import decode_file from webapi.imports.connectors.pdf import PdfConnector +from webapi.orchestration.reference.catalogs import CatalogoInvalido from webapi.imports.connectors.sql import SqlConnector from webapi.imports.connectors.tabular import FileConnector from webapi.imports.schemas.registry import ENTITY_REGISTRY diff --git a/webapi/imports/schemas/catalog_matching.py b/webapi/imports/schemas/catalog_matching.py index 76f8047..b97c8f6 100644 --- a/webapi/imports/schemas/catalog_matching.py +++ b/webapi/imports/schemas/catalog_matching.py @@ -16,8 +16,8 @@ from rapidfuzz import fuzz, process from extraction.nlp import DiscoveredField from extraction.nlp.text import find_date, fold -from indicadores_kit.plata.procedimiento import valor_de_observacion -from indicadores_kit.registry.catalogos import Catalogo, add_resultado +from webapi.orchestration.reference.catalogs import Catalogo, add_resultado +from webapi.orchestration.silver.procedures import valor_de_observacion # `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores # two short, unrelated captions that merely share common words ("de", "del") diff --git a/webapi/imports/services/catalog_commit_service.py b/webapi/imports/services/catalog_commit_service.py index 0fca715..62189bc 100644 --- a/webapi/imports/services/catalog_commit_service.py +++ b/webapi/imports/services/catalog_commit_service.py @@ -11,7 +11,7 @@ the import report lists them (`webapi.imports.audit`). There is no staging row for these — the whole point is a field outside today's structured schemas — so this bypasses `DESDE_STAGING` and writes straight through the domain's existing `carga_repository`, the same one -`webapi.orquestacion`'s `cargar` step uses for staging-derived batches. +`webapi.orchestration`'s `load` step uses for staging-derived batches. Marked clearly apart from every staging-derived procedimiento: `fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real @@ -27,11 +27,11 @@ from dataclasses import dataclass from importlib import import_module from extraction import ExtractedRecord -from indicadores_kit.plata.procedimiento import LotePlata -from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo -from indicadores_kit.tablas import tablas_de from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint +from webapi.orchestration.reference.catalogs import Catalogo, catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.silver.procedures import LotePlata +from webapi.orchestration.tables import tablas_de FUENTE_CATALOGO_ABIERTO = "catalogo_abierto" @@ -93,7 +93,7 @@ def commit_discovered_fields( if procedures: _sync_catalog(dominio, proyecto, tablas) - dominio.carga_repository.guardar_carga( + dominio.carga_repository.save_load( fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {}) ) return result @@ -120,4 +120,4 @@ def _sync_catalog(dominio, proyecto: str, tablas) -> None: runs: `procedimiento.estudio_id` and `observacion`'s catalog both need the matching `cat_estudio`/`cat_resultado` row to already be there.""" catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas) - dominio.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores) + dominio.catalog_repository.sync(catalogo.estudios, catalogo.resultados, catalogo.valores) diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py index 3a59dc3..2cf7b86 100644 --- a/webapi/orchestration/reference/catalogs.py +++ b/webapi/orchestration/reference/catalogs.py @@ -79,6 +79,40 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo: return Catalogo(estudios, resultados, valores) +def add_resultado( + proyecto: str, *, estudio_id: str, nombre: str, etiqueta: str, tipo_valor: str, estudio_etiqueta: str | None = None +) -> str: + """Appends a new `resultado_id` to the project's TOML (not to the + database): a `[estudio.resultados.nombre]` table, and the `[estudio]` + table too if it didn't exist yet. The file stays the source: the next + `catalogo_desde_toml` already brings it, and whoever syncs the table + writes it. + + Idempotent: if the resultado is already in the file, nothing is + written and its `resultado_id` is returned as is. `nombre` must be a + valid TOML key (whoever discovers the field builds it, e.g. from a + slug of the text found). + """ + if tipo_valor not in TIPOS_DE_VALOR: + raise CatalogoInvalido(f"{estudio_id}.{nombre}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}.") + ruta = ruta_de_catalogo(proyecto) + existentes = _leer(ruta) + resultado_id = f"{estudio_id}.{nombre}" + if estudio_id in existentes and nombre in existentes[estudio_id].get("resultados", {}): + return resultado_id + blocks = [] + if estudio_id not in existentes: + blocks.append(f'\n[{estudio_id}]\netiqueta = "{_escape(estudio_etiqueta or estudio_id)}"\n') + blocks.append(f'\n[{estudio_id}.resultados.{nombre}]\netiqueta = "{_escape(etiqueta)}"\ntipo_valor = "{tipo_valor}"\n') + with Path(ruta).open("a", encoding="utf-8") as archivo: + archivo.write("".join(blocks)) + return resultado_id + + +def _escape(text: str) -> str: + return text.replace("\\", "\\\\").replace('"', '\\"') + + def codigos_hospital(proyecto: str) -> dict[str, str]: """Código del hospital -> `estudio_id`, del catálogo del proyecto. -- 2.53.0 From cea74e1566b01d11c45075e1beb3b1679b4995be Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 15:24:02 -0600 Subject: [PATCH 17/24] uv.lock with models' dependencies on dev How: `uv lock` after the rebase onto dev, whose models adds the notebook and governance requirements. Implications: `uv sync` installs what the governance routes import (`models.io.storage.build_file` and the notebook runner). --- uv.lock | 716 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 711 insertions(+), 5 deletions(-) diff --git a/uv.lock b/uv.lock index a025434..f42e8a3 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -236,6 +236,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fe/ec/c672e72dd66b633fb65e6011bc7c30c128e090364f8497660b7869e10123/apache_hamilton-1.90.0-py3-none-any.whl", hash = "sha256:95e356f7cb23e1a10d44fd0cf5efd3fb36a077b4ccb673950c92005bfdec2ff7", size = 475199, upload-time = "2026-04-25T18:45:17.514Z" }, ] +[[package]] +name = "appnope" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/11/f7/a82489c2b6ebe32d3e2831895ae19c77861f0eadf3bb16034484d965dbb2/appnope-1.0.0.tar.gz", hash = "sha256:685db59cb6043c3c2e528adc0b3bce3a5f8d09bcf7492c6ea650d1b7421f3c49", size = 5454, upload-time = "2026-08-20T21:36:13.748Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/c7/6b687cb0f83d2a51017d47953f2ee430ffad6fec2a8ebc964e0718a33eb1/appnope-1.0.0-py3-none-any.whl", hash = "sha256:6fe0c04218aab65c54c4ff81638cdbf848d89f5653b74d68638a137f200dd16e", size = 4158, upload-time = "2026-08-20T21:36:12.444Z" }, +] + +[[package]] +name = "asttokens" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" }, +] + [[package]] name = "attrs" version = "26.1.0" @@ -245,6 +263,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "beautifulsoup4" +version = "4.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "soupsieve" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/c6/92fcd42f1ba33e1184263f25bfabf3d27c383410470f169e4b8163bf9c17/beautifulsoup4-4.15.0-py3-none-any.whl", hash = "sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9", size = 109924, upload-time = "2026-06-07T16:44:21.566Z" }, +] + +[[package]] +name = "bleach" +version = "6.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "webencodings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/3c/e12ac860709702bd5ebeb9b56a4fe334f1001246ee1b8f2b7ee28912df7d/bleach-6.4.0.tar.gz", hash = "sha256:4202482733d85cedd04e59fcb2f89f4e4c7c385a78d3c3c23c30446843a37452", size = 204857, upload-time = "2026-06-05T13:01:13.734Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/9d/40b6267367182187139a4000b82a3b287d84d745bccd808e75d916920e9d/bleach-6.4.0-py3-none-any.whl", hash = "sha256:4b6b6a54fff2e69a3dde9d21cc6301220bee3c3cb792187d11403fd795031081", size = 165109, upload-time = "2026-06-05T13:01:12.504Z" }, +] + +[package.optional-dependencies] +css = [ + { name = "tinycss2" }, +] + [[package]] name = "blinker" version = "1.9.0" @@ -515,6 +563,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "comm" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4c/13/7d740c5849255756bc17888787313b61fd38a0a8304fc4f073dfc46122aa/comm-0.2.3.tar.gz", hash = "sha256:2dc8048c10962d55d7ad693be1e7045d891b7ce8d999c97963a5e3e99c055971", size = 6319, upload-time = "2025-07-25T14:02:04.452Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" }, +] + [[package]] name = "contourpy" version = "1.4.0" @@ -688,6 +745,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/c1/631160994379b7baa4605c2a4ffa6bca374b3ef73213e43b2dfcbd6c2bb9/databricks_sdk-0.156.0-py3-none-any.whl", hash = "sha256:1aa5e0cabfc5626a886c9fa42bc1ce14a6166e8167ef34026dcc41f3c99e2a5a", size = 1112276, upload-time = "2026-10-22T04:33:33.024Z" }, ] +[[package]] +name = "debugpy" +version = "1.8.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/44/9d/3cb6693342acf96802dba89934a5b8da43c201d764ebd1f2c0514a3d42bd/debugpy-1.8.22.tar.gz", hash = "sha256:e489c7268e1c7b41e13b438d9c533d2a7af73fb59bf8cd30fead8286c1c39c4e", size = 1710877, upload-time = "2026-09-15T21:44:02.578Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/21/5c7f5c66eaeee57c9dadb0bbff22efddc8d99cdbd3d036c806175f1828cc/debugpy-1.8.22-cp312-cp312-macosx_15_0_universal2.whl", hash = "sha256:4ad076f4f66cb8acb79e4384d48b1ea60a0b1957aa0b1112d4887ea3a4df60e0", size = 2499375, upload-time = "2026-09-15T21:44:18.478Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ec/7389798843643ea5bc6a08480ba1b855377c70e2ed90189c0a03594e401e/debugpy-1.8.22-cp312-cp312-manylinux_2_34_x86_64.whl", hash = "sha256:8a697acec45dbc70d17fb5d9f4f61989fc294d273c69de487fd10cb35fdd75eb", size = 4000941, upload-time = "2026-09-15T21:44:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/20/f4/64ce7a2499550929e08654360b270409eeda3e321b7c27027d9c919aa36b/debugpy-1.8.22-cp312-cp312-win32.whl", hash = "sha256:12bc7f368182b517cf26c76a2393fff65354e365fa1552b6241e66edff17997b", size = 5359040, upload-time = "2026-09-15T21:44:22.218Z" }, + { url = "https://files.pythonhosted.org/packages/4b/fe/e7d3b72874cdd327bda295d1995a01e426857ae9cbaaba74fd997bc3afbc/debugpy-1.8.22-cp312-cp312-win_amd64.whl", hash = "sha256:371a4ba4a5975eb958393903f3254cf983da7b1c7c178b3f987ee427f42515e3", size = 5398304, upload-time = "2026-09-15T21:44:24.119Z" }, + { url = "https://files.pythonhosted.org/packages/6b/f4/fee6d40f5865aa84e1100c9df1a0f2cf8991776b61f11f433ff277df4415/debugpy-1.8.22-cp313-cp313-macosx_15_0_universal2.whl", hash = "sha256:c21dd7e1ec22556bb41dc3bf6b86c603e440ec889c4acb27d7206354b2106c54", size = 2493531, upload-time = "2026-09-15T21:44:25.835Z" }, + { url = "https://files.pythonhosted.org/packages/bc/4f/8df91270afbf61fc5ab202951f28451194a7eb093704b26da11cb0ecd308/debugpy-1.8.22-cp313-cp313-manylinux_2_34_x86_64.whl", hash = "sha256:c1ffb9953708b648ecf6acd2e5ad2c002bf68785ed618197dd4463a2a7226f39", size = 3994351, upload-time = "2026-09-15T21:44:27.31Z" }, + { url = "https://files.pythonhosted.org/packages/4f/11/2e34a4f21d6155b0c58003fd6fca9819df7d6fe7d7acd83b146b648a57ee/debugpy-1.8.22-cp313-cp313-win32.whl", hash = "sha256:ba810a66b437e3c43ca0ce0892404f010338286263ca8e5108442d76a9485337", size = 5359071, upload-time = "2026-09-15T21:44:29.064Z" }, + { url = "https://files.pythonhosted.org/packages/d0/f5/c2b3e8260388d7b76bc4e5a3a29648a0ca47dca6a2721d6549ff2d944eee/debugpy-1.8.22-cp313-cp313-win_amd64.whl", hash = "sha256:f49b1d6cecf326b63c06d7f517e4a6642777f758c58cb799e7bc5a6dd74721c2", size = 5400362, upload-time = "2026-09-15T21:44:30.857Z" }, + { url = "https://files.pythonhosted.org/packages/ea/95/d97240bb68b86db8d0a07602be068aae9e50f17063d696a4c6f619975311/debugpy-1.8.22-cp314-cp314-macosx_15_0_universal2.whl", hash = "sha256:e6744ac1850c73c2ba7b29a126cf9ab74efd1831190720e8fee17ef5389c8f5d", size = 2493148, upload-time = "2026-09-15T21:44:32.518Z" }, + { url = "https://files.pythonhosted.org/packages/70/9e/994fe1fb23dd4a5a8d059a0dc95da4b0821907200a61c2d5a4fdc21b6cf8/debugpy-1.8.22-cp314-cp314-manylinux_2_34_x86_64.whl", hash = "sha256:0c1104233340196e5cbf5514e7dfdbb98968e730cfd7fdd6f3d72a082be838a9", size = 3961025, upload-time = "2026-09-15T21:44:34.387Z" }, + { url = "https://files.pythonhosted.org/packages/37/e0/66319918883cf6dd6dea3805210c3cafd9e65dfaa6f8b852482cff10a026/debugpy-1.8.22-cp314-cp314-win32.whl", hash = "sha256:feea785c7bbeb8cfd5b01a63f9061c899dc468c8be81671141a29305774fa294", size = 5359408, upload-time = "2026-09-15T21:44:36.128Z" }, + { url = "https://files.pythonhosted.org/packages/94/53/5b4d91f7fffb9393ac907133201d1da0c070d57e463ee8e2ec1db3cb63b6/debugpy-1.8.22-cp314-cp314-win_amd64.whl", hash = "sha256:d593a330297332ec435f3965c448b6d500e03f33675cf2063178bc76377a788e", size = 5397429, upload-time = "2026-09-15T21:44:38.429Z" }, + { url = "https://files.pythonhosted.org/packages/24/71/580df4aed96c9b23c9cbb049907d8ac1347050afdb8f450df20649d51578/debugpy-1.8.22-cp315-cp315-macosx_15_0_universal2.whl", hash = "sha256:a9eca6ab09a61534e923064400081e016f7e1d8430cc6e8b7a9cecd2f59e2b07", size = 2493380, upload-time = "2026-09-15T21:44:40.074Z" }, + { url = "https://files.pythonhosted.org/packages/b0/10/a323945b0966e560c40fe48470d2847bfc7692a8f550d7086e9a28f5b623/debugpy-1.8.22-cp315-cp315-manylinux_2_34_x86_64.whl", hash = "sha256:b7dbde1fb822d100802d505b2aed6d0813b1a0a2015d495cb8798b2215d5d1e5", size = 3975456, upload-time = "2026-09-15T21:44:41.623Z" }, + { url = "https://files.pythonhosted.org/packages/ef/f9/4383635281999c3eaa44bf327de523ba42240b35eb87c1130adac4a829c6/debugpy-1.8.22-cp315-cp315-win32.whl", hash = "sha256:225d063f81708c2546999e7edfac0198b2d5c2f144797dc64858f867948633e0", size = 5359469, upload-time = "2026-09-15T21:44:43.234Z" }, + { url = "https://files.pythonhosted.org/packages/7b/14/4fe9f46a9c825c8cbc6dc4aebc2a885b0bceb37ce2a37699c170482e7a40/debugpy-1.8.22-cp315-cp315-win_amd64.whl", hash = "sha256:b17a4896520f1c6da09ce76ec8215df0b85b0b6f3617526a4c65c2315340875a", size = 5397869, upload-time = "2026-09-15T21:44:44.783Z" }, + { url = "https://files.pythonhosted.org/packages/56/3d/c7dc9f35bc9e22cdb53679f844bee40fd5cff871862f60595869a433400d/debugpy-1.8.22-py2.py3-none-any.whl", hash = "sha256:a9e9d3550e15ca479c59333e90845029190531f0cacfedab3b815a57bd913947", size = 5374857, upload-time = "2026-09-15T21:44:54.454Z" }, +] + [[package]] name = "decorator" version = "5.3.1" @@ -697,6 +779,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/05/7f/798705f5296a58ca505d600456748d1be48078eac8a7050d8a98bc9edb89/decorator-5.3.1-py3-none-any.whl", hash = "sha256:f47fe6fdbd2edd623ecfe36875d37aba411624e2670dd395dddae1358689bb3c", size = 10365, upload-time = "2026-05-18T06:03:26.517Z" }, ] +[[package]] +name = "defusedxml" +version = "0.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" }, +] + [[package]] name = "docker" version = "7.2.0" @@ -720,6 +811,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" }, ] +[[package]] +name = "executing" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/92/8a611141e42930c0f194f7504063ab87dfe970cf1a5af28e7703df448734/executing-2.3.0.tar.gz", hash = "sha256:15919cb5d667e5cb4e099511971d00d659573fff2dd5c4e6cd8b71636c7858d2", size = 1338003, upload-time = "2026-10-10T14:06:04.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/dd/8bc67e7d5ffc1d88aa5af511189dfb76dc4e1e5b808fab186146ef2663e5/executing-2.3.0-py3-none-any.whl", hash = "sha256:736e859c9f8701f11fcf516856f26f562e04776387824b43a35a1dfe21c84122", size = 29393, upload-time = "2026-10-10T14:06:02.777Z" }, +] + [[package]] name = "extraction" version = "0.1.0" @@ -768,6 +868,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/2a/101012d82931d9de3855384e1667e49c0e07a0048e3868f9fec1697293a9/fastapi-0.161.1-py3-none-any.whl", hash = "sha256:a1363080cf9aeedecd99f4e1a23669d7e77542227f6536f4d7bbd59f07ecaa94", size = 149049, upload-time = "2026-10-22T22:22:06.139Z" }, ] +[[package]] +name = "fastjsonschema" +version = "2.22.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/80/cc3c531dd70c8ffa1045aecf33c97c5581cc8fd0e824b3ecb2c1881550c1/fastjsonschema-2.22.3.tar.gz", hash = "sha256:8330c91b027dcf941efcb7b1f0998515ff95d177ea15bbabdfe8671965620901", size = 388854, upload-time = "2026-11-01T21:11:34.389Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/0d/6caab33488dc9d26440c24221fa610c7c8b83c30715ab45d31f0e004308e/fastjsonschema-2.22.3-py3-none-any.whl", hash = "sha256:f670b443830b75aca3f00b75949efa20f4b2a80302ec7a21505c28dd54cffd43", size = 28442, upload-time = "2026-11-01T21:11:29.306Z" }, +] + [[package]] name = "fhir-core" version = "1.1.12" @@ -1153,6 +1262,62 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "ipykernel" +version = "7.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "appnope", marker = "sys_platform == 'darwin'" }, + { name = "comm" }, + { name = "debugpy" }, + { name = "ipython" }, + { name = "jupyter-client" }, + { name = "jupyter-core" }, + { name = "matplotlib-inline" }, + { name = "nest-asyncio2" }, + { name = "packaging" }, + { name = "pyzmq" }, + { name = "tornado" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/05/e5499c8b762387d83926bf0389e8fff888c9bf6e7af30566a8527bc12f4a/ipykernel-7.4.0.tar.gz", hash = "sha256:4330114d22b9b33575b2c7c68753fc8faabbbcfbc60b0cdff9f14dd4ce63742f", size = 192731, upload-time = "2026-09-29T16:33:11.468Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/f8/8b5c10c7f36ab5a3b5c4703669e5b14e44e98782b58e535dd30670e8799a/ipykernel-7.4.0-py3-none-any.whl", hash = "sha256:a6757f790ddc5a6006b813d82da1a9dbb65b3a00f2b6607df776418c6566ec1c", size = 123184, upload-time = "2026-09-29T16:33:09.612Z" }, +] + +[[package]] +name = "ipython" +version = "9.18.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "psutil", marker = "sys_platform != 'android' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/38/04/0d945c72d5b77527273ecb4c66aa2436de7a3b3bbe3da345bf053232b886/ipython-9.18.1.tar.gz", hash = "sha256:6319c0f5372c196397899479e6db1783dd7937abae06815d1317e8d5d51aaaaf", size = 4437314, upload-time = "2026-11-02T09:19:55.55Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bb/1c/91da4a1c541b75e97eb99d09c6a9b0534de55bb4a466669d1170e39b915c/ipython-9.18.1-py3-none-any.whl", hash = "sha256:997ce9140d374531a61069c70c0f9ef299d6dd3559ea0f94b8af589726e3c1d5", size = 649819, upload-time = "2026-11-02T09:19:53.32Z" }, +] + +[[package]] +name = "ipython-pygments-lexers" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" }, +] + [[package]] name = "itsdangerous" version = "2.2.0" @@ -1162,6 +1327,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, ] +[[package]] +name = "jedi" +version = "0.20.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "parso" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/a4/4692ecd7fa700ac1066b1c1f6cadef60aa2e01e5e364710235137d823e0a/jedi-0.20.1.tar.gz", hash = "sha256:2f71208c3f9c1bca057c0e90d3f272aba44ace88fc4067d7587e9e069331b7e5", size = 3121738, upload-time = "2026-10-12T17:42:24.361Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/c7/71eb0d51cdcbb63b857c931aa4e9218b078b5d9f8ecd383b234f28fe7b0f/jedi-0.20.1-py2.py3-none-any.whl", hash = "sha256:0fb16d86c4a4c73c37ba518c77419975e30fcc620658a8d14fbb5720cdd34142", size = 4885980, upload-time = "2026-10-12T17:42:21.585Z" }, +] + [[package]] name = "jinja2" version = "3.1.6" @@ -1186,6 +1363,72 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + +[[package]] +name = "jupyter-client" +version = "8.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jupyter-core" }, + { name = "python-dateutil" }, + { name = "pyzmq" }, + { name = "tornado" }, + { name = "traitlets" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c5/2a/906772148a06e48885039e0250c340b770a55bbf37b08d6ee0449df369c3/jupyter_client-8.10.0.tar.gz", hash = "sha256:9f7116294dca55f1785be880057d44544db9b1567718d92cb33c58886afb9497", size = 360653, upload-time = "2026-08-28T12:17:10.854Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/88/7c548de1f6c2ade7c931a3282da73f9274fa6a1531091be682f89c85efb9/jupyter_client-8.10.0-py3-none-any.whl", hash = "sha256:5f73f24f22fa25192cfff6b23c051932a2473a797b05734aff495b392103e14e", size = 110184, upload-time = "2026-08-28T12:17:09.028Z" }, +] + +[[package]] +name = "jupyter-core" +version = "5.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "platformdirs" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/02/49/9d1284d0dc65e2c757b74c6687b6d319b02f822ad039e5c512df9194d9dd/jupyter_core-5.9.1.tar.gz", hash = "sha256:4d09aaff303b9566c3ce657f580bd089ff5c91f5f89cf7d8846c3cdf465b5508", size = 89814, upload-time = "2025-10-16T19:19:18.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/e7/80988e32bf6f73919a113473a604f5a8f09094de312b9d52b79c2df7612b/jupyter_core-5.9.1-py3-none-any.whl", hash = "sha256:ebf87fdc6073d142e114c72c9e29a9d7ca03fad818c5d300ce2adc1fb0743407", size = 29032, upload-time = "2025-10-16T19:19:16.783Z" }, +] + +[[package]] +name = "jupyterlab-pygments" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/90/51/9187be60d989df97f5f0aba133fa54e7300f17616e065d1ada7d7646b6d6/jupyterlab_pygments-0.3.0.tar.gz", hash = "sha256:721aca4d9029252b11cfa9d185e5b5af4d54772bb8072f9b7036f4170054d35d", size = 512900, upload-time = "2023-11-23T09:26:37.44Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/dd/ead9d8ea85bf202d90cc513b533f9c363121c7792674f78e0d8a854b63b4/jupyterlab_pygments-0.3.0-py3-none-any.whl", hash = "sha256:841a89020971da1d8693f1a99997aefc5dc424bb1b251fd6322462a1b8842780", size = 15884, upload-time = "2023-11-23T09:26:34.325Z" }, +] + [[package]] name = "kiwisolver" version = "1.5.1" @@ -1444,6 +1687,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/5a/9f440e7bec8b80d0af2a65d1165b2f4e718982dad785531f62255d9ff19b/matplotlib-3.11.2-cp315-cp315t-win_arm64.whl", hash = "sha256:d480038c83691532ed52ff3147db51fa902fc78cb2d8349993a1cdb684435bff", size = 9233946, upload-time = "2026-09-11T19:05:19.063Z" }, ] +[[package]] +name = "matplotlib-inline" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" }, +] + +[[package]] +name = "mistune" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/96/eb/749a4e69bf7396e751ae37444abe997eff2254e695a8095b84d1c89c1181/mistune-3.4.0.tar.gz", hash = "sha256:2eaf7952af928ca8d33b779762effc1da517b62c6ad85ec8ca957e3b07b9782a", size = 136772, upload-time = "2026-10-19T10:44:28.172Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/f7/021d590d52c1ac28e3290311776854c6a1c927fa3fb4b25ce74caf937a3d/mistune-3.4.0-py3-none-any.whl", hash = "sha256:d03cec4c8620f21517a996d82d14f3b59c30d79bda2cc6c56bd32b839f18ce6b", size = 70398, upload-time = "2026-10-19T10:44:26.751Z" }, +] + [[package]] name = "mlflow" version = "3.17.2" @@ -1561,23 +1825,34 @@ dependencies = [ { name = "scikit-learn" }, ] +[package.optional-dependencies] +notebooks = [ + { name = "ipykernel" }, + { name = "nbclient" }, + { name = "nbconvert" }, +] + [package.metadata] requires-dist = [ { name = "apache-hamilton", specifier = ">=1.90" }, { name = "extraction", editable = "../Extraction" }, + { name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" }, { name = "mlflow", specifier = ">=2.9" }, - { name = "onnx", marker = "extra == 'export'", specifier = ">=1.15" }, + { name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" }, + { name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" }, { name = "pandas", specifier = ">=2.0" }, { name = "pandera", specifier = ">=0.20" }, { name = "persistance", editable = "../Persistance" }, { name = "pyarrow", specifier = ">=15" }, { name = "scikit-learn", specifier = ">=1.4" }, ] -provides-extras = ["export"] +provides-extras = ["notebooks"] [package.metadata.requires-dev] dev = [ - { name = "onnx", specifier = ">=1.15" }, + { name = "ipykernel", specifier = ">=6.29" }, + { name = "nbclient", specifier = ">=0.10" }, + { name = "nbconvert", specifier = ">=7.16" }, { name = "pytest", specifier = ">=8.0.0" }, { name = "reportlab", specifier = ">=4.0" }, ] @@ -1738,6 +2013,70 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/89/5d4c86da1130d9059681e5b6cd7645df5c10279a6a079c5c37dcb2cc6f3f/narwhals-2.27.1-py3-none-any.whl", hash = "sha256:d057df13f5852b8e157596e82eb5e955fad267425df5e420e0ee9863da483b31", size = 483211, upload-time = "2026-10-10T06:52:16.32Z" }, ] +[[package]] +name = "nbclient" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jupyter-client" }, + { name = "jupyter-core" }, + { name = "nbformat" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/a5/b3bae4b590c0cbcada2c63a34f7580024e834a8ba213e949a2f906705787/nbclient-0.11.0.tar.gz", hash = "sha256:04a134a5b087f2c5887f228aca155db50169b8cd9334dee6942c8e927e56081a", size = 62535, upload-time = "2026-06-05T07:52:41.746Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/c9/94d73e5a01c5b926c3fa2496e97d7a8dc28ed5a77c0b2ed712f1a62e6694/nbclient-0.11.0-py3-none-any.whl", hash = "sha256:ef7fa0d59d6e1d41103933d8a445a18d5de860ca6b613b87b8574accdb3c2895", size = 25288, upload-time = "2026-06-05T07:52:40.115Z" }, +] + +[[package]] +name = "nbconvert" +version = "7.17.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "beautifulsoup4" }, + { name = "bleach", extra = ["css"] }, + { name = "defusedxml" }, + { name = "jinja2" }, + { name = "jupyter-core" }, + { name = "jupyterlab-pygments" }, + { name = "markupsafe" }, + { name = "mistune" }, + { name = "nbclient" }, + { name = "nbformat" }, + { name = "packaging" }, + { name = "pandocfilters" }, + { name = "pygments" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/53/6a/252c7620305a9661205aed7a2a4b3592f5207bfca56ad11b7dea2c5ec2f6/nbconvert-7.17.2.tar.gz", hash = "sha256:344a218e8595117ce37396ed025d994f146d076226ebac59255a2fa085ab24d8", size = 865989, upload-time = "2026-10-12T09:11:19.583Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/fd/a8d457af68848a8e5c12dd1d84ff35c415db471af78280e0703db4efbb12/nbconvert-7.17.2-py3-none-any.whl", hash = "sha256:6a143c11c00bf831604da4b1be4347d36ea52367057eb920135d69bc2862fed2", size = 262094, upload-time = "2026-10-12T09:11:17.215Z" }, +] + +[[package]] +name = "nbformat" +version = "5.11.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fastjsonschema" }, + { name = "jsonschema" }, + { name = "jupyter-core" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/31/72/b3446efab8756e7df4b8ec587f8e611cb5a7249e4323db480802f1d3be04/nbformat-5.11.1.tar.gz", hash = "sha256:32d4521c68c6e7d5b29c76defaeed9f42ea733142b9b19f88277ce10390b9c4d", size = 147775, upload-time = "2026-08-17T08:10:51.942Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/69/ee613f74085ca7103f79cd08d579c4f3177d1d26e5d3d9528d2d6536a707/nbformat-5.11.1-py3-none-any.whl", hash = "sha256:cc6698fa75f4fab8755ead786317815f13a6fee3b53311c0abb1a8b51d52f7ec", size = 79849, upload-time = "2026-08-17T08:10:50.18Z" }, +] + +[[package]] +name = "nest-asyncio2" +version = "1.7.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/32/2c/70e3b6bb2189cfd260280b7e1042bd622949a258663f95e887fada4ac1e6/nest_asyncio2-1.7.4.tar.gz", hash = "sha256:995b1409d926ec55e0876ea39a69bffdd8852cf1db3652c177e8c8ffdbcaf3cc", size = 16891, upload-time = "2026-10-07T22:31:50.507Z" } +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 = "numpy" version = "2.5.3" @@ -1961,6 +2300,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/84/107a480f7aa34a6878fb4fb85cda66f37e8aaee769c5917e3eaa2d55222e/pandera-0.33.1-py3-none-any.whl", hash = "sha256:8283bc12f7c85f0b429107d71b55150205f7e5ca59d68117aff971273a3bd2d8", size = 501976, upload-time = "2026-09-01T15:56:05.944Z" }, ] +[[package]] +name = "pandocfilters" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/6f/3dd4940bbe001c06a65f88e36bad298bc7a0de5036115639926b0c5c0458/pandocfilters-1.5.1.tar.gz", hash = "sha256:002b4a555ee4ebc03f8b66307e287fa492e4a77b4ea14d3f934328297bb4939e", size = 8454, upload-time = "2024-01-18T20:08:13.726Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/af/4fbc8cab944db5d21b7e2a5b8e9211a03a79852b1157e2c102fcc61ac440/pandocfilters-1.5.1-py2.py3-none-any.whl", hash = "sha256:93be382804a9cdb0a7267585f157e5d1731bbe5545a85b268d6f5fe6232de2bc", size = 8663, upload-time = "2024-01-18T20:08:11.28Z" }, +] + +[[package]] +name = "parso" +version = "0.8.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, +] + [[package]] name = "pdfminer-six" version = "20260107" @@ -2017,6 +2374,18 @@ dev = [ { name = "pytest", specifier = ">=8.0.0" }, ] +[[package]] +name = "pexpect" +version = "4.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ptyprocess" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } +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 = "pillow" version = "12.3.0" @@ -2132,6 +2501,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fe/be/2e6798ace5cc036f5d05d36b7b2fd85346f1a708c87060890b070d0ec607/prettytable-3.18.0-py3-none-any.whl", hash = "sha256:b3346e0e6f79180833aebaac088ae926340586cf6d7d991b9eb125b65f72313a", size = 37357, upload-time = "2026-06-22T16:07:48.595Z" }, ] +[[package]] +name = "prompt-toolkit" +version = "3.0.53" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, +] + [[package]] name = "propcache" version = "0.5.4" @@ -2258,6 +2639,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" }, ] +[[package]] +name = "psutil" +version = "7.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, + { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, + { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, + { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, + { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, + { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, + { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, + { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, + { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, + { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, + { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, + { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, + { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, + { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, + { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, +] + [[package]] name = "psycopg2-binary" version = "2.9.13" @@ -2310,6 +2719,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e8/30/3991c9fdcca90a5a1e55435292f4d74d176da2be15f3998f6858da3658cc/psycopg2_binary-2.9.13-cp315-cp315-win_amd64.whl", hash = "sha256:1752b9821f1377404d65ac43af03d59a1eccc57fb2c1eb8305f9a3fe8eb7a8ba", size = 2867246, upload-time = "2026-09-09T23:56:20.501Z" }, ] +[[package]] +name = "ptyprocess" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" }, +] + +[[package]] +name = "pure-eval" +version = "0.2.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/9f/abfd2959e9261dd5217ca8551d4de211ca6ab26fe9b72cf44731ff6c4442/pure_eval-0.2.4.tar.gz", hash = "sha256:260c2774686e651b79f8b8e7fc9d80b3599ea6a66334b47d5f4abb69fc2c0ea1", size = 20563, upload-time = "2026-09-10T21:41:22.836Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/18/83376915176eb058cb86470eb7396388a13350b09a8f233a79303bbcbc5b/pure_eval-0.2.4-py3-none-any.whl", hash = "sha256:96cae060a313cfaad51bb761278bfb0e62dc0248d9315a81173752dc546cd37a", size = 11893, upload-time = "2026-09-10T21:41:21.532Z" }, +] + [[package]] name = "pyarrow" version = "25.0.1" @@ -2701,6 +3128,60 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] +[[package]] +name = "pyzmq" +version = "27.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "implementation_name == 'pypy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e2/e1/ea46ab0d707219c098065a37d2add5b53d3b124241aa19429bcd0863e5b4/pyzmq-27.3.0.tar.gz", hash = "sha256:bbedb3d1d99babc625f1dd9d7438acefd442b36b75073fd6bc1ef7c0a4b96d56", size = 293249, upload-time = "2026-11-04T00:31:33.068Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/9e/6663ccc8c1af4e7db85de65921560a8058ad4ad4c40ebc49af4b1164f01a/pyzmq-27.3.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:15155fd8f308d3bd47f67a8f6cc809f9db90abbf63c514c384a17622e2cf080f", size = 1232964, upload-time = "2026-11-04T00:29:09.922Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/4fc65d7a48077f535705ac957c29a3c07fa54a1f8d2595ca2f5f1489b21c/pyzmq-27.3.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ad8b828407caee77ff3ab0bdb2984ee8d48922328b226e8fda7c84a71a55dbb4", size = 770405, upload-time = "2026-11-04T00:29:11.487Z" }, + { url = "https://files.pythonhosted.org/packages/2c/62/e4721d8b8b9de685323717489a408521067a786cabc2b73ccd91aa9b9077/pyzmq-27.3.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:858fe25231e0fd8612da142efde019faa5ef63fa150a821a27870e791b38c798", size = 855178, upload-time = "2026-11-04T00:29:13.042Z" }, + { url = "https://files.pythonhosted.org/packages/39/5f/8190ff273beb195d9c9b62a36d0d87bad79019e76ff4407cabe463bc650d/pyzmq-27.3.0-cp312-abi3-manylinux_2_28_i686.whl", hash = "sha256:8b174298b57d5c2397c74fbefd656101d477357035916881970ed5f53b7b904c", size = 919158, upload-time = "2026-11-04T00:29:14.854Z" }, + { url = "https://files.pythonhosted.org/packages/8f/66/ab116baad852235c82be3d8d83af7098a7165c48995a03f2b6e8d50297dc/pyzmq-27.3.0-cp312-abi3-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cffd75359342ef88c86c287c99b16b2b100795dab467fd5398bcedd87d49bce7", size = 813613, upload-time = "2026-11-04T00:29:17.239Z" }, + { url = "https://files.pythonhosted.org/packages/b3/55/5075ef84055eca159435e65f8d67591bfe06c562cf310792cd50a6aeb0c9/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:220095b4c11b0542ae5c0d67411331d3819753ee9ec0468e63a4ca6fd4ccf50f", size = 1762126, upload-time = "2026-11-04T00:29:18.994Z" }, + { url = "https://files.pythonhosted.org/packages/28/6f/e75d5e5aeda920dbcaaedcc413605379287b817578d00e47bfa89a8ea671/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:e9e12fe784529e12177937aee8c714b7aed8913a2429ee2567400c904d4d55b5", size = 2067522, upload-time = "2026-11-04T00:29:20.762Z" }, + { url = "https://files.pythonhosted.org/packages/9c/b4/0d91b1e5ea8d659c1014ef39acfda279f4768fc4043120e98b764a59f1c9/pyzmq-27.3.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d317685b83663fbd03ca8b5c34add7463e9bed094e3e1a69d2a895130b64ffaf", size = 1893864, upload-time = "2026-11-04T00:29:22.451Z" }, + { url = "https://files.pythonhosted.org/packages/2a/23/ed213d9dc6e48913a1f77090d1aed85bc4b1e5567ef74a86fd8fd473f423/pyzmq-27.3.0-cp312-abi3-win32.whl", hash = "sha256:07dd778d7cf242a1e131bfad6244f64df59441dda7ea639d037d0fdb22112b6c", size = 567172, upload-time = "2026-11-04T00:29:24.09Z" }, + { url = "https://files.pythonhosted.org/packages/fa/6d/23a02024011a494fb52bcfb179f10a3b230cff7b6fe0d5b8a3c775ce3b82/pyzmq-27.3.0-cp312-abi3-win_amd64.whl", hash = "sha256:3ea8e8fa5c097e68fef91d70b150fda96f307758103868018fc4deeb9c214122", size = 642389, upload-time = "2026-11-04T00:29:25.739Z" }, + { url = "https://files.pythonhosted.org/packages/e2/1b/410fc7ec4fc114b46da17ed0df3b88606f0624fbe172e184658d361b1dc1/pyzmq-27.3.0-cp312-abi3-win_arm64.whl", hash = "sha256:2187a5ca80691a5edb30690f02d9fb714e2c32d3dfdeb652e159ff5da2dd4283", size = 570810, upload-time = "2026-11-04T00:29:27.709Z" }, + { url = "https://files.pythonhosted.org/packages/d1/0f/81652a1066e994000cfec501f16137fa231e921675b63ee54c8cf4e30362/pyzmq-27.3.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:a418d35be0a0a2693bf1990d831a744ee2f012b8268b3e0c6cb28b06c2769d76", size = 1136520, upload-time = "2026-11-04T00:29:29.58Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0e/a2e5cb7db327ce85f3c2d11f25be55aba1639f55dad8ea77e03458ec5dbf/pyzmq-27.3.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:e9012762d869d620dad3c83fb5ff8f4900490decddd98caf6ff80847176c4be0", size = 1181427, upload-time = "2026-11-04T00:29:31.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/b8/8a80749971b1a42fc415c720a52deedd33d0ae72792544331fc76f306ded/pyzmq-27.3.0-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:fca5c2352c499e8355b581ddecfe52538984131b7efc052a30e2d32426baf637", size = 1143753, upload-time = "2026-11-04T00:29:32.923Z" }, + { url = "https://files.pythonhosted.org/packages/59/2d/196f50920da3137fd54b1636c36aba97b95d18d467bf097edca5f6ef5be8/pyzmq-27.3.0-cp314-cp314-android_24_x86_64.whl", hash = "sha256:91ac316f440aca4e6eaf3786f54b80f4ab433e5cc4e5e9b82eb44a27c5c987cd", size = 1182341, upload-time = "2026-11-04T00:29:35.073Z" }, + { url = "https://files.pythonhosted.org/packages/c7/3f/bf2a67da7cfac3c1f85c0130b8bd1fc48e96c1e66e8a50c71faea83979b3/pyzmq-27.3.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:d292cedc7250db240e9f41994cf3eefe2c7606c702ef5c56aab8d4f03870108c", size = 1271939, upload-time = "2026-11-04T00:29:36.803Z" }, + { url = "https://files.pythonhosted.org/packages/f6/43/2bfa60b57b3febd892d5760c811012b6850306962e3dd6a2f91b96cd5398/pyzmq-27.3.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:924f870055c05926887157485efe903c8f9668d0f3f19d56df7612bcb3d662cb", size = 779903, upload-time = "2026-11-04T00:29:38.52Z" }, + { url = "https://files.pythonhosted.org/packages/e3/72/4f88cd0d1da0e5db9a26a899e37f8b46d925f328f9bae590f86fc995074b/pyzmq-27.3.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6dac496cd8aacf185a634e5cc8930331db1627dd214a58ee4c27948ce4ae79af", size = 864708, upload-time = "2026-11-04T00:29:50.209Z" }, + { url = "https://files.pythonhosted.org/packages/79/5e/fce842845aad4135a2e1936f3cd1a418b4f49e2d45cd7b5576d6f836d95b/pyzmq-27.3.0-cp314-cp314t-manylinux_2_28_i686.whl", hash = "sha256:665b1a3d35a4ffe6cfa626191a5439108159d51d17bd9d44f1beb1690114adfc", size = 927234, upload-time = "2026-11-04T00:29:52.003Z" }, + { url = "https://files.pythonhosted.org/packages/e1/28/945736083a00750e101c4259312b5303aead36ef08539a0f0ad93a1cb899/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0fedab58520a5091ffa62547eb507bea44882ce72d49929fa9626061ae1b9a2c", size = 1771921, upload-time = "2026-11-04T00:29:53.677Z" }, + { url = "https://files.pythonhosted.org/packages/3d/30/2a584e845a51c0e5d6e13889fe659aa90912004fbb5bc4750491f558528c/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:1b9b9d11e2e775a81d0e8b5c6cb76a395ddaa7c6b6373f3b0d2c8f8146d95f4a", size = 2075396, upload-time = "2026-11-04T00:29:55.772Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6b/93066f121c31b825c56c74dca01ea5c00847f8b44645ad990f92bd04d29c/pyzmq-27.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:169a522c4d166c3bc7b67ed827d3beda549a8e65c4015c9410687757fb39852f", size = 1903986, upload-time = "2026-11-04T00:29:57.741Z" }, + { url = "https://files.pythonhosted.org/packages/85/ae/ecc7c77cd6ea18ff7b2b07a2fd0db5c31c2204ecf9a774e80bd1250dc9d9/pyzmq-27.3.0-cp314-cp314t-win32.whl", hash = "sha256:0228fe121f05a8b638ef218dde7508477a8c46200a588f71ce7143d85987cdd7", size = 597206, upload-time = "2026-11-04T00:29:59.35Z" }, + { url = "https://files.pythonhosted.org/packages/7a/1d/0bee73e1e8ab1c26eecba13a4725dfbe0405b53f451a91671dd515effe00/pyzmq-27.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8a3d02fc710302a23c9a67b287bc13f2992067d398c3192b50eb0e30d44ed885", size = 685132, upload-time = "2026-11-04T00:30:01.144Z" }, + { url = "https://files.pythonhosted.org/packages/cd/23/13a768f9a8e66a999250abd216e50e1961a1cd4a8708749f656f5c0c2aea/pyzmq-27.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2b9f08778b608fe4f6250e2d132f41b4f99fa8d03051cf2809b1c0420def81b4", size = 595549, upload-time = "2026-11-04T00:30:02.693Z" }, + { url = "https://files.pythonhosted.org/packages/91/ac/674d5c512c196c3ff2c37b27ce87764e9e69c7591902ef48330ff0ebfc07/pyzmq-27.3.0-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:81fcd4e798f384a158b1790171a63541e66ccdee5a139a4dd0848a6e88dc7b9e", size = 1143291, upload-time = "2026-11-04T00:30:04.411Z" }, + { url = "https://files.pythonhosted.org/packages/c1/eb/6bf15cb88fb5d9f8fe6ee6b57185c110f862b6bc1ad02772767571bd3c5c/pyzmq-27.3.0-cp315-cp315-android_24_x86_64.whl", hash = "sha256:e9b87a6f40b62c7cd47691fc2ba4fdc28bef58f5fccf48eaf39940d183d2a16c", size = 1181899, upload-time = "2026-11-04T00:30:05.993Z" }, + { url = "https://files.pythonhosted.org/packages/2c/bc/e00cf032d751a709e12d71c3e2e265957bfb0097d8d071fae4f6a45e2d4c/pyzmq-27.3.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:23ddfe5d4d0c6ea529614c8999065d609a113f343c7e60dda9746d7dcb00d766", size = 1270101, upload-time = "2026-11-04T00:30:07.977Z" }, + { url = "https://files.pythonhosted.org/packages/20/aa/87ebb4664bb27fa53382d45f21f9f49d6194c0eb6737d7c2c5d5e921f1ee/pyzmq-27.3.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b437cf437fe737e17082625f470258f12e4bf5d56edfb88cb21d3aa4089fcef9", size = 779378, upload-time = "2026-11-04T00:30:10.504Z" }, + { url = "https://files.pythonhosted.org/packages/c1/85/e998ff27a29aca9b0f8529e32b0913420e75f8f990a54ad9434faa3d4c5e/pyzmq-27.3.0-cp315-cp315t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc2cc98f37a14a3c9baccc18173a9fca9c6d18ffb233bca7079e58b2e47ee7f8", size = 864317, upload-time = "2026-11-04T00:30:12.259Z" }, + { url = "https://files.pythonhosted.org/packages/d6/7a/6535a0b2fbde9554291caeb3c41b6452207ed7afeb910af830f48e6731f5/pyzmq-27.3.0-cp315-cp315t-manylinux_2_28_i686.whl", hash = "sha256:1a1e092726596141e8ad2cc7f542fd366ddd692b8a9e254d2972ac47b399b982", size = 926240, upload-time = "2026-11-04T00:30:13.862Z" }, + { url = "https://files.pythonhosted.org/packages/51/6f/0c3b1b621f17ebd3eaa2c974b11507dc88cef529ebdc72b42935d00e4a90/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:0c9c332883373eb85b72f4d912a9a4402ba7702709fa783d3c76ff2bd703a491", size = 1771499, upload-time = "2026-11-04T00:30:15.471Z" }, + { url = "https://files.pythonhosted.org/packages/e1/a5/b753eb9acc131fbb4da67c4c68037965f12f8782d1fd5e461e803e0a1dc1/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:1f724caa222b1ae3c48f7d25147c816c8bde56fb109c164a650f0502b9005ab6", size = 2074632, upload-time = "2026-11-04T00:30:17.149Z" }, + { url = "https://files.pythonhosted.org/packages/d1/ad/8bce8d0ff0f0cc0958bdfeebbde9ee319cbd025c949607ab2864df657ce6/pyzmq-27.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:129ca693e543940527e105144dcacdf9e0ec01d41421098e08893de8227aca58", size = 1903559, upload-time = "2026-11-04T00:30:19.142Z" }, + { url = "https://files.pythonhosted.org/packages/fd/25/e5b3e6a066b59840cdc0ea6de8244b1a50b5f237edc7b7adc0e085973708/pyzmq-27.3.0-cp315-cp315t-win32.whl", hash = "sha256:39b9ff1fbab854ccbc53da0e79cb6b78b61b470fb7c191b89aa034825ea9a883", size = 596443, upload-time = "2026-11-04T00:30:20.811Z" }, + { url = "https://files.pythonhosted.org/packages/3f/c8/20ecc504500aeaab0440a4c8487a3c1cd32f4ac38f3e92482f1671fcaeca/pyzmq-27.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:3b850eaa955ae7edb926fe266600e57da818255d1f6ee9c3d8049967aa4a22cc", size = 684767, upload-time = "2026-11-04T00:30:22.784Z" }, + { url = "https://files.pythonhosted.org/packages/e8/5d/33c528d9b7ee074d0807e3af1a23a3e50bfdbe28cbc178e99f0466c13648/pyzmq-27.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:f0b9d192b285a9d38e390e762011f2672432742a301859b6c8cb4fab5f10f687", size = 594143, upload-time = "2026-11-04T00:30:24.33Z" }, + { url = "https://files.pythonhosted.org/packages/53/53/6ea90b8bb4c77bcc4babd15ef6a63ed243cfd47920cb270da5f29438d11f/pyzmq-27.3.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:cff2031014f79b213818b6773253cbf330119c93de33ee1a635596f407da5c35", size = 689536, upload-time = "2026-11-04T00:31:12.423Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9e/699898cdd86e4cd4bc20547b9f1bce24c58900f51e6a9d5fad03c2890407/pyzmq-27.3.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:18da98ce26045ef503b42a3f98fc2a2af0cdb2af87dc0594852fa5cea3795427", size = 632027, upload-time = "2026-11-04T00:31:14.338Z" }, + { url = "https://files.pythonhosted.org/packages/a6/59/5d6ccce5456cafbdf84c98141d3ddf6c073716eb7b958254349e047fad84/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13c7336a4112d3e09c5d78d17e17af1cd01da858ec1c5e3755b2d06339aa7d4f", size = 684300, upload-time = "2026-11-04T00:31:15.891Z" }, + { url = "https://files.pythonhosted.org/packages/b4/37/c4cf124d820495c5549b3f606b1292949c9e2053467309a7e1baaf0c3784/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e1358fabf41920d69cab170495b6e263680797ac5b80ace1b5cf1eb2d89642", size = 761485, upload-time = "2026-11-04T00:31:17.817Z" }, + { url = "https://files.pythonhosted.org/packages/a7/cf/caa0bd5f7a1b139b9240faf3b34586867656f682774364101572e8e84f80/pyzmq-27.3.0-pp312-pypy312_pp80-manylinux_2_28_i686.whl", hash = "sha256:cdb5efd4c23465573e928fb8429e40996ac0e1a4809365efe19e2753112b6ee1", size = 821382, upload-time = "2026-11-04T00:31:19.451Z" }, + { url = "https://files.pythonhosted.org/packages/8e/34/81fa1d9701024eb4f48949ba5f93da3a063ab997e0e0c9787ff37f11ecda/pyzmq-27.3.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:1b7ab96158dd50d7e6e430e6e4f744aaccee1df2e9d167ace9e7d2f3e3051712", size = 564187, upload-time = "2026-11-04T00:31:21.486Z" }, +] + [[package]] name = "rapidfuzz" version = "3.14.6" @@ -2791,6 +3272,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/04/a0b0e6324b6384d1ab40feb4d16400af3b3101d38cbd15957edd9d17cbe0/rapidfuzz-3.14.6-cp315-cp315t-win_arm64.whl", hash = "sha256:07c7aa0b1e4b9999a54f9e73317d6743ff85442c8ef7b7fbbe6b190fd37d9e75", size = 1243815, upload-time = "2026-08-30T21:45:31.187Z" }, ] +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + [[package]] name = "reportlab" version = "5.0.1" @@ -2819,6 +3314,114 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] +[[package]] +name = "rpds-py" +version = "2026.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/42/68/3bd46b8a5e01d3c2ebdf9c5e9497912e3fe0cde02bac21a7130ca866e403/rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12", size = 63948, upload-time = "2026-10-04T16:32:36.469Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/34/a828586ea3329fbb50895b50e9cf98ca3d924a9f41a0b26d443bff1b3794/rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af", size = 346822, upload-time = "2026-10-04T16:29:16.258Z" }, + { url = "https://files.pythonhosted.org/packages/90/81/ac6a0d064982251856ce009c9e1dd51a34110b3c055aa7d1aad18b4899a3/rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b", size = 341380, upload-time = "2026-10-04T16:29:17.706Z" }, + { url = "https://files.pythonhosted.org/packages/42/ff/bf7d54f362748fd6a49277b9d6531c394074110fedf50ad791ec59133fbb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a", size = 373053, upload-time = "2026-10-04T16:29:19.063Z" }, + { url = "https://files.pythonhosted.org/packages/60/de/74b0ccdbbd28687b9b5fdb34c1cabed88352182facaced9d6f5486b8b9ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07", size = 377742, upload-time = "2026-10-04T16:29:20.543Z" }, + { url = "https://files.pythonhosted.org/packages/c2/6d/b979775a3057b2a5c26d75ecbff60a20a24ef081db6dd76836fca3f20247/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69", size = 487289, upload-time = "2026-10-04T16:29:21.958Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5d/7c34734ce3ece943d9d6ee0122a74a21bbc75b47acb5b7053c83f6efb1ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d", size = 390710, upload-time = "2026-10-04T16:29:23.378Z" }, + { url = "https://files.pythonhosted.org/packages/1d/6d/b26eb1e75395925b3a142ed351cbed2ec8212f5c9d937aee3df32c701baa/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab", size = 371261, upload-time = "2026-10-04T16:29:25.1Z" }, + { url = "https://files.pythonhosted.org/packages/7c/98/b2fdfe10301a9e27af21e634337fbba7baac0bc17fe44619a17c26bba2cb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e", size = 376075, upload-time = "2026-10-04T16:29:26.748Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b1/c4b8d954e49c3c69cf8063c0c9e0919c99f3d2cecc46311606a1cbe835dc/rpds_py-2026.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237", size = 399358, upload-time = "2026-10-04T16:29:28.282Z" }, + { url = "https://files.pythonhosted.org/packages/b3/59/9559a7293c97dff0cbb293efffbd36644103883ecc27741af8ef90c84ca8/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3", size = 550267, upload-time = "2026-10-04T16:29:29.851Z" }, + { url = "https://files.pythonhosted.org/packages/6c/9d/6dc60e49511de4c8b00e74f9c1d43aed4d27f712cdb1ade92f2c199cbf64/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc", size = 614018, upload-time = "2026-10-04T16:29:31.54Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bc/92a4ecf27301b886232a413360f6b348a81d55ffef654f2ebda5970ebc3d/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6", size = 578509, upload-time = "2026-10-04T16:29:33.01Z" }, + { url = "https://files.pythonhosted.org/packages/08/53/efb97f2e6589b7ab8394385a73870e0b2ab2a195281c117b21fd6d7d4855/rpds_py-2026.9.1-cp312-cp312-win32.whl", hash = "sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3", size = 205401, upload-time = "2026-10-04T16:29:34.451Z" }, + { url = "https://files.pythonhosted.org/packages/1c/84/1700cc748d0eaa747486e4e82882d2575224e6e9a3148df583058850c629/rpds_py-2026.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f", size = 222923, upload-time = "2026-10-04T16:29:35.709Z" }, + { url = "https://files.pythonhosted.org/packages/c3/89/0302215373c2f8b4408b0fdfee955368cc378a98ff59508d47a7e0dc2dbf/rpds_py-2026.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02", size = 218415, upload-time = "2026-10-04T16:29:37.263Z" }, + { url = "https://files.pythonhosted.org/packages/83/ea/ee88fd9e756ff93fb6b1182a47ec09504a242620e33ce1d20679efefe841/rpds_py-2026.9.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9", size = 346229, upload-time = "2026-10-04T16:29:38.82Z" }, + { url = "https://files.pythonhosted.org/packages/57/71/a097d6552f837500fc36e6b23d09cfb9890c3cc47531f9ca64e149799615/rpds_py-2026.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858", size = 340514, upload-time = "2026-10-04T16:29:40.405Z" }, + { url = "https://files.pythonhosted.org/packages/bd/b7/497e85768bf4e0d8ddbaa096a4cac31d1509251dee2728a8490aa367e0b5/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063", size = 372611, upload-time = "2026-10-04T16:29:41.778Z" }, + { url = "https://files.pythonhosted.org/packages/52/4b/74ab4108916250b6e198e0d3af05bc6835eb046315f22f7a0ceb49667c5a/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025", size = 377712, upload-time = "2026-10-04T16:29:43.242Z" }, + { url = "https://files.pythonhosted.org/packages/0c/8e/067e77d9d7b3cc793c9d909b7e97e7aadbbb1fb094093b6876902cc96d38/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5", size = 488106, upload-time = "2026-10-04T16:29:44.692Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b4/c5aae6c2dde269bf955f6b7d35065c655a57e47750d9668052ad67e74dda/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0", size = 390795, upload-time = "2026-10-04T16:29:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/a0/36/76fab39973ee11e7f9f357c55138197bb01c86f6502cb76487e3b4f42db0/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b", size = 370794, upload-time = "2026-10-04T16:29:47.603Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/cd2a80e6d7b871937a60e935c5d507aa390d143f4ff3636f640b9733d5df/rpds_py-2026.9.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33", size = 375673, upload-time = "2026-10-04T16:29:49.223Z" }, + { url = "https://files.pythonhosted.org/packages/6c/18/7464a9953724e55a3b3206062fa0ffdeaa519584c6aabf65d3956d94f131/rpds_py-2026.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83", size = 398758, upload-time = "2026-10-04T16:29:50.601Z" }, + { url = "https://files.pythonhosted.org/packages/c0/86/1534b436700fd49ff411063b7c4d7e938adfabf90895b6cf1622d5a7d1f6/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c", size = 550370, upload-time = "2026-10-04T16:29:52.002Z" }, + { url = "https://files.pythonhosted.org/packages/57/1c/e1fa82a8a01e3c5820f3ba98a8b2673f642128eb368fa88871b01dd2c909/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36", size = 613106, upload-time = "2026-10-04T16:29:53.655Z" }, + { url = "https://files.pythonhosted.org/packages/29/55/b20b8c4c3dde8755bfcd5b08492a02d0cd2e26929aedf6199ca2a377d42a/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d", size = 578235, upload-time = "2026-10-04T16:29:55.157Z" }, + { url = "https://files.pythonhosted.org/packages/55/42/df3f7bbc3f7ab37a8a9db8d6c2ff2c985422899f1f7926afbf7ec3c0b8b4/rpds_py-2026.9.1-cp313-cp313-win32.whl", hash = "sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c", size = 205293, upload-time = "2026-10-04T16:29:56.669Z" }, + { url = "https://files.pythonhosted.org/packages/31/9c/ba5a9569d719bfdd6ce863df4133ac6a1658cf1b07cc3534c31db729fbbc/rpds_py-2026.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9", size = 222409, upload-time = "2026-10-04T16:29:58.049Z" }, + { url = "https://files.pythonhosted.org/packages/35/72/f28ca566f6c23c35bbf7445f65eb0364577b25a026305995e24f78b83d94/rpds_py-2026.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f", size = 217681, upload-time = "2026-10-04T16:29:59.449Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f2/67b94be1532767803415c1c5a1fd88ea487643d74a673cec1ba140af77bb/rpds_py-2026.9.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b", size = 347178, upload-time = "2026-10-04T16:30:00.865Z" }, + { url = "https://files.pythonhosted.org/packages/04/37/b751de2b59b0197a1d92a5dd491de88e8a5e928c2e6562581974f1e85263/rpds_py-2026.9.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35", size = 341878, upload-time = "2026-10-04T16:30:02.564Z" }, + { url = "https://files.pythonhosted.org/packages/72/e2/5873bc4643c250db9e05d48dc0c93763d4aa68bc3b81164cb1af3b45b284/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0", size = 373963, upload-time = "2026-10-04T16:30:04.026Z" }, + { url = "https://files.pythonhosted.org/packages/51/03/5acf7632158247f3f6386ff0af3a1ee48167d575037e8d0920594b76d92b/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477", size = 377975, upload-time = "2026-10-04T16:30:05.555Z" }, + { url = "https://files.pythonhosted.org/packages/e6/00/63fda451b8bffa5808fc8bb311ee7c073b340974b09f273c7b2a145d3d62/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4", size = 490347, upload-time = "2026-10-04T16:30:07.156Z" }, + { url = "https://files.pythonhosted.org/packages/a1/ae/c093ffd070ba0fb02f76c565d06fecc65ad6e4afdbae78f7031076d3cdac/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef", size = 392962, upload-time = "2026-10-04T16:30:08.77Z" }, + { url = "https://files.pythonhosted.org/packages/22/9d/d08a1128ab199b2f0cf25bfeb0639bd05119fff4b7c47bec24ef9a8ec23f/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd", size = 371623, upload-time = "2026-10-04T16:30:10.501Z" }, + { url = "https://files.pythonhosted.org/packages/53/c7/4758ddcbb75609414bbccfcb11d612436f9b3ee821bd2f33f0f1604ee648/rpds_py-2026.9.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35", size = 376997, upload-time = "2026-10-04T16:30:12.124Z" }, + { url = "https://files.pythonhosted.org/packages/87/e4/947bd7f608ff60faf46dc9d389c3dffd0e3d767d78a0be19978448ef0ce7/rpds_py-2026.9.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86", size = 400169, upload-time = "2026-10-04T16:30:13.804Z" }, + { url = "https://files.pythonhosted.org/packages/4b/35/fe93e020a0543b5670472c18d7e6af3197c08da571240ce1965c84f85c0f/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e", size = 551615, upload-time = "2026-10-04T16:30:15.332Z" }, + { url = "https://files.pythonhosted.org/packages/0d/4f/5d2a0136bb03b2a56a39dc6ff92d58a6e3e53a2e17079238b86228882f16/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785", size = 614655, upload-time = "2026-10-04T16:30:16.92Z" }, + { url = "https://files.pythonhosted.org/packages/09/1c/3f1025aaf70d9bf7272cc41f8b64ee76b48bf01726248138430e16f23b38/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118", size = 579602, upload-time = "2026-10-04T16:30:18.555Z" }, + { url = "https://files.pythonhosted.org/packages/53/0d/5c72e6204f76610608706da32b6b7e11ef7e10317558a7bb15a122e008dc/rpds_py-2026.9.1-cp314-cp314-win32.whl", hash = "sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc", size = 206315, upload-time = "2026-10-04T16:30:20.05Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0b/489d48abbcc7d70cf3fbf662d9d22abf1f4650761c0a9ae05260800800d3/rpds_py-2026.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c", size = 222852, upload-time = "2026-10-04T16:30:21.604Z" }, + { url = "https://files.pythonhosted.org/packages/91/16/bbb05a7e6a10cf79ba639be7f799d770ee15f64175cc61d081b218dd402a/rpds_py-2026.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31", size = 218709, upload-time = "2026-10-04T16:30:23.036Z" }, + { url = "https://files.pythonhosted.org/packages/22/ac/ac507a0a4ec478ca470440a09583db4be5259ba7670aeba0620822f1e57a/rpds_py-2026.9.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e", size = 349596, upload-time = "2026-10-04T16:30:24.558Z" }, + { url = "https://files.pythonhosted.org/packages/e9/f2/817a46b658d5070f477f722c298ee9a24525b0e4017347964146ef5fdd0e/rpds_py-2026.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96", size = 343114, upload-time = "2026-10-04T16:30:26.048Z" }, + { url = "https://files.pythonhosted.org/packages/6c/42/6ade976b13ac1b4cb3bf2eb603f1be2fe74df19a29988d4c2b386be59d6f/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445", size = 374197, upload-time = "2026-10-04T16:30:27.699Z" }, + { url = "https://files.pythonhosted.org/packages/d9/70/77cdf1d3f1a07faabe936016ae623aec7981f73108a8fe7a203ed2e21998/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69", size = 378025, upload-time = "2026-10-04T16:30:29.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/18a44a3beaa9b7931acb04af7bd9539836477c630a794452d4826d6185d4/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495", size = 491969, upload-time = "2026-10-04T16:30:30.995Z" }, + { url = "https://files.pythonhosted.org/packages/73/27/fb39cfd6bddaf741b024f813890374578ff8ac1f1adc473659c048b03b05/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c", size = 393905, upload-time = "2026-10-04T16:30:32.628Z" }, + { url = "https://files.pythonhosted.org/packages/ed/71/0fa7bb77b57af0d710273964180d11b503f62b8a5c358eb2d8c3f62feff6/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e", size = 374569, upload-time = "2026-10-04T16:30:34.257Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/f41cfac269af3b449513ef1bc3d7f32fde52abbbd2d01c7e76b47743acd9/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346", size = 377482, upload-time = "2026-10-04T16:30:35.997Z" }, + { url = "https://files.pythonhosted.org/packages/b4/fc/312b49006e7f8f9ca5f96647577b8aa6f3df30519c46bd448f5c425af0b2/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299", size = 400040, upload-time = "2026-10-04T16:30:37.76Z" }, + { url = "https://files.pythonhosted.org/packages/cf/a6/18cca7a878dc7fa95165a83343fd4d7b65643fd22e54e47340a451121d5c/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531", size = 551849, upload-time = "2026-10-04T16:30:39.443Z" }, + { url = "https://files.pythonhosted.org/packages/e4/6d/1f5685e20f39604691bdc3c05aaa6b8bd2f954e9e996477adf2376768e33/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb", size = 614842, upload-time = "2026-10-04T16:30:41.231Z" }, + { url = "https://files.pythonhosted.org/packages/c6/25/98652109fd9f7e10268dd4571aa52b81987001b806f37ef1a18260de714a/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa", size = 582606, upload-time = "2026-10-04T16:30:43.345Z" }, + { url = "https://files.pythonhosted.org/packages/19/03/11ca09099bab5f53373a80a334c424ec917c13d050760a59499d2af5171e/rpds_py-2026.9.1-cp314-cp314t-win32.whl", hash = "sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569", size = 203341, upload-time = "2026-10-04T16:30:44.954Z" }, + { url = "https://files.pythonhosted.org/packages/6f/8a/88909e3ffd9f47f5b58211473875d8c3c09079f0058c46fb72c55a702a26/rpds_py-2026.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e", size = 222843, upload-time = "2026-10-04T16:30:46.486Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b7/a662f367d4896dd0a10cef2fc91f10b7f08af1c10858e287e019563f338d/rpds_py-2026.9.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9", size = 347463, upload-time = "2026-10-04T16:30:48.203Z" }, + { url = "https://files.pythonhosted.org/packages/ae/3f/ad45d03df4f84ebae5439577ee81f3999d182711e82235c8037b6528890e/rpds_py-2026.9.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25", size = 342051, upload-time = "2026-10-04T16:30:49.872Z" }, + { url = "https://files.pythonhosted.org/packages/7e/31/3dcd68c13d4bcc59c1f7eb33ac8e80698f06f3eb0d8a1e06419836071c20/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871", size = 374143, upload-time = "2026-10-04T16:30:51.508Z" }, + { url = "https://files.pythonhosted.org/packages/cf/0d/68c1f058a250fbd1380ebda9fc227cbf50117adf8ffe8161ef383ea79f68/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91", size = 378604, upload-time = "2026-10-04T16:30:53.206Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d6/2d4c59b85397cb4800594fadf692688ccf5ce556adc930e7a5bf21061a5e/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f", size = 490790, upload-time = "2026-10-04T16:30:54.925Z" }, + { url = "https://files.pythonhosted.org/packages/da/04/7e05dc3aebaf52f4e026766bd668fdd09a9d0e23f64a14686b36b3501892/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d", size = 393146, upload-time = "2026-10-04T16:30:56.625Z" }, + { url = "https://files.pythonhosted.org/packages/57/ca/e2e9a0a46a74ed51a0498ba1fe10f4ea6b2d9a155f372a2f91e51f18cf10/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945", size = 372022, upload-time = "2026-10-04T16:30:58.295Z" }, + { url = "https://files.pythonhosted.org/packages/ba/cb/8f8774df5134e23424372838bcc5c7ed4127d723e1ff52f7bebd4dcb2563/rpds_py-2026.9.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297", size = 377092, upload-time = "2026-10-04T16:30:59.984Z" }, + { url = "https://files.pythonhosted.org/packages/90/02/8d7095d73bf9114219be40230baa5df00611e0a82ed9517779ff9c19f82b/rpds_py-2026.9.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0", size = 400830, upload-time = "2026-10-04T16:31:01.721Z" }, + { url = "https://files.pythonhosted.org/packages/ec/02/8206856f8f363cd042a8315dc86b3912f5dcb6d3c66bbb24b69c2bfb0775/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9", size = 551478, upload-time = "2026-10-04T16:31:03.472Z" }, + { url = "https://files.pythonhosted.org/packages/41/6b/36211f1bb1f0b0313f496d92f5905b74ea107f27cb16fa3355a82f04575e/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6", size = 615173, upload-time = "2026-10-04T16:31:05.281Z" }, + { url = "https://files.pythonhosted.org/packages/35/77/cda0c4a6f055446b692f0ed5692f73707cafd3dff82672ede31b1a9b59de/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7", size = 579653, upload-time = "2026-10-04T16:31:07.065Z" }, + { url = "https://files.pythonhosted.org/packages/74/ec/d8385f446240aed643b9e92a5055cff3015cc04a13c61f73b2883c478ed5/rpds_py-2026.9.1-cp315-cp315-win32.whl", hash = "sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429", size = 206498, upload-time = "2026-10-04T16:31:08.989Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a5/71b5cd00e0521e3b6b81828baea368c62b6b700ebdd9554cd7d41ddf12fa/rpds_py-2026.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15", size = 223121, upload-time = "2026-10-04T16:31:10.84Z" }, + { url = "https://files.pythonhosted.org/packages/33/58/dba857c3bc8221b31b62eb170a3080f4f191de79f047200389b7ed1b06a7/rpds_py-2026.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009", size = 218741, upload-time = "2026-10-04T16:31:12.592Z" }, + { url = "https://files.pythonhosted.org/packages/5b/d0/320ab28ccc1415eeb509d68682b0014fb74690cd49f1c2d29a232475af50/rpds_py-2026.9.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0", size = 349719, upload-time = "2026-10-04T16:31:14.48Z" }, + { url = "https://files.pythonhosted.org/packages/56/88/f5b12f1358f443c08b7ce3cc8391d82d335f4872580e2e097847fd36087a/rpds_py-2026.9.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a", size = 343267, upload-time = "2026-10-04T16:31:16.827Z" }, + { url = "https://files.pythonhosted.org/packages/f7/0c/c765b0059d532acb3b9c45d781ccc22f15a96dbe443d00903f643ba9df10/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d", size = 374555, upload-time = "2026-10-04T16:31:18.931Z" }, + { url = "https://files.pythonhosted.org/packages/6b/8a/cafddfda77564a10cd21184640c3bffda6a2b8d20972fb5dedd5e0166328/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db", size = 378346, upload-time = "2026-10-04T16:31:20.75Z" }, + { url = "https://files.pythonhosted.org/packages/b9/01/5e626016eff72c183bf6c96539240cace15d402468647a453ec08415b2fc/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250", size = 492373, upload-time = "2026-10-04T16:31:22.614Z" }, + { url = "https://files.pythonhosted.org/packages/3b/9c/15a2469e9389242f46896b3f0a01d68caea8a5a35c011fcb05ef333aae73/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f", size = 394371, upload-time = "2026-10-04T16:31:24.768Z" }, + { url = "https://files.pythonhosted.org/packages/63/f5/c100ff77e1e6366e947c75969c258fdfc4b7bc5bbfe7351e62ffbf2a1228/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018", size = 375132, upload-time = "2026-10-04T16:31:26.588Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f4/fe0269c9de253e99c81cabc12b8971a5feaa083debdaff1221e06264d9e3/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d", size = 377642, upload-time = "2026-10-04T16:31:28.677Z" }, + { url = "https://files.pythonhosted.org/packages/05/65/b34a7b257baccff8f4a24a722933166d4941d5ebdc9c3f4bc4ffcd5ce4f4/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b", size = 400855, upload-time = "2026-10-04T16:31:30.802Z" }, + { url = "https://files.pythonhosted.org/packages/98/32/844e54176b6071b90b38a564e6940bc6eb8f97b2890dc709c19db9dec0f4/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6", size = 552573, upload-time = "2026-10-04T16:31:32.709Z" }, + { url = "https://files.pythonhosted.org/packages/17/73/6041d20729dffbfdf155c02d65be58bc225a1c1fb548fd87c23ef306138f/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad", size = 615840, upload-time = "2026-10-04T16:31:34.565Z" }, + { url = "https://files.pythonhosted.org/packages/af/9e/418094adaee6b056ce199051b255448ed872829051e341b2294c80da0977/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903", size = 582764, upload-time = "2026-10-04T16:31:36.665Z" }, + { url = "https://files.pythonhosted.org/packages/3d/9b/1698ebf6b840ddfe8b472198abbed6ace35c6e398faeecd6c47dae742a4e/rpds_py-2026.9.1-cp315-cp315t-win32.whl", hash = "sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b", size = 203795, upload-time = "2026-10-04T16:31:38.53Z" }, + { url = "https://files.pythonhosted.org/packages/8a/e2/91f70d804c61f8eac39a417e82aa1024f655ab9e8bdd7393b196242bc41b/rpds_py-2026.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567", size = 223037, upload-time = "2026-10-04T16:31:40.468Z" }, + { url = "https://files.pythonhosted.org/packages/a3/90/a9ba81408369d34c1aca73319c15adc91ed45c1d21e9e8ee4832ffb7fe0b/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4", size = 381109, upload-time = "2026-10-04T16:32:08.994Z" }, + { url = "https://files.pythonhosted.org/packages/b3/44/5192a0bed94cec86bd2a5e1cc5a1bb8f7eec3aec907eacd2deb13e87e326/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759", size = 388222, upload-time = "2026-10-04T16:32:11.321Z" }, + { url = "https://files.pythonhosted.org/packages/92/cd/5356549711448f18b52f7a11ffbe90f1228774996fbf3c6cd1b18d22abaf/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb", size = 500384, upload-time = "2026-10-04T16:32:13.478Z" }, + { url = "https://files.pythonhosted.org/packages/7a/88/ddda9d28adfe33119c75b2e733d4ba7e326f41d7e1b1093951771768ca48/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82", size = 401661, upload-time = "2026-10-04T16:32:15.653Z" }, + { url = "https://files.pythonhosted.org/packages/32/c3/bb59ba16a6b4a57995d15b8c04c00f28df3b938c4dcdde48fbe0f73edb0c/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c", size = 380748, upload-time = "2026-10-04T16:32:17.727Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b8/0580faa1c5a32ddc160130dd7ae54d2d007272a89a40a6b5db3e50f9f585/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14", size = 385731, upload-time = "2026-10-04T16:32:19.855Z" }, + { url = "https://files.pythonhosted.org/packages/bf/70/f73564642bbe3322c7eeef2c2f258cf040b71c41a430b532e59d04a1b838/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c", size = 412131, upload-time = "2026-10-04T16:32:22.285Z" }, + { url = "https://files.pythonhosted.org/packages/8c/5d/17fff2e1f8f68721a2afb5cb48f7e442c751bb6b4883157c5abaf618cd08/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68", size = 558193, upload-time = "2026-10-04T16:32:24.4Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d0/869ab6fb08531f97aae4a780b4d61b4190d8aef48fe054ee28bcf7114466/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_i686.whl", hash = "sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da", size = 622448, upload-time = "2026-10-04T16:32:26.844Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a5/9672e532fe02cd3b92c78cfd8743abca939d96853006c63835009a1ecb6f/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448", size = 591126, upload-time = "2026-10-04T16:32:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/80/ef/3a9f8e4279c7920af561deed4cb7ebebed2794a8f608cf404d5eef14a105/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0", size = 357108, upload-time = "2026-10-04T16:32:31.641Z" }, + { 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-learn" version = "1.9.1" @@ -2975,6 +3578,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, ] +[[package]] +name = "soupsieve" +version = "4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/95/48/21a393ff731b8f928fa4f8176f9a7ceba2252ee60a5149f25b45c292aa5c/soupsieve-4.1.tar.gz", hash = "sha256:ca9abf7126667010d8f6e9b39bfc1bc3b23c8aed9bcb0f54a754dde969bb8aab", size = 161955, upload-time = "2026-11-10T01:59:50.399Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/73/6a2087c72975cfc07394623bca8d17654342ea4055ae368deafe5a81a542/soupsieve-4.1-py3-none-any.whl", hash = "sha256:e4d667b3974ce6e038e7390486b8093369854a1d345ffdd4c121dfc4a782e809", size = 52302, upload-time = "2026-11-10T01:59:48.571Z" }, +] + [[package]] name = "sqlalchemy" version = "2.0.54" @@ -3048,6 +3660,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d9/50/f00935da0ec7cbf325f8dc4f772ae46fbc7b672dd62876e73f0a94adda57/sqlparse-0.6.0-py3-none-any.whl", hash = "sha256:b861c0288ce2fa56209a9a6412d2e066ac664b3873b89c26c9d8415e8e32996f", size = 50070, upload-time = "2026-08-13T19:16:04.062Z" }, ] +[[package]] +name = "stack-data" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asttokens" }, + { name = "executing" }, + { name = "pure-eval" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" }, +] + [[package]] name = "starlette" version = "1.9.0" @@ -3070,6 +3696,68 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/43/3f/f88a53f60a472b46f4023f56d204dd7de33d34c5d2acbfa0d70a674e639e/threadpoolctl-3.7.0-py3-none-any.whl", hash = "sha256:cd8b60b5641b45c67bbf73c64c843235fc2d8a480c87389f52f5dbee893b86be", size = 26362, upload-time = "2026-09-15T15:46:19.168Z" }, ] +[[package]] +name = "tinycss2" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "webencodings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/ae/2ca4913e5c0f09781d75482874c3a95db9105462a92ddd303c7d285d3df2/tinycss2-1.5.1.tar.gz", hash = "sha256:d339d2b616ba90ccce58da8495a78f46e55d4d25f9fd71dfd526f07e7d53f957", size = 88195, upload-time = "2025-11-23T10:29:10.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/45/c7b5c3168458db837e8ceab06dc77824e18202679d0463f0e8f002143a97/tinycss2-1.5.1-py3-none-any.whl", hash = "sha256:3415ba0f5839c062696996998176c4a3751d18b7edaaeeb658c9ce21ec150661", size = 28404, upload-time = "2025-11-23T10:29:08.676Z" }, +] + +[[package]] +name = "tornado" +version = "6.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/64/2b/8ff2b41620cbba0eeb0862fed21dcaa5a2ad36c6dd9bb465f9ff7a147be2/tornado-6.6.1.tar.gz", hash = "sha256:28e6311402af59c8b02e3fa0f5e7d8eb465b25081381803b127d97e6a4395d5a", size = 623388, upload-time = "2026-11-09T21:09:22.71Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/d3/ef3a4d38d1a72c52ad07483ed760dbb93027d28f19c3a2d98148abdd63e1/tornado-6.6.1-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:a8d3e6acde5a80d13b13b5e4c7c226ca682f31d0a62b6c33cea038714bc2de1b", size = 533249, upload-time = "2026-11-09T21:08:22.475Z" }, + { url = "https://files.pythonhosted.org/packages/38/4d/c65ea949a3cdc185f1afac8c337074d4f2d029b48293d2db4d2c3dea4849/tornado-6.6.1-cp311-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1b6ff57cc69b339f8feb9e7b567b0e0eacb16bfaf234159496623ef7a67ba640", size = 534470, upload-time = "2026-11-09T21:08:24.27Z" }, + { url = "https://files.pythonhosted.org/packages/03/ff/20911f85dd399b56761496e8138810e8608ea25f0912377f4205d52af853/tornado-6.6.1-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da6ce2da215810d56539fa6cac77d9e27f4d8139c6868c53436b2fe933f43c79", size = 535446, upload-time = "2026-11-09T21:08:25.625Z" }, + { url = "https://files.pythonhosted.org/packages/be/70/a4a159dd4f1fef39ff8eadae655b133a85722b39087a89e21ce463af9832/tornado-6.6.1-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8cd28b2cacbe63d53e28a38546a3492b488417eeb3f7ecf10954476fc2508882", size = 535664, upload-time = "2026-11-09T21:08:27.191Z" }, + { url = "https://files.pythonhosted.org/packages/ed/d5/db70d5d23d3b4eaea0b26b710f28d2ca387bb44e68ccfede60ba3bbc2096/tornado-6.6.1-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:25b2619274bca77d0eb7b4d96dcf2d1142bb9bf172ad6a7491a1e1f82e6e48fa", size = 534660, upload-time = "2026-11-09T21:08:28.78Z" }, + { url = "https://files.pythonhosted.org/packages/f7/f6/0528ee039266902e707edd9996ee3ce7364dc1baf08bed585d8e6fb3ccd0/tornado-6.6.1-cp311-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:77dd6e0c659fdc45824e0746988ac5c060c2a9fee9b8cbbcdb999b3f29d3cd10", size = 532834, upload-time = "2026-11-09T21:08:30.432Z" }, + { url = "https://files.pythonhosted.org/packages/a6/bb/b733df2d487a78283080663bd6d96955121b58b6d445d9cb832607da9786/tornado-6.6.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b62fded687e55acaf9e36c1230b006066a35b3f6df093ba1fd3b2ff592070e1d", size = 535289, upload-time = "2026-11-09T21:08:31.692Z" }, + { url = "https://files.pythonhosted.org/packages/a7/7c/c81cb83f2bbb5740fcba1eb83d794b6d6fab2063b16a475cc9039266091e/tornado-6.6.1-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:ecef88054d8a77878f61061ff67dfc5e1c17d1f7334890ab508b310e8e68ee46", size = 535382, upload-time = "2026-11-09T21:08:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/8a/ae/c499da4cc8be1c1f31a5d8df2328f2aae091de2db13302ad5c20ed704ec4/tornado-6.6.1-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:ca95e762df1ca761f330e3f2a034c15ac144569844b52527a5a9eca9f524c0f1", size = 534534, upload-time = "2026-11-09T21:08:34.57Z" }, + { url = "https://files.pythonhosted.org/packages/61/7c/6b163c9e58ca9df0c941bda9ba2dcabbd87ecb81c5fa546f54eeac689232/tornado-6.6.1-cp311-abi3-musllinux_1_2_s390x.whl", hash = "sha256:8cae3d8f2585be01670da9fd5010c61724c51b61ecd4c06820e95874739daf7c", size = 534728, upload-time = "2026-11-09T21:08:35.828Z" }, + { url = "https://files.pythonhosted.org/packages/18/11/b5107ac6a278387635d73d283e7ab5a5c76fb8ccf402efa57006ea25852f/tornado-6.6.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6596f3e939962f13099ce8d1a96b83226e908ca369b193370a6efa84585a1601", size = 534676, upload-time = "2026-11-09T21:08:37.209Z" }, + { url = "https://files.pythonhosted.org/packages/65/df/0574c4479c565d9233def796afc9179fa840f41f8c240f740609f746da67/tornado-6.6.1-cp311-abi3-win32.whl", hash = "sha256:0f0f596a0dab6826aa21d103c7bc242e3fb7cfc99c5c3d44a35ba8c83abbdca4", size = 535565, upload-time = "2026-11-09T21:08:38.518Z" }, + { url = "https://files.pythonhosted.org/packages/36/57/35439a779582e3b19c98e799b6a41519fb3bdaa3a21b7a94ce4dd7b3b732/tornado-6.6.1-cp311-abi3-win_amd64.whl", hash = "sha256:5cb82ca38596e1350fceaf994f287847f82f7b8436380d36ba0937a03107d0ee", size = 535806, upload-time = "2026-11-09T21:08:39.892Z" }, + { url = "https://files.pythonhosted.org/packages/89/b8/2cb42845af01ea7e70ac23e6f6fe2f26b9b158bce186c6991c057c9abe1d/tornado-6.6.1-cp311-abi3-win_arm64.whl", hash = "sha256:58d2f47e7b54fded3407dbbbe4e59d29ca627f85bf6c0f21f0b151c6c7fc9c53", size = 535825, upload-time = "2026-11-09T21:08:41.339Z" }, + { url = "https://files.pythonhosted.org/packages/10/de/cfeae9e75c144ca22018ee3b858e343c1658d6edd2184f35d810ec1ef789/tornado-6.6.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ed0bc5a1a9f6346e7bdadc106fa2d4c6e79d71d8b2df4366260ab3baf36a8399", size = 533356, upload-time = "2026-11-09T21:08:42.603Z" }, + { url = "https://files.pythonhosted.org/packages/3d/d8/7812a729c797fb8c15748c9a69faeaaa13630075cf9b76ba9f7fbcfb7f42/tornado-6.6.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:54c80f9bed0bf1533ecf5a90dc59651645622d62b0bcffa2692d108a1f794917", size = 537511, upload-time = "2026-11-09T21:08:43.84Z" }, + { url = "https://files.pythonhosted.org/packages/70/47/ebef304487feea6d8efb6a7d2642964ecb1f5cc785f687628e1d7cac4326/tornado-6.6.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb67ba2cbf598e842f14684eab029a5a4ba7ab587e8c4e40940a77ed0596b31e", size = 538566, upload-time = "2026-11-09T21:08:45.203Z" }, + { url = "https://files.pythonhosted.org/packages/a3/6a/87532e6745c415eb2daa9bc1c9c89c69ce9e8255b1c0bde9938f3299440b/tornado-6.6.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d83bac141bd9360d8e995ec512097be19ead2e9213c3e7088510a036f3192b8d", size = 538793, upload-time = "2026-11-09T21:08:46.478Z" }, + { url = "https://files.pythonhosted.org/packages/e4/c7/26af60f71f7c32f19257bad58711500628f579edf1a2c3d8328ad15aae04/tornado-6.6.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:60aad449dbcebaa8d69bff50c6ba39858fab8d256e779a99bb30ebf6724b9b48", size = 537691, upload-time = "2026-11-09T21:08:47.975Z" }, + { url = "https://files.pythonhosted.org/packages/ba/9d/af233b8bf4311d3466099ab267eb595ec6f1655607d290dc7f706b6dbd6f/tornado-6.6.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b9ce0d6548bd73b1329075b247d3fdc61538922f558ee42059e08f5df53fc197", size = 535877, upload-time = "2026-11-09T21:08:49.76Z" }, + { url = "https://files.pythonhosted.org/packages/95/66/78e7583ce69f66e5177c65988a98373be2ab25c1d22405d274e037acbc58/tornado-6.6.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ce5a18654f5d56d11400ab5d87103660e14deceab41818a06a42acc8dbbe427d", size = 538295, upload-time = "2026-11-09T21:08:51.221Z" }, + { url = "https://files.pythonhosted.org/packages/a3/3a/ad336d4994547cf268a3bd6d10f6ef691e1e888fc776940c0bfe02e8d85c/tornado-6.6.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:3298fce72c35f836eab4c4db8b960104ff1ea718033a6b5e236f04efe3a1b6e1", size = 538349, upload-time = "2026-11-09T21:08:52.761Z" }, + { url = "https://files.pythonhosted.org/packages/cf/cf/563d24516afd266f6b3c3f1c7ac15ad39b8668966d2bccce917c169ab0c0/tornado-6.6.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:0223e827cedf4e35ebb035e57a0d9974563cd043e3a53f8bb72a859b6f53777e", size = 537469, upload-time = "2026-11-09T21:08:54.279Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ea/1705ff4014c8bad5d7045022647156cfebd6c7014886da47e13512d27c08/tornado-6.6.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:533185c89be3ffb01656c9425da4ff42587a3af784b37d39fe762e8fce3b2dbe", size = 537624, upload-time = "2026-11-09T21:08:55.648Z" }, + { url = "https://files.pythonhosted.org/packages/50/5d/421168e62c8b80e3ef88f80d642e9a7e5b1d0c6e8cd136d99064f663951c/tornado-6.6.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fbaa022a49a27b65668592cf43b898ff3978cbe4e6926fdfe24dbef59053bd26", size = 537632, upload-time = "2026-11-09T21:08:57.797Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b4/13b2f98a3141c152915fa3e69531a04bdc1cd7dd203f442136f3792a486f/tornado-6.6.1-cp314-cp314t-win32.whl", hash = "sha256:4bc6c60faf86162df25ba2ff5611d27b6ef8226de9d61c07a0fab53c169630a5", size = 535424, upload-time = "2026-11-09T21:08:59.145Z" }, + { url = "https://files.pythonhosted.org/packages/84/83/6d54c37b3e437ab0ff2bddd71249c6ea2a17051104dd2995cb4e181e95a7/tornado-6.6.1-cp314-cp314t-win_amd64.whl", hash = "sha256:71c16b382b22d3234913a3f74a1ea84bede197d11eb03871df17bb123088dfa5", size = 535715, upload-time = "2026-11-09T21:09:00.456Z" }, + { url = "https://files.pythonhosted.org/packages/d4/38/75419d8cd577b7c4f335f4c5e75f127af286545ad49047a73afffdf877fe/tornado-6.6.1-cp314-cp314t-win_arm64.whl", hash = "sha256:510c7261ed986ecd6f74edc1a13412759e7abc2e8be3a6c85e15f6c53e1f3c84", size = 535718, upload-time = "2026-11-09T21:09:01.783Z" }, + { url = "https://files.pythonhosted.org/packages/91/8b/96e460653f3e2ad83d70328414394132d73d5655047c692ce7b69ae2f6c0/tornado-6.6.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:01dc73e3697eb94d78c42e03931ab621da97d12fdfb6339e64ff5a934b220fcf", size = 533376, upload-time = "2026-11-09T21:09:03.097Z" }, + { url = "https://files.pythonhosted.org/packages/1a/1e/644bace0700e533235f01ffa68a7b5e3d6cc9eb7380e3929039d04b648b9/tornado-6.6.1-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:95bd4751357bef52aa655e236b9667ff054885de4b118e4ce9ba5c06e12ef5d0", size = 537696, upload-time = "2026-11-09T21:09:04.519Z" }, + { url = "https://files.pythonhosted.org/packages/e6/0a/afccc23d1ed71bcb1ce4a5b6e0f61f82c7a0b275f3b377ee7aee6680a565/tornado-6.6.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:29bce3190c2973fcd2171c95eeab8bf06d2f7a7eb107455ce3e4662c704aecdb", size = 538796, upload-time = "2026-11-09T21:09:05.956Z" }, + { url = "https://files.pythonhosted.org/packages/e5/24/69692f8ba851ed2738c2623eab592360d646f0a2e16b6deea16516aa8595/tornado-6.6.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b777fbe0bdb2c4dc764aadf5f70e9b23b2e536c339d61c799d3ea1b575a7c285", size = 538951, upload-time = "2026-11-09T21:09:07.298Z" }, + { url = "https://files.pythonhosted.org/packages/00/82/234306b41b33600a470da7e595b8064b85e2f509f64f5c1d39387c0abbb8/tornado-6.6.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:15443805d6b7aa11610cc6c5be7e71b4a93369aeb2ca5a13c2def53a3af5ba45", size = 537861, upload-time = "2026-11-09T21:09:08.857Z" }, + { url = "https://files.pythonhosted.org/packages/5b/87/6d13a60c320c0379cbfa4c2520b4ba076780c33e6a01ba3073fff74b71db/tornado-6.6.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b77ab23d1520c807d11e703e79b020d3bc3676a0f5ebc8531f46d3fac8aecb2f", size = 536178, upload-time = "2026-11-09T21:09:10.424Z" }, + { url = "https://files.pythonhosted.org/packages/96/c7/e27f2a21e05d7c5aa9886db7368436e6436880b85349072988b4f62422e3/tornado-6.6.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:872249311539281c1e8a5d8d6f27f478bf705a9bd931bf374b6b31b05177dfda", size = 538491, upload-time = "2026-11-09T21:09:11.968Z" }, + { url = "https://files.pythonhosted.org/packages/f3/c7/1f981336039c51d81ee6f895e3412178edc409bd709e38767365c55c0daa/tornado-6.6.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:08b808e8d3312c268f9fe1ffebfcfaaf342e7fe4ac40d219a7e1b58bac547d6f", size = 538491, upload-time = "2026-11-09T21:09:13.226Z" }, + { url = "https://files.pythonhosted.org/packages/5d/4f/7dafc65726778ac148b68c91920605892e84bf0ffcc02890aaf1a7d0ba8d/tornado-6.6.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:8d475f4053c693b5c1483eb4845824129b0b51c65712e736b3c2ea1c8f6080cd", size = 537775, upload-time = "2026-11-09T21:09:14.697Z" }, + { url = "https://files.pythonhosted.org/packages/a1/25/85c852307f9e49896b6dc5119f6a0131f5f6d97c478a687654c2c0c3f0f4/tornado-6.6.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:e923e75c9d641cdb8bbac60070a2dccdb684fc555af2bff48b0eaded0f88c2dc", size = 537798, upload-time = "2026-11-09T21:09:15.946Z" }, + { url = "https://files.pythonhosted.org/packages/60/43/a37ec29b0f98c3c639da495e1d547d6c44c69a6727b9864cf149bf346433/tornado-6.6.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a72f70b1aa630fa2106d39a025e2be75c272b7ec8233da94e2f407ea754cc32d", size = 537809, upload-time = "2026-11-09T21:09:17.265Z" }, + { url = "https://files.pythonhosted.org/packages/3b/d4/13973391071552e03acb308d93f6deb4fb535a769a6bbdafdb4cafcb2f91/tornado-6.6.1-cp315-cp315t-win32.whl", hash = "sha256:2fbfd2510b6163b189773155a8246c025cb260ccc7cd12ad18c36c54f5617bb9", size = 535422, upload-time = "2026-11-09T21:09:18.525Z" }, + { url = "https://files.pythonhosted.org/packages/19/94/c952b625904b63fdac5b747f2eeaca64ab5d36cdb8faff57effa57162d87/tornado-6.6.1-cp315-cp315t-win_amd64.whl", hash = "sha256:3c35091add5863feb9cf651851bb1b23592f1f9551b5dfed72837c83ea4e5b85", size = 535713, upload-time = "2026-11-09T21:09:20.061Z" }, + { url = "https://files.pythonhosted.org/packages/f8/62/8d0c0c42f3346f3f2455738d3bc689bbd8efba38abf7b90ab2b8294eae83/tornado-6.6.1-cp315-cp315t-win_arm64.whl", hash = "sha256:065bc741478b168df9baf754956a3010c04d1330bb45a84833d807c29e11b257", size = 535719, upload-time = "2026-11-09T21:09:21.317Z" }, +] + [[package]] name = "tqdm" version = "4.70.1" @@ -3082,6 +3770,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, ] +[[package]] +name = "traitlets" +version = "5.16.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" } +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 = "typeguard" version = "4.6.0" @@ -3214,7 +3911,7 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "models" }, + { name = "models", extra = ["notebooks"] }, { name = "openpyxl" }, { name = "pandas" }, { name = "pdfplumber" }, @@ -3272,6 +3969,15 @@ dev = [ { name = "reportlab", specifier = ">=4.0" }, ] +[[package]] +name = "webencodings" +version = "0.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d5/a0/8fd707bcb776a7be556bad06a2ea5fb9bd519df78ef8e26f70ccf0f38bff/webencodings-0.6.1.tar.gz", hash = "sha256:565f9ad031c702dae404e27a099e3e09186a3ab1b9520f06d215502b651fd910", size = 15001, upload-time = "2026-08-15T14:22:57.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/c6/040cbc72480d789a5f40d63fb484d3106554c4dfa2d2b70ad5022057750f/webencodings-0.6.1-py3-none-any.whl", hash = "sha256:7fab6269c8bf237c657876b52058ccb182e861518d1c695c1a9aaa8c1c105d5b", size = 8745, upload-time = "2026-08-15T14:22:56.31Z" }, +] + [[package]] name = "werkzeug" version = "3.1.8" -- 2.53.0 From 64d3d721e3a5d609b5a4e6ef55ca33e267efbf7e Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 15:29:52 -0600 Subject: [PATCH 18/24] Source forms as a partial, non-injective function into the catalog's codes, checked on the catalog How: `reference.source_mapping` keys a mapping by source system, result, normalized form and validity; `check_function` rejects a form that gives two codes while both mappings are in force, and `resolve` gives the code in force on a date, or none when nothing or two disagreeing mappings match. The catalog's own check of spellings (`_claves_de_extraccion`) now runs `check_function` on each result's codes, labels and aliases. Implications: the same rule serves the TOML today and any store of mappings with systems and dates; every catalog passes it. --- tests/test_source_mapping.py | 65 ++++++++++++ webapi/orchestration/reference/catalogs.py | 18 ++-- .../orchestration/reference/source_mapping.py | 98 +++++++++++++++++++ 3 files changed, 170 insertions(+), 11 deletions(-) create mode 100644 tests/test_source_mapping.py create mode 100644 webapi/orchestration/reference/source_mapping.py diff --git a/tests/test_source_mapping.py b/tests/test_source_mapping.py new file mode 100644 index 0000000..d53560a --- /dev/null +++ b/tests/test_source_mapping.py @@ -0,0 +1,65 @@ +"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`): +many forms to one code, no code for an unknown form, the same form read per source system and per date, and two +codes for one form rejected when they're in force together; and every catalog's TOML passing that check. + +Fixtures: none; the rows are built in each test. +""" + +import tomllib +from datetime import date + +import pytest +from webapi.orchestration.reference.catalogs import ruta_de_catalogo +from webapi.orchestration.reference.source_mapping import ( + SourceForm, ambiguities, check_function, from_result, normalize, resolve, +) + +HER2 = "biopsia.her2" +LAB_A = [SourceForm("lab_a", HER2, "3+", "H3", None, date(2026, 12, 31)), + SourceForm("lab_a", HER2, "Positivo", "H3", None, date(2026, 12, 31))] +LAB_B = [SourceForm("lab_b", HER2, "Positivo (score 3)", "H3", date(2027, 1, 1)), + SourceForm("lab_b", HER2, "Positivo", "H2", date(2027, 1, 1))] + + +def test_many_forms_give_one_code_and_an_unknown_form_none(): + """Pins down: the mapping isn't injective and is partial: several spellings, compared without case, accents or + extra spaces, give the same code; a spelling with no mapping gives None. Fails if `normalize` stops folding or + `resolve` invents a code.""" + assert {resolve(LAB_A, "lab_a", HER2, f) for f in ("3+", " positivo ", "POSITIVO")} == {"H3"} + assert resolve(LAB_A, "lab_a", HER2, "Equívoco") is None + assert normalize(" Positívo (score 3) ") == "POSITIVO (SCORE 3)" + + +def test_a_form_is_read_per_source_system_and_per_date(): + """Pins down: "Positivo" is H3 at lab A and H2 at lab B, and a mapping applies only to documents dated within its + validity. Fails if `resolve` ignores the system or the dates, letting one lab's spelling leak into another's.""" + rows = LAB_A + LAB_B + assert resolve(rows, "lab_a", HER2, "Positivo", date(2026, 6, 1)) == "H3" + assert resolve(rows, "lab_b", HER2, "Positivo", date(2027, 2, 1)) == "H2" + assert resolve(rows, "lab_b", HER2, "Positivo", date(2026, 6, 1)) is None + assert ambiguities(rows) == [] + + +def test_two_codes_for_one_form_in_force_together_are_rejected(): + """Pins down: a form mapped to two codes with overlapping validity breaks the function: `check_function` names + it and `resolve` gives None rather than either code. Two codes in validities that don't overlap, or the same + code twice, are fine. Fails if the overlap test or the code comparison is dropped.""" + clash = SourceForm("lab_b", HER2, "positivo", "H3", date(2027, 6, 1)) + with pytest.raises(ValueError, match="se escribe igual para 'H2' y 'H3'"): + check_function(LAB_B + [clash]) + assert resolve(LAB_B + [clash], "lab_b", HER2, "Positivo", date(2027, 7, 1)) is None + corrected = [LAB_B[1]._replace(valid_to=date(2027, 5, 31)), clash] + check_function(corrected) + assert resolve(corrected, "lab_b", HER2, "Positivo", date(2027, 7, 1)) == "H3" + check_function(LAB_B + [LAB_B[0]._replace(form="POSITIVO (SCORE 3)")]) + + +@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) +def test_every_catalog_s_spellings_are_a_function(proyecto): + """Pins down: in each domain's TOML, every result's codes, labels and aliases map to one value each. Fails when + an edit to a catalog gives one spelling two values.""" + estudios = tomllib.loads(ruta_de_catalogo(proyecto).read_text(encoding="utf-8")) + rows = [row for estudio_id, estudio in estudios.items() + for nombre, resultado in estudio.get("resultados", {}).items() + for row in from_result(f"{estudio_id}.{nombre}", resultado)] + check_function(rows) diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py index 2cf7b86..2691940 100644 --- a/webapi/orchestration/reference/catalogs.py +++ b/webapi/orchestration/reference/catalogs.py @@ -15,10 +15,10 @@ from pathlib import Path from typing import NamedTuple import core -from extraction.nlp.text import fold from core.indicadores.catalogos import TIPOS_DE_VALOR from sqlmodel import SQLModel +from webapi.orchestration.reference.source_mapping import check_function, from_result from webapi.orchestration.tables import TablasKit # Los catálogos viven en Core, junto a los modelos de sus tablas. @@ -165,7 +165,8 @@ def resultados_extraibles(proyecto: str) -> dict[str, ResultadoExtraible]: def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None: - """The extraction keys of a result: captions as a non-empty list of texts, and no spelling on two values.""" + """The extraction keys of a result: captions as a non-empty list of texts, and its spellings a function into + its values (`source_mapping.check_function`).""" etiquetas = resultado.get("etiquetas_fuente") if etiquetas is not None and (not isinstance(etiquetas, list) or not etiquetas or not all(isinstance(e, str) and e.strip() for e in etiquetas)): @@ -176,15 +177,10 @@ def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None: raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo {resultado.get('tipo_valor')} no se extrae de texto.") if resultado.get("buscar_en_texto") and resultado.get("tipo_valor") != "codigo": raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo se busca como mención en el texto.") - de: dict[str, str] = {} - for valor in resultado.get("valores", ()): - for forma in (valor.get("etiqueta", ""), *valor.get("alias", ())): - clave = " ".join(fold(forma).split()) - if de.get(clave, valor["valor"]) != valor["valor"]: - raise CatalogoInvalido( - f"{resultado_id}: {forma!r} se escribe igual para {de[clave]!r} y {valor['valor']!r}." - ) - de[clave] = valor["valor"] + try: + check_function(from_result(resultado_id, resultado)) + except ValueError as e: + raise CatalogoInvalido(str(e)) from None def _leer(ruta: Path) -> dict: diff --git a/webapi/orchestration/reference/source_mapping.py b/webapi/orchestration/reference/source_mapping.py new file mode 100644 index 0000000..143e126 --- /dev/null +++ b/webapi/orchestration/reference/source_mapping.py @@ -0,0 +1,98 @@ +"""How a source writes the catalog's values: a partial, non-injective function into a fixed set of codes. + +A source form (a spelling, an abbreviation, a lab's own code) maps to one `valor_id` of one result: + + f : (source system, resultado_id, normalized form, document date) -> valor_id + +- non-injective: many forms give the same code ("3+", "Positivo (score 3)" -> H3); +- partial: a form with no mapping gives nothing, and the observation keeps it as `valor_fuente`, counted as out of + catalog, until a mapping is added; +- per source system and per date: the same form may mean different codes at two labs, and a mapping applies to the + documents dated within its validity; +- into a fixed set: a mapping only names a `valor_id` the catalog defines (`cat_valor`). + +For `f` to be a function, two mappings in force on the same date can't give the same key two codes: +`check_function` rejects that, and `resolve` returns nothing for a key it still finds ambiguous, so the observation +goes back to the out-of-catalog queue instead of keeping a code. Today the mappings come from the catalog's TOML +(`from_result`: one system, always in force); any other store of mappings gives `SourceForm` rows and is checked +and read the same way. +""" + +from collections import defaultdict +from datetime import date +from typing import Iterable, NamedTuple + +from extraction.nlp.text import fold + +CATALOG = "catalogo" # the source system of the mappings written in the catalog's TOML + + +class SourceForm(NamedTuple): + """One mapping: how `system` writes `value_id` of `result_id`, in force from `valid_from` to `valid_to`.""" + + system: str + result_id: str + form: str + value_id: str + valid_from: date | None = None # None: since always + valid_to: date | None = None # None: while current + + @property + def key(self) -> tuple[str, str, str]: + return self.system, self.result_id, normalize(self.form) + + def in_force(self, on: date | None) -> bool: + return on is None or ((self.valid_from is None or self.valid_from <= on) + and (self.valid_to is None or on <= self.valid_to)) + + +class AmbiguousForm(NamedTuple): + """Two mappings of the same key whose validities overlap and whose codes differ.""" + + first: SourceForm + second: SourceForm + + +def normalize(form: str) -> str: + """What is compared: uppercase, without accents, single spaces.""" + return " ".join(fold(form).split()) + + +def ambiguities(rows: Iterable[SourceForm]) -> list[AmbiguousForm]: + """Every pair of mappings that would give one key two codes on some date.""" + by_key: dict[tuple, list[SourceForm]] = defaultdict(list) + for row in rows: + by_key[row.key].append(row) + found = [] + for same_key in by_key.values(): + for i, a in enumerate(same_key): + found += [AmbiguousForm(a, b) for b in same_key[i + 1:] if a.value_id != b.value_id and _overlap(a, b)] + return found + + +def check_function(rows: Iterable[SourceForm]) -> None: + """Raises `ValueError` naming each form that maps to two codes while both mappings are in force.""" + found = ambiguities(rows) + if found: + raise ValueError("; ".join(f"{a.first.result_id}: {a.first.form!r} se escribe igual para " + f"{a.first.value_id!r} y {a.second.value_id!r}" for a in found) + ".") + + +def resolve(rows: Iterable[SourceForm], system: str, result_id: str, form: str, on: date | None = None) -> str | None: + """The code `form` maps to on `on` for `system`; None when no mapping in force matches it or two disagree.""" + key = (system, result_id, normalize(form)) + codes = {r.value_id for r in rows if r.key == key and r.in_force(on)} + return codes.pop() if len(codes) == 1 else None + + +def from_result(result_id: str, result: dict, system: str = CATALOG) -> list[SourceForm]: + """A catalog result's mappings: each value's code, label and aliases, in force always.""" + return [SourceForm(system, result_id, form, value["valor"]) + for value in result.get("valores", ()) + for form in (value["valor"], value.get("etiqueta", ""), *value.get("alias", ())) if form.strip()] + + +def _overlap(a: SourceForm, b: SourceForm) -> bool: + starts_before_b_ends = a.valid_from is None or b.valid_to is None or a.valid_from <= b.valid_to + b_starts_before_a_ends = b.valid_from is None or a.valid_to is None or b.valid_from <= a.valid_to + return starts_before_b_ends and b_starts_before_a_ends -- 2.53.0 From 73cbf0cfb846839e393bd9b0d9ec5854fe0d0e2a Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 15:31:21 -0600 Subject: [PATCH 19/24] The catalog step seeds each domain's mappings, and a mapping is written only if the function still holds How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the `catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet (`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add` with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's repository. Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and a second code for a form in force is refused before it's written. Loads still read the TOML's aliases. --- tests/test_orquestacion_plata.py | 7 +- tests/test_source_mapping.py | 57 +++++++++++++++- webapi/orchestration/cycle.py | 14 +++- .../orchestration/reference/source_mapping.py | 68 +++++++++++++++++-- webapi/orchestration/repositories.py | 3 + 5 files changed, 138 insertions(+), 11 deletions(-) diff --git a/tests/test_orquestacion_plata.py b/tests/test_orquestacion_plata.py index ae67df9..dea96b8 100644 --- a/tests/test_orquestacion_plata.py +++ b/tests/test_orquestacion_plata.py @@ -75,7 +75,9 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base): del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados), "valores": len(catalogo.valores)} - assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0} + conteos = base.run("catalogs")["catalogs"] + assert conteos.pop("mapeos_nuevos") > 0 + assert conteos == {**del_toml, "retirados": 0} assert filas_del_catalogo(base) == del_toml @@ -83,7 +85,8 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base): base.run("catalogs") antes = filas_del_catalogo(base) - assert base.run("catalogs")["catalogs"]["retirados"] == 0 + conteos = base.run("catalogs")["catalogs"] + assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0) assert filas_del_catalogo(base) == antes diff --git a/tests/test_source_mapping.py b/tests/test_source_mapping.py index d53560a..85e5db4 100644 --- a/tests/test_source_mapping.py +++ b/tests/test_source_mapping.py @@ -1,8 +1,10 @@ """What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`): many forms to one code, no code for an unknown form, the same form read per source system and per date, and two -codes for one form rejected when they're in force together; and every catalog's TOML passing that check. +codes for one form rejected when they're in force together; every catalog's TOML passing that check; and, in each +domain's database, the catalog step seeding `cat_mapeo` without touching a stored row and `register` refusing a +mapping that breaks the function. -Fixtures: none; the rows are built in each test. +Fixtures: `base` (conftest), each domain's migrated fixture database; the other tests build their rows. """ import tomllib @@ -11,7 +13,7 @@ from datetime import date import pytest from webapi.orchestration.reference.catalogs import ruta_de_catalogo from webapi.orchestration.reference.source_mapping import ( - SourceForm, ambiguities, check_function, from_result, normalize, resolve, + CATALOG, SourceForm, ambiguities, check_function, from_result, normalize, register, resolve, ) HER2 = "biopsia.her2" @@ -63,3 +65,52 @@ def test_every_catalog_s_spellings_are_a_function(proyecto): for nombre, resultado in estudio.get("resultados", {}).items() for row in from_result(f"{estudio_id}.{nombre}", resultado)] check_function(rows) + + +# --- the stored mappings, in each domain --- + + +def a_coded_result(base) -> tuple[str, str, str]: + """A coded result of the domain's catalog with two values: (resultado_id, first valor_id, second valor_id).""" + estudios = tomllib.loads(ruta_de_catalogo(base.proyecto).read_text(encoding="utf-8")) + for estudio_id, estudio in estudios.items(): + for nombre, resultado in estudio.get("resultados", {}).items(): + valores = resultado.get("valores", ()) + if len(valores) >= 2: + return f"{estudio_id}.{nombre}", valores[0]["valor"], valores[1]["valor"] + raise AssertionError("el catálogo no tiene un resultado codificado con dos valores") + + +def test_the_catalog_step_seeds_the_mappings_and_keeps_what_a_person_changed(base): + """Pins down: the catalog step adds the catalog's own mappings (each value's code among them) and, run again, + adds nothing and leaves a person's row for a new form as it is. Fails if the step stops seeding or a deploy + replaces stored rows.""" + base.run("catalogs") + mappings = base.ctx.repos.silver.mappings + resultado, primero, segundo = a_coded_result(base) + sembradas = mappings.forms(sistema_fuente_id=CATALOG, resultado_id=resultado, clase="valor") + assert {(m.forma, m.valor_id) for m in sembradas} >= {(primero, primero), (segundo, segundo)} + register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=" forma del curador ", registrado_por="curador", + vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo) + assert base.run("catalogs")["catalogs"]["mapeos_nuevos"] == 0 + [mia] = mappings.forms(forma_normalizada="FORMA DEL CURADOR") + assert (mia.forma, mia.valor_id, mia.registrado_por) == ("forma del curador", segundo, "curador") + + +def test_register_refuses_a_second_code_for_a_form_in_force(base): + """Pins down: `register` checks the new row against the stored ones: the catalog's own code of one value can't + be mapped to another value, and a lab's form can, once the first row's validity ends before the second's starts. + Fails if the write path stops running `check_function`.""" + base.run("catalogs") + mappings = base.ctx.repos.silver.mappings + resultado, primero, segundo = a_coded_result(base) + with pytest.raises(ValueError, match="se escribe igual"): + register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=primero, registrado_por="curador", + vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo) + viejo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="Código de laboratorio", + registrado_por="curador", vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=primero) + mappings.close(viejo.mapeo_id, date(2026, 12, 31)) + nuevo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="codigo de LABORATORIO", + registrado_por="curador", vigente_desde=date(2027, 1, 1), resultado_id=resultado, valor_id=segundo) + filas = mappings.forms(forma_normalizada=normalize("Código de laboratorio")) + assert [f.mapeo_id for f in filas] == [viejo.mapeo_id, nuevo.mapeo_id] diff --git a/webapi/orchestration/cycle.py b/webapi/orchestration/cycle.py index a54c9f1..c44706c 100644 --- a/webapi/orchestration/cycle.py +++ b/webapi/orchestration/cycle.py @@ -27,6 +27,7 @@ from webapi.orchestration.reference.support import ( grupos_de_edad_de, ) from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo +from webapi.orchestration.reference.source_mapping import catalog_rows from webapi.orchestration.reference.rules import ( RUTA_PARAMETROS, leer_parametros, @@ -66,9 +67,18 @@ def migrate(ctx: Context) -> str: def catalogs(migrate: str, ctx: Context) -> dict[str, int]: - """`core/catalogos/.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra.""" + """`core/catalogos/.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra. + + Then the catalog's own mappings (`cat_mapeo`, system `catalogo`): only the forms with no row yet are added, so a + mapping edited in the application survives every deploy.""" catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project)) - return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores) + counts = ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores) + mappings = ctx.repos.silver.mappings + if mappings is not None: + system, rows = catalog_rows(ctx.project, mappings) + mappings.ensure_system(system) + counts["mapeos_nuevos"] = mappings.seed(rows) + return counts def load(catalogs: dict[str, int], ctx: Context) -> SQLModel: diff --git a/webapi/orchestration/reference/source_mapping.py b/webapi/orchestration/reference/source_mapping.py index 143e126..b490584 100644 --- a/webapi/orchestration/reference/source_mapping.py +++ b/webapi/orchestration/reference/source_mapping.py @@ -13,13 +13,16 @@ A source form (a spelling, an abbreviation, a lab's own code) maps to one `valor For `f` to be a function, two mappings in force on the same date can't give the same key two codes: `check_function` rejects that, and `resolve` returns nothing for a key it still finds ambiguous, so the observation -goes back to the out-of-catalog queue instead of keeping a code. Today the mappings come from the catalog's TOML -(`from_result`: one system, always in force); any other store of mappings gives `SourceForm` rows and is checked -and read the same way. +goes back to the out-of-catalog queue instead of keeping a code. + +The mappings are stored in `cat_sistema_fuente` and `cat_mapeo`: the `catalogs` step seeds the catalog's own +(`catalog_rows`, system `catalogo`, always in force) and never changes a stored row, and `register` adds one after +checking it against the rows of the same form. """ +import tomllib from collections import defaultdict -from datetime import date +from datetime import date, datetime, timezone from typing import Iterable, NamedTuple from extraction.nlp.text import fold @@ -96,3 +99,60 @@ def _overlap(a: SourceForm, b: SourceForm) -> bool: starts_before_b_ends = a.valid_from is None or b.valid_to is None or a.valid_from <= b.valid_to b_starts_before_a_ends = b.valid_from is None or a.valid_to is None or b.valid_from <= a.valid_to return starts_before_b_ends and b_starts_before_a_ends + + +# --- the mappings stored in `cat_sistema_fuente` and `cat_mapeo` --- + +CATALOG_SINCE = date(1900, 1, 1) # the catalog's own mappings hold for every document + + +def as_source_form(row) -> SourceForm: + """A `cat_mapeo` row as the function sees it: a study code maps to its `estudio_id`, a spelling to its value.""" + return SourceForm(row.sistema_fuente_id, row.resultado_id or "", row.forma, row.valor_id or row.estudio_id, + row.vigente_desde, row.vigente_hasta) + + +def check_stored(same_form: list, new) -> None: + """`SourceMappingRepository.add`'s check: a study code or a spelling stays a function with the new row. A + caption may introduce several results (a receptor and its percentage), so it isn't checked.""" + if new.clase == "etiqueta": + return + check_function([as_source_form(r) for r in same_form if r.clase == new.clase] + [as_source_form(new)]) + + +def register(repository, *, sistema_fuente_id: str, clase: str, forma: str, registrado_por: str, + vigente_desde: date, estudio_id: str | None = None, resultado_id: str | None = None, + valor_id: str | None = None, motivo: str | None = None): + """Adds one mapping, rejected with `ValueError` if it makes a form give two codes while both are in force.""" + row = repository.model( + sistema_fuente_id=sistema_fuente_id, clase=clase, forma=forma.strip(), forma_normalizada=normalize(forma), + estudio_id=estudio_id, resultado_id=resultado_id, valor_id=valor_id, vigente_desde=vigente_desde, + registrado_por=registrado_por, registrado_en=datetime.now(timezone.utc), motivo=motivo) + return repository.add(row, check=check_stored) + + +def catalog_rows(project: str, repository) -> tuple[object, list]: + """The catalog's source system and its mappings, from the TOML: study codes, captions, and each value's code, + label and aliases. What `SourceMappingRepository.seed` adds when they're missing.""" + from webapi.orchestration.reference.catalogs import ruta_de_catalogo + + system = repository.sistema(sistema_fuente_id=CATALOG, etiqueta="Catálogo del proyecto", fuente_tabla=None, + vigente_desde=CATALOG_SINCE) + now = datetime.now(timezone.utc) + rows = {} + + def add(clase, forma, **target): + row = repository.model(sistema_fuente_id=CATALOG, clase=clase, forma=forma, forma_normalizada=normalize(forma), + vigente_desde=CATALOG_SINCE, registrado_por=CATALOG, registrado_en=now, **target) + rows.setdefault((clase, target.get("resultado_id"), target.get("estudio_id"), row.forma_normalizada), row) + + for study_id, study in tomllib.loads(ruta_de_catalogo(project).read_text(encoding="utf-8")).items(): + for code in study.get("codigos_hospital", ()): + add("estudio", code, estudio_id=study_id) + for name, result in study.get("resultados", {}).items(): + result_id = f"{study_id}.{name}" + for caption in result.get("etiquetas_fuente", ()): + add("etiqueta", caption, resultado_id=result_id) + for form in from_result(result_id, result): + add("valor", form.form, resultado_id=result_id, valor_id=form.value_id) + return system, list(rows.values()) diff --git a/webapi/orchestration/repositories.py b/webapi/orchestration/repositories.py index 8a1b7c7..35da4af 100644 --- a/webapi/orchestration/repositories.py +++ b/webapi/orchestration/repositories.py @@ -21,6 +21,7 @@ from persistance.edges.silver import ( ObservationRepository, TimelineRepository, LinksRepository, + SourceMappingRepository, ViewsRepository, ) from persistance.materializer import Materializer @@ -43,6 +44,7 @@ class Silver: observation: ObservationRepository links: LinksRepository timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it + mappings: SourceMappingRepository | None = None # how each source writes the catalog's codes @dataclass(frozen=True) @@ -80,6 +82,7 @@ def repositories_of(proyecto: str) -> Repositories: observation=dominio.observation_period_repository, links=dominio.links_repository, timeline=dominio.timeline_repository, + mappings=dominio.source_mapping_repository, ), materializer=dominio.materializer, gold=Gold( -- 2.53.0 From 790879513b15f6423dfbb768b123bddf8d7d2ad1 Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 13 Nov 2026 15:31:29 -0600 Subject: [PATCH 20/24] The image compiles dbt's manifest and sets DBT_MANIFEST, so the measure and FHIR routes are served --- Dockerfile | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 71d909d..3b0db98 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,17 @@ # Build context is the repo root (see docker-compose.yml) so the sibling # packages Core/, Persistance/, Extraction/ and models/ -# can be copied. +# can be copied, and Transformation/ compiled. + +# dbt's manifest: the measures' definitions and the compiled SQL of their event +# models. The API serves the measures from it and the indicator cycle creates +# the views. Compiling needs no data; the SQL is SQLite's, the image's default +# engine. +FROM python:3.12-slim AS manifest +COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/ +WORKDIR /app/Transformation +COPY Transformation/ ./ +RUN uv sync && uv run --no-sync dbt compile --profiles-dir . --profile tea + FROM python:3.12-slim # Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary. @@ -34,6 +45,11 @@ ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true ENV WEBAPI_REPORT_DIR=/data/reportes ENV INDICADORES_DIR=/data/indicadores ENV MLFLOW_DISABLE_AGENT_HINT=1 +# Without it the measure routes (//indicadores, //fhir) aren't +# registered. On another engine, mount a manifest compiled with that dbt target +# and point this at it. +COPY --from=manifest /app/Transformation/target/manifest.json /app/Transformation/target/manifest.json +ENV DBT_MANIFEST=/app/Transformation/target/manifest.json RUN chmod +x /app/WebApi/docker-entrypoint.sh -- 2.53.0 From 461d651805035b67171e8f1d1df1a031233218b3 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 13 Nov 2026 17:03:23 -0600 Subject: [PATCH 21/24] TEA FHIR: an episode's _include brings its ADOS-2 observation --- tests/test_fhir_tea.py | 7 +++++-- webapi/fhir/__init__.py | 12 ++++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py index 61533db..59bf569 100644 --- a/tests/test_fhir_tea.py +++ b/tests/test_fhir_tea.py @@ -167,8 +167,9 @@ def test_the_follow_up_filters(client, query, n): def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client): """Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT, - confirmed diagnosis and study EEG as a DiagnosticReport with its quality observations; no metric observation while - the alterations are hidden. Fails if an included resource drops out or the alterations leak.""" + ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality + observations; no metric observation while the alterations are hidden. Fails if an included resource drops out or + the alterations leak.""" body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*") included = resources(body, mode="include") kinds = {r["resourceType"] for r in included} @@ -177,6 +178,8 @@ def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client): reports = [r for r in included if r["resourceType"] == "DiagnosticReport"] assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"} assert all(len(r["result"]) == 5 for r in reports) + ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"] + assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2) def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch): diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index eaeb72f..63b750f 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -342,13 +342,17 @@ def tea_outcome(status: int, code: str, error: Exception): def _included(tea, queries, e, simulated: bool) -> list[dict]: - """What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG.""" + """What an episode's search includes: its patient, its steps, its M-CHAT, its ADOS-2, its diagnosis and its study + EEG.""" from sqlalchemy import select - persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"])) - resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated), + pac_id = e.child["pac_id"] + persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == pac_id)) + ados2 = tea.ados2_observation(tea._rows(queries, select(tea.ADOS2).where(tea.ADOS2.c.pac_id == pac_id)), + e.pseudonym, simulated) + resources = [tea.patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated), tea.care_plan(e, simulated)] - resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r] + resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r] if (eeg := e.study_eeg()) is not None: resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated) return resources -- 2.53.0 From b8045e74814c956bd8ff4a6b1cb691404e5d3e35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 15 Nov 2026 00:47:38 -0600 Subject: [PATCH 22/24] dbt's manifest compiled at start-up for the deployment's engine; the image carries the dbt environments --- Dockerfile | 18 ++++++--- docker-entrypoint.sh | 14 ++++++- tests/test_dbt_manifest.py | 53 ++++++++++++++++++++++++ webapi/dbt_manifest.py | 83 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 160 insertions(+), 8 deletions(-) create mode 100644 tests/test_dbt_manifest.py create mode 100644 webapi/dbt_manifest.py diff --git a/Dockerfile b/Dockerfile index 3b0db98..257c5e0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,13 +4,18 @@ # dbt's manifest: the measures' definitions and the compiled SQL of their event # models. The API serves the measures from it and the indicator cycle creates -# the views. Compiling needs no data; the SQL is SQLite's, the image's default -# engine. +# the views. The manifest built here is SQLite's, the image's default engine; +# the same environments compile it again at start-up against MySQL/MariaDB, +# PostgreSQL or SQL Server when *_DATABASE_URL points there (docker-entrypoint.sh), +# because those adapters open a connection to compile. dbt-mysql needs an +# older dbt-core, so it gets an environment of its own. FROM python:3.12-slim AS manifest COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/ WORKDIR /app/Transformation COPY Transformation/ ./ -RUN uv sync && uv run --no-sync dbt compile --profiles-dir . --profile tea +RUN uv sync --group sqlite --group sqlserver --group postgres \ + && UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql \ + && uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect FROM python:3.12-slim @@ -46,10 +51,11 @@ ENV WEBAPI_REPORT_DIR=/data/reportes ENV INDICADORES_DIR=/data/indicadores ENV MLFLOW_DISABLE_AGENT_HINT=1 # Without it the measure routes (//indicadores, //fhir) aren't -# registered. On another engine, mount a manifest compiled with that dbt target -# and point this at it. -COPY --from=manifest /app/Transformation/target/manifest.json /app/Transformation/target/manifest.json +# registered. The entrypoint replaces it with one compiled against the +# deployment's engine when that engine isn't SQLite (webapi.dbt_manifest). +COPY --from=manifest /app/Transformation /app/Transformation ENV DBT_MANIFEST=/app/Transformation/target/manifest.json +ENV TRANSFORMATION_DIR=/app/Transformation RUN chmod +x /app/WebApi/docker-entrypoint.sh diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 46bdf4c..204fef9 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -16,14 +16,24 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER esac done +cd /app/WebApi + +# dbt's manifest for the deployment's engine: the image's is SQLite's; on +# another engine it's compiled now, against the configured databases, into +# /data (webapi.dbt_manifest prints the path to use, or nothing to keep the +# image's). +if compiled="$(uv run --no-sync python -m webapi.dbt_manifest)"; then + [ -n "$compiled" ] && export DBT_MANIFEST="$compiled" +else + echo "dbt manifest: compilation failed; the measure routes will stay unregistered" >&2 +fi + # The live indicator worker (webapi.recomputation) shares the image; the # API container runs the migrations, so the worker starts after it. if [ "$1" = "indicadores" ]; then - cd /app/WebApi exec uv run --no-sync python -m webapi.recomputation fi -cd /app/WebApi # --no-sync: the environment was synced at build time; syncing at startup # would try to reach the package index (and pull dev deps). for domain in cacu cama tea governance; do diff --git a/tests/test_dbt_manifest.py b/tests/test_dbt_manifest.py new file mode 100644 index 0000000..f0bdf1e --- /dev/null +++ b/tests/test_dbt_manifest.py @@ -0,0 +1,53 @@ +"""The dbt target and environment derived from the deployment's database URLs (`webapi.dbt_manifest`). + +No dbt runs here: only the mapping the entrypoint relies on to compile the manifest against the right engine. +No fixtures.""" + +import pytest + +from webapi.dbt_manifest import dbt_executable, environment, target_of + +URLS_MSSQL = { + "cacu": "mssql+pymssql://usuario:clave@servidor:1433/isss_cacu", + "cama": "mssql+pymssql://usuario:clave@servidor:1433/isss_cama", + "tea": "mssql+pymssql://usuario:clave@servidor:1433/isss_tea", +} + + +def test_sqlite_urls_keep_the_image_manifest(): + """SQLite URLs give the `sqlite` target, which the entrypoint treats as "keep the image's manifest". Fails if + `target_of` stops recognising SQLite or maps it elsewhere.""" + urls = {d: f"sqlite:////data/{d}.db" for d in ("cacu", "cama", "tea")} + assert target_of(urls) == "sqlite" + assert environment(urls, "sqlite")["TEA_DB_PATH"] == "/data/tea.db" + + +@pytest.mark.parametrize("scheme, target", [("mssql+pymssql", "sqlserver"), ("postgresql+psycopg2", "postgres"), + ("mysql+pymysql", "mysql"), ("mariadb+pymysql", "mysql")]) +def test_each_engine_maps_to_its_dbt_target(scheme, target): + """Every engine the platform runs on has a dbt target. Fails if a backend name is dropped from `TARGETS`.""" + urls = {d: f"{scheme}://u:p@h:1/{d}" for d in ("cacu", "cama", "tea")} + assert target_of(urls) == target + + +def test_mixed_engines_are_refused(): + """One manifest serves the three domains, so their databases must share an engine. Fails if `target_of` + silently picks one of several engines.""" + urls = {**URLS_MSSQL, "tea": "sqlite:////data/tea.db"} + with pytest.raises(ValueError, match="one engine"): + target_of(urls) + + +def test_environment_feeds_profiles_yml(): + """The server, port, credentials and each domain's database name reach dbt through the variables + `Transformation/profiles.yml` reads. Fails if a variable name changes on either side.""" + env = environment(URLS_MSSQL, "sqlserver") + assert env == {"CACU_DBT_DATABASE": "isss_cacu", "CAMA_DBT_DATABASE": "isss_cama", "TEA_DBT_DATABASE": "isss_tea", + "DBT_HOST": "servidor", "DBT_PORT": "1433", "DBT_USER": "usuario", "DBT_PASSWORD": "clave"} + + +def test_mysql_has_its_own_environment(tmp_path): + """dbt-mysql pins an older dbt-core, so the image keeps it in `.venv-mysql`. Fails if the executable lookup + stops distinguishing MySQL.""" + assert dbt_executable(tmp_path, "mysql") == tmp_path / ".venv-mysql" / "bin" / "dbt" + assert dbt_executable(tmp_path, "sqlserver") == tmp_path / ".venv" / "bin" / "dbt" diff --git a/webapi/dbt_manifest.py b/webapi/dbt_manifest.py new file mode 100644 index 0000000..41a2952 --- /dev/null +++ b/webapi/dbt_manifest.py @@ -0,0 +1,83 @@ +"""dbt's manifest for the deployment's engine. + +The measures are served from `manifest.json` (`DBT_MANIFEST`), whose compiled SQL is the dialect of the dbt target it +was compiled with. The image ships SQLite's; on another engine the entrypoint runs this module, which compiles the +project in `TRANSFORMATION_DIR` against the configured databases (the adapters for MySQL, PostgreSQL and SQL Server +open a connection to compile) and prints the path of the manifest to serve. On SQLite it prints nothing: the image's +manifest is the right one. + +The three domains must share one engine: one manifest covers every domain's models. +""" + +import os +import subprocess +import sys +from pathlib import Path + +from sqlalchemy.engine import make_url + +DOMAINS = ("cacu", "cama", "tea") +TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"} + + +def target_of(urls: dict[str, str]) -> str: + """The dbt target the domains' database URLs share. `ValueError` for an engine dbt has no target for, or when + the domains don't share one engine.""" + targets = {domain: TARGETS.get(make_url(url).get_backend_name()) for domain, url in urls.items()} + if unknown := [domain for domain, target in targets.items() if target is None]: + raise ValueError(f"no dbt target for the engine of {', '.join(unknown)}") + if len(set(targets.values())) != 1: + raise ValueError("the domains' databases must be on one engine: one manifest serves the three domains") + return next(iter(targets.values())) + + +def environment(urls: dict[str, str], target: str) -> dict[str, str]: + """What `Transformation/profiles.yml` reads: the server and credentials from CaCu's URL (one server for the three + domains), each domain's database name, and on SQLite each domain's file.""" + env: dict[str, str] = {} + for domain, url in urls.items(): + parsed = make_url(url) + if target == "sqlite": + env[f"{domain.upper()}_DB_PATH"] = parsed.database or f"{domain}.db" + else: + env[f"{domain.upper()}_DBT_DATABASE"] = parsed.database or domain + first = make_url(urls["cacu"]) + if target != "sqlite": + env["DBT_HOST"] = first.host or "localhost" + if first.port: + env["DBT_PORT"] = str(first.port) + env["DBT_USER"] = first.username or "" + env["DBT_PASSWORD"] = first.password or "" + return env + + +def dbt_executable(root: Path, target: str) -> Path: + """dbt-mysql runs on an older dbt-core, so it lives in its own environment next to the main one.""" + return root / (".venv-mysql" if target == "mysql" else ".venv") / "bin" / "dbt" + + +def compile_manifest(root: Path, target: str, env: dict[str, str], out_dir: Path) -> Path: + """Compiles every model with placeholders for the question's parameters (`--no-introspect`: the target's + tables needn't exist yet) and returns the manifest's path.""" + out_dir.mkdir(parents=True, exist_ok=True) + command = [str(dbt_executable(root, target)), "compile", "--project-dir", str(root), "--profiles-dir", str(root), + "--profile", "cacu", "--target", target, "--no-introspect", "--target-path", str(out_dir)] + subprocess.run(command, check=True, env={**os.environ, **env}, stdout=sys.stderr) + return out_dir / "manifest.json" + + +def main() -> int: + from persistance.settings import settings + + urls = {domain: getattr(settings, f"{domain}_database_url") for domain in DOMAINS} + target = target_of(urls) + if target == "sqlite": + return 0 + root = Path(os.environ.get("TRANSFORMATION_DIR") or Path(__file__).resolve().parents[2] / "Transformation") + out_dir = Path(os.environ.get("DBT_MANIFEST_DIR", "/data/dbt")) + print(compile_manifest(root, target, environment(urls, target), out_dir)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) -- 2.53.0 From 854a2e9c55b36e0c3e6130416b36e4e0c0255e96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 15 Nov 2026 05:37:50 -0600 Subject: [PATCH 23/24] The recomputation worker estimates with the models in production and wakes on the marker directory; the scanned test form carries a birth date --- pyproject.toml | 1 + tests/test_imports_pdf_endpoints.py | 14 +++-- tests/test_live_estimators.py | 58 +++++++++++++++++++++ uv.lock | 64 ++++++++++++++++++++++- webapi/orchestration/__main__.py | 4 +- webapi/orchestration/estimators.py | 81 +++++++++++++++++++++++++++++ webapi/recomputation.py | 67 ++++++++++++++++++------ 7 files changed, 266 insertions(+), 23 deletions(-) create mode 100644 tests/test_live_estimators.py create mode 100644 webapi/orchestration/estimators.py diff --git a/pyproject.toml b/pyproject.toml index 208f351..0c20d79 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,7 @@ dependencies = [ "gunicorn>=23.0", "sqlglot>=25.0", "rapidfuzz>=3.9", + "watchdog>=6.0", ] [project.optional-dependencies] diff --git a/tests/test_imports_pdf_endpoints.py b/tests/test_imports_pdf_endpoints.py index 8cb8072..0911fdb 100644 --- a/tests/test_imports_pdf_endpoints.py +++ b/tests/test_imports_pdf_endpoints.py @@ -76,14 +76,16 @@ def _font(size: int = 34): return ImageFont.load_default() -def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes: - """A scanned-like page with two text blocks at known pixel positions and - no text layer, so only the OCR/region path applies.""" +def _build_scanned_form_pdf(id_hospital: str, sexo: str, nacimiento: str = "1980-05-17") -> bytes: + """A scanned-like page with three text blocks on one line at known pixel + positions and no text layer, so only the OCR/region path applies. The birth + date is there because a patient row is not valid without it.""" img = Image.new("RGB", (_IMG_W, _IMG_H), "white") draw = ImageDraw.Draw(img) font = _font() draw.text((40, 100), id_hospital, fill="black", font=font) draw.text((400, 100), sexo, fill="black", font=font) + draw.text((560, 100), nacimiento, fill="black", font=font) buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=letter) @@ -99,6 +101,7 @@ def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes: _ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H) _SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H) +_NACIMIENTO_BBOX = (540 / _IMG_W, 60 / _IMG_H, 880 / _IMG_W, 180 / _IMG_H) # --------------------------------------------------------------------- @@ -229,6 +232,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): regions = [ {"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)}, {"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)}, + {"target_field": "pac_fecha_nacimiento", "page_numbers": [1], "bbox": list(_NACIMIENTO_BBOX)}, ] extract_response = client.post( "/imports/sources/pdf/regions/extract", @@ -236,13 +240,13 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): ) assert extract_response.status_code == 200 extract_body = extract_response.get_json() - assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}] + assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1980-05-17"}] assert extract_body["warnings"] == [] source = { "source_type": "pdf", "target": "cacu.Paciente", - "column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}, + "column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento"}, "payload": { "file_base64": base64.b64encode(pdf_bytes).decode(), "mode": "regions", diff --git a/tests/test_live_estimators.py b/tests/test_live_estimators.py new file mode 100644 index 0000000..4b1e669 --- /dev/null +++ b/tests/test_live_estimators.py @@ -0,0 +1,58 @@ +"""The live estimators the recomputation worker hands the cycle (`webapi.orchestration.estimators`, +`webapi.recomputation`). + +Fixtures: `base` (conftest) gives a migrated CaCu database with the synthetic staging; the registry and the live +estimators are stubbed so no MLflow store or model is needed. The stub estimator is the cycle tests' `EstimadorFijo`. +""" + +import pytest +from sqlalchemy import text + +from webapi.orchestration import estimators +from webapi.recomputation import RecomputationQueue +from tests.test_orquestacion_riesgos import URL, EstimadorFijo + + +def test_only_cacu_has_a_live_estimator(): + """CaMa and TEA have no registered model, so their cycles estimate nothing. Fails if a domain without a model + gets an estimator that would then fail resolving a version.""" + assert estimators.live_estimators("cama") == {} + assert estimators.live_estimators("tea") == {} + + +def test_without_a_production_version_cacu_estimates_nothing(monkeypatch): + """No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle. + Fails if `live_estimators` stops catching the registry's `LookupError`.""" + from models.io.registry import registry + + monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none"))) + assert estimators.live_estimators("cacu") == {} + + +def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch): + """With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which + reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes.""" + from models.io.registry import registry + + monkeypatch.setattr(registry, "resolve", lambda *a, **k: object()) + live = estimators.live_estimators("cacu") + assert list(live) == [URL] + estimator = live[URL] + assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar) + with pytest.raises(RuntimeError): + estimator.procedencia() + + +@pytest.mark.parametrize("proyecto", ["cacu"]) +def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monkeypatch): + """After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator. + Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written + as anything but `preliminary`.""" + monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()}) + result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025) + assert result["estado"] == "ok", result + assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"] + with base.motor.connect() as con: + assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo_lote")).scalar_one() == 1 + assert con.execute(text("SELECT MIN(estado) FROM evaluacion_riesgo")).scalar_one() == "preliminary" + assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo")).scalar_one() > 0 diff --git a/uv.lock b/uv.lock index f42e8a3..c977ed8 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 2 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -1159,7 +1159,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/72/18/3fc6d951466ae9a2a688edcddde3b2e388da0a8244e0caf7117bbeb0eb95/greenlet-3.5.6-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:a5876d0a60355af98d535c47f6cd6eb0f8a432396dab26845d380b92f8412422", size = 295668, upload-time = "2026-09-14T14:22:33.241Z" }, { url = "https://files.pythonhosted.org/packages/27/89/366d2af5061eeefa5012f510d95a99c8620dcc457609838db4d538820318/greenlet-3.5.6-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e85880b538e59a59f55117b81f208a6660ad5ac328aad9305f812d9b8bc67a0f", size = 611700, upload-time = "2026-09-14T15:12:01.962Z" }, { url = "https://files.pythonhosted.org/packages/54/1c/07f133f865fd58ae593dd2bbec3144acaee9b04ffe2eb48c6e121747ceef/greenlet-3.5.6-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f0ba7c2a329d650628f4c8572fd1db29f0a59dd70a3e3e0710dcf18a35cce9d8", size = 624223, upload-time = "2026-09-14T15:20:42.459Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f2/844dc823ff2752ad049caa6b59d57e4572f9c445934b02d3518f4c67197c/greenlet-3.5.6-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee7d9da3bf493909cf811a3f038840cb34fab5ae2956b8a263919f6e289ab188", size = 629529, upload-time = "2026-09-14T15:25:06.354Z" }, { url = "https://files.pythonhosted.org/packages/66/6a/1594f3869c57c149abdb380492529e04d4c0229b5e4d79572c5bd0aaa673/greenlet-3.5.6-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:975736b002ed080d124cf81a79cb7e05cb26d6b3f5c7a7b651c0fcce70353aa1", size = 621404, upload-time = "2026-09-14T14:35:59.027Z" }, + { url = "https://files.pythonhosted.org/packages/c0/42/b1f8dbc89a53b9e77859fc1ad1627d106fc361daa3ea4bdf43a91ebb4338/greenlet-3.5.6-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:71890d5247020c25c21a6b65202782bfc281d4e6e244842419d30e3492bb6dcc", size = 432385, upload-time = "2026-09-14T15:28:37.369Z" }, { url = "https://files.pythonhosted.org/packages/a2/f5/33e5c9e48178b9259fd000f8f45caa4a65036f65d3d0c06a602f570f025d/greenlet-3.5.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0616b8f878098c5681fd8f0dc92d887551717402342a70f0abcbfea5f5ad8a44", size = 1584998, upload-time = "2026-09-14T15:10:06.653Z" }, { url = "https://files.pythonhosted.org/packages/ef/31/9b4e140bc24d0ad7927ebd651f5608b0acc2334d061748c3b6ad19085cfa/greenlet-3.5.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3dbb4596a6a4e5d47121a33ff20533a81e60f302d9e67b69909a8bc21a43f0a7", size = 1647568, upload-time = "2026-09-14T14:35:49.787Z" }, { url = "https://files.pythonhosted.org/packages/c3/71/d79f1791f824f8ff15c2978746640467ae932a2365e0201069f7f272395f/greenlet-3.5.6-cp312-cp312-win_amd64.whl", hash = "sha256:7ac4abb3877c43af320392c664774eef6fa2cc063c79a55fc02d844a3cbe7395", size = 324203, upload-time = "2026-09-14T14:22:54.504Z" }, @@ -1167,7 +1169,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/a1/e720a38852366c589e1a46cf570b886507ad2cf591050c203365638baab0/greenlet-3.5.6-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:f96f0e30b5a95c7631b12bfe214cbc90ec8fe8cfa36920596c10514a65743519", size = 294627, upload-time = "2026-09-14T14:24:40.102Z" }, { url = "https://files.pythonhosted.org/packages/eb/c3/58187858df41354a11e6a55b421e7af9059798abdab3a384cc51b8567c38/greenlet-3.5.6-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c75116c9de79949de23006e2d9b35ee82874c594fcf5c0311b439acaa14b8441", size = 614356, upload-time = "2026-09-14T15:12:03.399Z" }, { url = "https://files.pythonhosted.org/packages/ce/b9/3a7e67d5f05c9760b1ad411fa52264bd69cc08e22a2ebfb4018b90628ced/greenlet-3.5.6-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cad5782f93f7f738b62c6527b6f32a60694d924029f299a8b524758cfa53d815", size = 626756, upload-time = "2026-09-14T15:20:44.269Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7c/40400455f5b5a65bb83e94fde66d1be9e5ec518638113f8083ace746c309/greenlet-3.5.6-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a93ee7c6e8fd0f8a83525a51bd777be57ee17787e91d805bd8d6faf9dcada18e", size = 632632, upload-time = "2026-09-14T15:25:07.813Z" }, { url = "https://files.pythonhosted.org/packages/85/cb/ab0c123c514ed4e94c0dc9ee2e86362633e6b998cfc05de7fc9ac2eb9690/greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f98e8215e172f567ce80eeaed9107fb4d32b6c44f26983d9b8334658136a205a", size = 623779, upload-time = "2026-09-14T14:36:01.104Z" }, + { url = "https://files.pythonhosted.org/packages/f9/67/1f35cff30a6c51c3f23b63d4afcc7313ab4f97490ba3676fa78178984b27/greenlet-3.5.6-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:7f731ebac68ea06d628658295cb2d217b10186329fcf9a3b6a149045059bf92e", size = 434933, upload-time = "2026-09-14T15:28:38.858Z" }, { url = "https://files.pythonhosted.org/packages/a5/26/fda8a5a06e7073333ccb038133c5893b9e0c4fe29d5992a17e83c241bc6e/greenlet-3.5.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df19e2d0b1620039af5102563fbd96e8938c7f5c3f5828528d641d9fc585525e", size = 1584930, upload-time = "2026-09-14T15:10:08.234Z" }, { url = "https://files.pythonhosted.org/packages/2f/37/50f8813163148d6234e08b23dcad6a9e37f01d148c8ec976e4c44ea2d918/greenlet-3.5.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:06c0e933290fba8ffe53ead4ae1b8044b0e9754b75cebf381aa2bc3e50d82fac", size = 1647590, upload-time = "2026-09-14T14:35:51.173Z" }, { url = "https://files.pythonhosted.org/packages/86/da/b7669b09586365654083a62bd0724cf06cb74bd5085a15cdd161271f992f/greenlet-3.5.6-cp313-cp313-win_amd64.whl", hash = "sha256:5b602b4201b965a8354d74e232364a66ff243dd142e350d035f46169bb36e13d", size = 324086, upload-time = "2026-09-14T14:23:48.428Z" }, @@ -1175,7 +1179,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/66/c0/d254544ae2b8bdd311aef000fafc02828c2771b17d994b3075620ea7cc6e/greenlet-3.5.6-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46", size = 295221, upload-time = "2026-09-14T14:25:11.583Z" }, { url = "https://files.pythonhosted.org/packages/18/18/eb54be16b9cc3971e09ca5b73334e1b8c804a4630d9addaaf218a4fe300f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb", size = 660992, upload-time = "2026-09-14T15:12:04.876Z" }, { url = "https://files.pythonhosted.org/packages/8f/b4/e193efe65671dcf294bc51fcc59efb52d154adf8612c4ea016da0d2c486c/greenlet-3.5.6-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b", size = 673428, upload-time = "2026-09-14T15:20:45.756Z" }, + { url = "https://files.pythonhosted.org/packages/fd/21/631bb45fafde1dca782152377c0676d182ec924820064047f533a3627b28/greenlet-3.5.6-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b", size = 677688, upload-time = "2026-09-14T15:25:09.279Z" }, { url = "https://files.pythonhosted.org/packages/45/ac/28fa7a9e50f2859466214c4ac584d776db52c1604ad4dd158960a5af2a1f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88", size = 670773, upload-time = "2026-09-14T14:36:02.577Z" }, + { url = "https://files.pythonhosted.org/packages/40/30/2b0a73e68e1e18e30b601d0d183cfdfc2beca4de5a6843c630f0fc9fb90c/greenlet-3.5.6-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77", size = 480475, upload-time = "2026-09-14T15:28:40.741Z" }, { url = "https://files.pythonhosted.org/packages/c3/cd/fb7d6cdd86ff3427c1494854f0e35437eba05142be91f530f6da75e09e19/greenlet-3.5.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02", size = 1631900, upload-time = "2026-09-14T15:10:09.745Z" }, { url = "https://files.pythonhosted.org/packages/f6/40/143bdbb20a516628cb15074ae52ed17d850b450292609c7a6fccac6dbece/greenlet-3.5.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424", size = 1693740, upload-time = "2026-09-14T14:35:52.959Z" }, { url = "https://files.pythonhosted.org/packages/c9/9e/019642432e6ae283301df1361227d47610709d2dc69a38f95edef266d713/greenlet-3.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a", size = 327473, upload-time = "2026-09-14T14:28:12.948Z" }, @@ -1183,14 +1189,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/7e/7a205688a5b3074933b18a906608d46d106e9a79d776bdab5a4abf4b4feb/greenlet-3.5.6-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951", size = 305352, upload-time = "2026-09-14T14:21:31.962Z" }, { url = "https://files.pythonhosted.org/packages/78/cb/9c4a57a9d9dd0256e20b8f7f4f06554c2c92badebf0ab73ce344321b78b9/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49", size = 672671, upload-time = "2026-09-14T15:12:06.347Z" }, { url = "https://files.pythonhosted.org/packages/97/52/c6729681ebbd298f4decd28746815acc8a0b0a0fde21d2df33776fd4d042/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b", size = 679489, upload-time = "2026-09-14T15:20:47.291Z" }, + { url = "https://files.pythonhosted.org/packages/71/76/3c11c21e0716b1f1dc7c1a4b3d690abb1d3b448c69a9d32049fecb64010a/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d", size = 681303, upload-time = "2026-09-14T15:25:11.088Z" }, { url = "https://files.pythonhosted.org/packages/58/c5/2b6c721ba8b8963da42d5a0f57f25b8aaeb1fe9bdd156875e57f3be648a2/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc", size = 676608, upload-time = "2026-09-14T14:36:03.959Z" }, + { url = "https://files.pythonhosted.org/packages/3f/26/3ae402202452cd5941bbbd483e5a74297e2397e7aa3182c2a5e3ab7d5666/greenlet-3.5.6-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81", size = 510112, upload-time = "2026-09-14T15:28:42.112Z" }, { url = "https://files.pythonhosted.org/packages/b2/04/0d018e0d05bcdde19a0fcb907834155f1fc853a9bedd3f3f5e6acadcae19/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961", size = 1641479, upload-time = "2026-09-14T15:10:11.216Z" }, { url = "https://files.pythonhosted.org/packages/59/bb/f02ef9073919158f6403fe3701d4ed4403d646720e7201dfc6e9d264bac3/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404", size = 1698758, upload-time = "2026-09-14T14:35:54.336Z" }, { url = "https://files.pythonhosted.org/packages/08/a5/1f48fe647473a2dcccfd1839b2ff2c78eb57009be776b4da071e901c9bff/greenlet-3.5.6-cp314-cp314t-win_amd64.whl", hash = "sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16", size = 331574, upload-time = "2026-09-14T14:27:18.451Z" }, { url = "https://files.pythonhosted.org/packages/cd/72/3882855a75838faeb54a58aeef4fd77d20b2a86d4bad570c70d41b565dcf/greenlet-3.5.6-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:3ac3494c381dab876cad7d0b22f3a722f3e0c8deb3a65b9e7f35ad7f58b8fcb3", size = 295926, upload-time = "2026-09-14T14:27:21.16Z" }, { url = "https://files.pythonhosted.org/packages/10/1f/be4d957d8a9b90bcbe8db206548a42134d96222d43e5ed3fc4708fb6e24b/greenlet-3.5.6-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:602024dae6d77e161f4b89491b62ca1d4f19949d79d47b2db057e476d21179d6", size = 666910, upload-time = "2026-09-14T15:12:07.901Z" }, { url = "https://files.pythonhosted.org/packages/a1/af/60d62571a7d6de961e4ce7625d6c2faf359345659fc782d2cdf517c34577/greenlet-3.5.6-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f8e63209c3e1e828ee6a457529b4a6d8b05d050fe0ae03a7ae49e967c5d312e0", size = 677415, upload-time = "2026-09-14T15:20:48.817Z" }, + { url = "https://files.pythonhosted.org/packages/f5/41/b3114c97c10e796010f00a30f51c81470072bca4b53e396ccca87484fcf7/greenlet-3.5.6-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9133d68624b1f2e89ec2f554d56aea8a5b0d7168cd9320200ba58d4d794845a4", size = 681337, upload-time = "2026-09-14T15:25:12.812Z" }, { url = "https://files.pythonhosted.org/packages/fb/16/ac9e547b611539aaed1870eb1d6ddc57abdd5924b3a99bb9b5f0b44176b8/greenlet-3.5.6-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccadce0130fd813ec86ebfe969a6c58b42acc1d0fe55a47525375b740e07b605", size = 675927, upload-time = "2026-09-14T14:36:05.34Z" }, + { url = "https://files.pythonhosted.org/packages/48/1b/d41861c2fa00968e39e467a495ca8db9ce9b6310a5d9b57561b3d0dc48fa/greenlet-3.5.6-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:5adcbbfe78bdc242c71740a02e0991cc1b2f34d33c8bb15ca45eee8fd1140942", size = 487339, upload-time = "2026-09-14T15:28:43.497Z" }, { url = "https://files.pythonhosted.org/packages/c4/b1/b7ba08d6431121741f1d30be0d5d292e76873325179a63586cd9217b62f6/greenlet-3.5.6-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9297fb9c39b9a2c039dbcd306c410bd6906b95244dec3bba4318d36c718c164c", size = 1637236, upload-time = "2026-09-14T15:10:12.442Z" }, { url = "https://files.pythonhosted.org/packages/af/c5/3b1cbc68f0c082022fc8717f7fe4b8b13b8d583c52352be37f4e9f55bcd2/greenlet-3.5.6-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b374e79ffa7511afc11773aef40a4ccea6191fba1c856ea2f9c56738dca69d7a", size = 1698526, upload-time = "2026-09-14T14:35:56.039Z" }, { url = "https://files.pythonhosted.org/packages/de/56/12941ed2711400451c89d544e10f831800a2770f19dd55eac8f0f7f2003b/greenlet-3.5.6-cp315-cp315-win_amd64.whl", hash = "sha256:7969bffa322c097bd46ae595ada6a931cefda613f18ba64587e9cff4cb320756", size = 327739, upload-time = "2026-09-14T14:23:55.768Z" }, @@ -1198,7 +1208,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/16/c2/86cfc5555a98e12b86966ddbd24fd39af32f71f2f785c6595b7feb2db156/greenlet-3.5.6-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:de3de000d459402cda015068fd135aa50c0bf6f2477a80d4da1e646f123b4e78", size = 306244, upload-time = "2026-09-14T14:27:57.565Z" }, { url = "https://files.pythonhosted.org/packages/14/6d/83ffc9d05a75a80ab3a7595dbb1d9604e5d4fc2996d73a8ae2dbd1284900/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45663c01a4de48b9a64a2ee1509d92d1dfd3afb02b2ccfc9333029d11aef996a", size = 676578, upload-time = "2026-09-14T15:12:09.468Z" }, { url = "https://files.pythonhosted.org/packages/5d/d6/c2cf684810e5caded075970aaadea654ecb58b8382b9aecf1d231b936894/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3deccbb57a481e3a408fe61cdfd5c13e0678fc0a30fdd09597917ca87b4be877", size = 684203, upload-time = "2026-09-14T15:20:50.261Z" }, + { url = "https://files.pythonhosted.org/packages/f2/d1/039c353d5593a97a89699e989324c9bc86af499e6c6152fe0180f5742204/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:63aff70fe5aac59c72215f42ec39fcb59ff46774fa966e717f8ecb6ee2273577", size = 686023, upload-time = "2026-09-14T15:25:14.528Z" }, { url = "https://files.pythonhosted.org/packages/62/19/00e1bee5d2af890dc8f400b54d0b0f9b489965f92bc12b407ff72cc6f469/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:311018b46472fb26ee85870847fb89eb64cc8aaddb617400789d87076f7cfeec", size = 681253, upload-time = "2026-09-14T14:36:06.742Z" }, + { url = "https://files.pythonhosted.org/packages/8a/62/97ceb8e0b2ea96046cdf8e95b042715020ebb12d83ea0690db80a8f03d23/greenlet-3.5.6-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:520648db8fb92eef7b3e6013f5a6f901cdf0d6685f639c2f7a245879f865bef7", size = 517058, upload-time = "2026-09-14T15:28:44.924Z" }, { url = "https://files.pythonhosted.org/packages/89/58/c9275fd0ca195d1d3402931bcce8cfcc74726ff76efb1883d229e6e1a3d7/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:7f924a5a9d5890649566f2f6682e0d8ad8ca23028bacffbbac36dbd7fd680176", size = 1645988, upload-time = "2026-09-14T15:10:13.758Z" }, { url = "https://files.pythonhosted.org/packages/e0/36/b35747582fa4f1a5453f8f3002405dbac788e450cec7674dc2d204b6ccb5/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:de9923832f2d8c1a5ecd8d7260465a6ca5a86888a0d129e3bd5cf0406d2fc5bf", size = 1702383, upload-time = "2026-09-14T14:35:58.143Z" }, { url = "https://files.pythonhosted.org/packages/ed/69/6ec22ac9351e474d2a134d0ff9400dc80362d1c20f0721088ffffdfc205b/greenlet-3.5.6-cp315-cp315t-win_amd64.whl", hash = "sha256:2ab5f42ac6c238eb71770715e6e909ad9a1a92b6c681ccb64cd5a0f07edb953f", size = 331845, upload-time = "2026-09-14T14:27:41.723Z" }, @@ -2379,7 +2391,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess" }, + { name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } wheels = [ @@ -3865,6 +3877,52 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8d/57/a27182528c90ef38d82b636a11f606b0cbb0e17588ed205435f8affe3368/waitress-3.0.2-py3-none-any.whl", hash = "sha256:c56d67fd6e87c2ee598b76abdd4e96cfad1f24cacdea5078d382b1f9d7b5ed2e", size = 56232, upload-time = "2024-11-16T20:02:33.858Z" }, ] +[[package]] +name = "watchdog" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e2/55/087e45c2a3ed8223bc9f30d6b65f051de35513cfc30c989c2b1a14bf862e/watchdog-7.1.0.tar.gz", hash = "sha256:d3861e255416f49a1384474cb2efa097de165fb330d4c5432ce6708b509ed922", size = 218748, upload-time = "2026-11-05T09:33:21.28Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/59/14/40662f61f6e09f6a0371d95d916f6fc134825a7937b3ebff08cb6be433a8/watchdog-7.1.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:5047bc32663aa6c8a720940072a64cd648f4c6c6f34cd43592719bcc880b7465", size = 120967, upload-time = "2026-11-05T09:32:32.212Z" }, + { url = "https://files.pythonhosted.org/packages/83/dd/a36aed1934abf1b9a827f5d5b4fab23de395526eb1bc40da34aad9f2d589/watchdog-7.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:24bf3345278ed7861438cd1ff162888e955250124d1e3c122f9be1d5c2a142c3", size = 112992, upload-time = "2026-11-05T09:32:33.631Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4d/a490bcebc20c0c2781b0e1b2674245354502c9a62b274cc41859f4b269cd/watchdog-7.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:84a196f6259d18ce53cc58f211f7d0184939dbbfaaebae6efc509cec333ba9ea", size = 113581, upload-time = "2026-11-05T09:32:34.752Z" }, + { url = "https://files.pythonhosted.org/packages/c3/1f/804e62a8895212f436944ea2f13cdb3e6a7e2570b14f3723d3fef2bc9db7/watchdog-7.1.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:33501d3ab5627e41b6230d5f92e651ea843b1d236cf2b135959dfda2d42d2f69", size = 120813, upload-time = "2026-11-05T09:32:35.831Z" }, + { url = "https://files.pythonhosted.org/packages/30/35/59365fa94ebc1cddf89a21752eb17afef037bd534d63ab1800721540e5f4/watchdog-7.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:531f1a21bf0d37ea82be9a717ab92c05ab6f2f32ec6c1f2e7a748f9cfd21c8b2", size = 112905, upload-time = "2026-11-05T09:32:37.371Z" }, + { url = "https://files.pythonhosted.org/packages/41/ac/d4d6fb1bd6f25b614fa7150629b8eb3e30f7ded82f63a19b4427b140475e/watchdog-7.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fb84cdb12a3c4c273d71e4e5a4f76861fbf8f49bc9ca5be86f085ab6f57c683f", size = 113516, upload-time = "2026-11-05T09:32:38.48Z" }, + { url = "https://files.pythonhosted.org/packages/d4/8c/a25dac9642a4962d70cace9ffbb9ea4e575e6a61412ba5c80569460e0c81/watchdog-7.1.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:a0fdb62a48b5073ea3bcca29b9910f1cbde1026ab8bffb87a69b112bf6d97d1c", size = 122360, upload-time = "2026-11-05T09:32:39.85Z" }, + { url = "https://files.pythonhosted.org/packages/c7/56/b262a7c5acb47cb7eebc0cb25ded697ac4fbfc2d65c3a505a210ecb2b2e3/watchdog-7.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:8b637a1525d7e23548419368485bf1de931aca4c9e132e89a41bad52ff435fca", size = 113003, upload-time = "2026-11-05T09:32:40.873Z" }, + { url = "https://files.pythonhosted.org/packages/e0/5f/5133b328bae8ec5fab02c329c4364445459d678194c42457c9721b6f64ea/watchdog-7.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:b1a669c90ae6dc734f2a5a417f15ba30d5ef41d890bc28aef161d51bb62b7882", size = 113518, upload-time = "2026-11-05T09:32:41.924Z" }, + { url = "https://files.pythonhosted.org/packages/13/e1/0de47b185b82317696f59c0f0b9bb105f6492d6d3423cb1535ce60f70c2f/watchdog-7.1.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4332ae52b5e530d2c25a8525d765f1d34e595cfb07096c6b6368f9da10b5a8bf", size = 123108, upload-time = "2026-11-05T09:32:43.453Z" }, + { url = "https://files.pythonhosted.org/packages/56/f7/84b94e50c73479a291733027bd572336ba5b85dca27c18982186293bd8bd/watchdog-7.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:701586db59c9c421389e2e007713a821d934c3d83d034f0cafa95516a422758d", size = 113369, upload-time = "2026-11-05T09:32:44.689Z" }, + { url = "https://files.pythonhosted.org/packages/12/71/a6e482e81cb7ebe9f2aea7955254dee2865ea99a580bfeceaf53c274875d/watchdog-7.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d4c9804d3db8e18659cd7cd968e2dbb31a655d12fcc07ec54df5ae47ff929f50", size = 113900, upload-time = "2026-11-05T09:32:45.742Z" }, + { url = "https://files.pythonhosted.org/packages/46/8b/aeeacda90fcbcf2c8c3eeb761f9dcce798b0209c4413e9f89733d4bc8c8f/watchdog-7.1.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:a78673ab08b15f42760ae036f9251d02ac4107390c074963ccad4fc91cf880ac", size = 122415, upload-time = "2026-11-05T09:32:46.9Z" }, + { url = "https://files.pythonhosted.org/packages/66/07/69e1962eeccd885cc6196fea3f45f610741ca259ce9f69f372aa42e35146/watchdog-7.1.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:b0747551092578b70a4e8c48260ab956a9aa7efd2e9f7614471a7f73ada91c44", size = 113001, upload-time = "2026-11-05T09:32:48.023Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9a/3beeb0a20d9907468b48bdc63e2e0e5ff858b308c46051a823280164bbcf/watchdog-7.1.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:3dcf1a72c8c83a945e99965746c818bca3f50c0835b66ef1deb388d89bae792a", size = 113576, upload-time = "2026-11-05T09:32:49.407Z" }, + { url = "https://files.pythonhosted.org/packages/f1/f6/d552bd549125010e7c7d78fbb8057ee4ec6f5d258ffdc8cd6c675f9a70ef/watchdog-7.1.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:22fb8c80a2e510ec7773e4f6b2c6db869c2aed80bfb09962feb0962eb54f3ac9", size = 123152, upload-time = "2026-11-05T09:32:50.724Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7e/b951aeea6d6db7a917e3c1c5a341cbb3e5c8cc02ccb9201b2715547603c3/watchdog-7.1.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e226f1797764c3995ff9e91ce46f1b2ae65f59ab231785ef2f62243f06ba7956", size = 113366, upload-time = "2026-11-05T09:32:52.04Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ce/9e944c1d21b9b767023fb63cc764affcff1c8f4853de8e0ad14005cadbba/watchdog-7.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:2dc548262230493c8740c50cb0016d5983143ef3e587284d55f8a9fac393340f", size = 113951, upload-time = "2026-11-05T09:32:53.341Z" }, + { url = "https://files.pythonhosted.org/packages/33/7d/1d661f910c1f3717603b3eea0e3bd5540c7a76221371ae24bb42e0e3b049/watchdog-7.1.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:550ff9204139b6d759cd37210935bb88f6aac42542ad17516edaf17c9b35fd41", size = 112168, upload-time = "2026-11-05T09:32:57.02Z" }, + { url = "https://files.pythonhosted.org/packages/b6/29/f3b91fe0ef86c11f508de1c189054e2b4f00be8da6043e96130f841697d0/watchdog-7.1.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:22d8869d9cb822c735923eea39d9279f03d5fd23e6d325800ac9e402e34c0a28", size = 112671, upload-time = "2026-11-05T09:32:58.143Z" }, + { url = "https://files.pythonhosted.org/packages/b3/5b/1e62e5ab365634f84afe91f8fd78563c71226056d57e36d5fcba9d99b536/watchdog-7.1.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:dbd4e701a31b9bfa686bd831177b433695f5e4dabee6aa0bdf4efcf6f0fd5b9f", size = 103268, upload-time = "2026-11-05T09:32:59.401Z" }, + { url = "https://files.pythonhosted.org/packages/6e/0a/1da133041dfa1ca8d512e06485ce82dd2a9af7b6cc4fe9c277008380d10a/watchdog-7.1.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:d47f3067eb77a83d04de1cac214284da604f960eaee9816d7ebfd01a165b4175", size = 103269, upload-time = "2026-11-05T09:33:00.478Z" }, + { url = "https://files.pythonhosted.org/packages/e5/b4/3c9142add82c134fcbb748cc23e52603519679dddc4b5900d83e473d0648/watchdog-7.1.0-py3-none-manylinux2014_i686.whl", hash = "sha256:400788184d62c0e384da67de4d7fcb892bfeb064b2e59a7d1a1dccb9ff4b49bc", size = 103267, upload-time = "2026-11-05T09:33:01.522Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d3/dbbc79e5ce139516cad0b88ec08df27fd00ef478547c0e584951f2c687b3/watchdog-7.1.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:b76e3ac088550b33046c4eabacdd7dd4cb9db9147c8749b202643a4b5c2433c8", size = 103266, upload-time = "2026-11-05T09:33:02.614Z" }, + { url = "https://files.pythonhosted.org/packages/7a/ad/721ff870f9ecf25532a07d58fb677764e17390a46b675486bf23ce278873/watchdog-7.1.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:d94d0bcf30a9ea5ac5387df290b9e175c04747558c33443d2b0f763471699531", size = 103269, upload-time = "2026-11-05T09:33:03.694Z" }, + { url = "https://files.pythonhosted.org/packages/ab/4c/dfe0265c572027b2af9e824c6370a6ca39da33c819a99af48ddbc0cf1706/watchdog-7.1.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:cbae4a087f712bac4086e653273a949f86e2f908d16f157fd3568217e0c07cbe", size = 103268, upload-time = "2026-11-05T09:33:04.738Z" }, + { url = "https://files.pythonhosted.org/packages/98/4d/60e1c38c27973d63f8748cfe8da70bdf698d1c1ab0e94fd18de15b3044fe/watchdog-7.1.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:77f06d709fe5d766ec51ec07b79773f5e29a0b3c4c3d195cfc7aa1e909fa566c", size = 103269, upload-time = "2026-11-05T09:33:05.95Z" }, + { url = "https://files.pythonhosted.org/packages/72/88/9190129165760c76191f4711b64a728d1bff02de74649c675797ae253f26/watchdog-7.1.0-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:48db8dd8f9f92359ca5d4bccbd82be814facc3f57feaa3c67be964cc86b1dc33", size = 103270, upload-time = "2026-11-05T09:33:07.48Z" }, + { url = "https://files.pythonhosted.org/packages/5e/6c/1c3a9066266b5c3f0db9146422f67e5d13781b2fb1b9e777ead5553fc1a7/watchdog-7.1.0-py3-none-manylinux_2_17_armv7l.whl", hash = "sha256:a47d6e1418d7ed80f69454fb7f000ded554363209f8b04b812bf46b6c9e3093f", size = 103268, upload-time = "2026-11-05T09:33:08.639Z" }, + { url = "https://files.pythonhosted.org/packages/40/6b/aa8fb28263d3965f91228ce9b251a786e36060a3571f4d724b2fab44a1c1/watchdog-7.1.0-py3-none-manylinux_2_17_i686.whl", hash = "sha256:71b0ebfd5b3ffe7cf53143f2ab63fa5038ca190fc10782ec23202765a859b057", size = 103268, upload-time = "2026-11-05T09:33:10.041Z" }, + { url = "https://files.pythonhosted.org/packages/63/bb/8757c54c6dcb0edcc514a47b0dc026f8751a266b6c320a0df8830d9f89a4/watchdog-7.1.0-py3-none-manylinux_2_17_ppc64.whl", hash = "sha256:c71bd120d57b16c2c49abd55d74d3c83f984e19024249ebe7ba4dc4903eb27ee", size = 103268, upload-time = "2026-11-05T09:33:11.147Z" }, + { url = "https://files.pythonhosted.org/packages/79/47/bdd6c0176695fb5b44fa9164ab5aa3edbefd322eea7dc584073fe7bfe67c/watchdog-7.1.0-py3-none-manylinux_2_17_ppc64le.whl", hash = "sha256:a17f37720ea088430754a7cc5869fad93915c69eaff8d5284adbac41f1befaaa", size = 103268, upload-time = "2026-11-05T09:33:12.264Z" }, + { url = "https://files.pythonhosted.org/packages/e6/99/13406d1424ed4a8796a800016d21ac6fba3ba9ac508cc860e97ce352f14e/watchdog-7.1.0-py3-none-manylinux_2_17_s390x.whl", hash = "sha256:89f78b2b1c153715463e27fc86f0f95fd4dd6cb07a2cdad932fe01840101fb5a", size = 103269, upload-time = "2026-11-05T09:33:13.414Z" }, + { url = "https://files.pythonhosted.org/packages/bb/28/96130c970c236e4278a188cb6b8dec2500ff395ddcebb74c6171f5fc6069/watchdog-7.1.0-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:ad6d0b473cb8cde0721692b22b30fcbea8b52102430528874b3593549888bd81", size = 103269, upload-time = "2026-11-05T09:33:14.916Z" }, + { url = "https://files.pythonhosted.org/packages/17/54/312036da06d83b4a21d25a0d83643d2a9b2188eb2e5031e52fe82eddbe0a/watchdog-7.1.0-py3-none-win32.whl", hash = "sha256:9c937139c8afdb26405639309956352ef72c453006e772e0cf5c0bbc0d1cba82", size = 103255, upload-time = "2026-11-05T09:33:16.394Z" }, + { url = "https://files.pythonhosted.org/packages/5a/bc/c04fbb2d6366afb0850e39c6d848f2d38066ff6dadccc886b3cb12c39e32/watchdog-7.1.0-py3-none-win_amd64.whl", hash = "sha256:16a5ba8694587cdbeae4ab8e6434cece994f9cce4e5bab03e61e6d1a0a93a643", size = 103260, upload-time = "2026-11-05T09:33:17.687Z" }, + { url = "https://files.pythonhosted.org/packages/92/9c/5a39ec8880c08e50f75d90f4e0e27b95dc91a04deb5e6e04871dd4b7e006/watchdog-7.1.0-py3-none-win_arm64.whl", hash = "sha256:5ed4b94365c53ffd51d88e47ca48d6afae02fb1bd849175a9a10927a2fbfb932", size = 103260, upload-time = "2026-11-05T09:33:18.987Z" }, + { url = "https://files.pythonhosted.org/packages/c0/aa/7a7210433e000f2491ddec7756d312009b0a47847e5c3457ccb03852cfdf/watchdog-7.1.0-py3-none-win_ia64.whl", hash = "sha256:0cfc5a6b3d4e76fc3e18fd371ee79d57945004da4105b589f71bb16966fd3e67", size = 103256, upload-time = "2026-11-05T09:33:20.159Z" }, +] + [[package]] name = "wcwidth" version = "0.9.3" @@ -3922,6 +3980,7 @@ dependencies = [ { name = "rapidfuzz" }, { name = "sqlalchemy" }, { name = "sqlglot" }, + { name = "watchdog" }, ] [package.optional-dependencies] @@ -3959,6 +4018,7 @@ requires-dist = [ { name = "rapidfuzz", specifier = ">=3.9" }, { name = "sqlalchemy", specifier = ">=2.0" }, { name = "sqlglot", specifier = ">=25.0" }, + { name = "watchdog", specifier = ">=6.0" }, ] provides-extras = ["sql-drivers"] diff --git a/webapi/orchestration/__main__.py b/webapi/orchestration/__main__.py index f45d65e..82570e1 100644 --- a/webapi/orchestration/__main__.py +++ b/webapi/orchestration/__main__.py @@ -13,6 +13,7 @@ from datetime import date from pathlib import Path from webapi.orchestration.context import Context +from webapi.orchestration.estimators import live_estimators from webapi.orchestration.runner import run PROJECTS = ("cacu", "cama", "tea") @@ -42,7 +43,8 @@ def main(argv: list[str] | None = None) -> None: print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}") return logging.basicConfig(level=logging.INFO, format="%(message)s") - ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters) + ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters, + estimators=live_estimators(args.project)) for paso in run(ctx, only=args.only): print(f"{paso.name:20} {paso.seconds:6.1f} s") diff --git a/webapi/orchestration/estimators.py b/webapi/orchestration/estimators.py new file mode 100644 index 0000000..f8965cf --- /dev/null +++ b/webapi/orchestration/estimators.py @@ -0,0 +1,81 @@ +"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version +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 +unused by design. +""" + +from dataclasses import dataclass +from importlib import import_module +from typing import Any + + +@dataclass(frozen=True) +class Provenance: + modelo_nombre: str + modelo_version: str + mlflow_run_id: str + modelo_sha: str | None + + def como_dict(self) -> dict[str, str]: + return {key: value for key, value in self.__dict__.items() if value} + + +class Cin2LogisticEstimator: + """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to + test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has + something to report when `estimate` calls it.""" + + def __init__(self, domain: str = "cacu", version: str | None = None): + self.domain = domain + self.version = version + self.desenlace = "cin2_mas" + self._provenance: Provenance | None = None + + def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]: + import mlflow.pyfunc + from persistance.settings import settings + + from models.cacu.cin2_logistic.model import SETTINGS + 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.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" + self._provenance = Provenance( + modelo_nombre=registered_name(self.domain, SETTINGS["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)] + + def procedencia(self) -> Provenance: + if self._provenance is None: + raise RuntimeError("estimar() runs before procedencia()") + return self._provenance + + +def live_estimators(domain: str) -> dict[str, Any]: + """The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where + none is in production yet, the same as no estimator being configured: `estimate` then does nothing.""" + if domain != "cacu": + return {} + from models.cacu.cin2_logistic.model import SETTINGS + from models.io.registry import registry + + try: + registry.resolve(domain, SETTINGS["scenario"]) + except LookupError: + return {} + return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)} diff --git a/webapi/recomputation.py b/webapi/recomputation.py index 39fda58..08cfdd4 100644 --- a/webapi/recomputation.py +++ b/webapi/recomputation.py @@ -1,11 +1,15 @@ """Recomputes a domain's indicators after its staging tables change. -A successful import asks for a recomputation (`RecomputationQueue.solicitar`), +A successful import asks for a recomputation (`RecomputationQueue.request_run`), which only drops a marker file. A separate process (`python -m -webapi.recomputation`, the `indicadores` compose service) picks the -markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs -> -staging to facts -> views -> registry -> definitions -> reports. -Requests that arrive while a domain is running are folded into one more run. +webapi.recomputation`, the `indicadores` compose service) watches the markers' +directory and, on any change there, runs every pending domain's cycle +(`webapi.orchestration.run`): catalogs -> staging to facts -> views -> registry +-> definitions -> event models -> cohorts -> estimates, with the live estimators +of the models in production (`webapi.orchestration.estimators`). A periodic +check (`INDICADORES_INTERVALO_S`) stays as a fallback for a missed or coalesced +filesystem event; it no longer sets the normal reaction time. Requests that +arrive while a domain is running are folded into one more run. State lives in files under `INDICADORES_DIR`: `pendiente/` markers and `estado.json`; each run is also appended, as counts only, to @@ -24,6 +28,9 @@ from datetime import date, datetime, timezone from pathlib import Path from typing import Any +from watchdog.events import FileSystemEventHandler +from watchdog.observers import Observer + from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes @@ -99,6 +106,7 @@ class RecomputationQueue: def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]: """Runs the domain's graph (without `migrate`: the API migrates on startup).""" from webapi.orchestration import Context, run, steps_of + from webapi.orchestration.estimators import live_estimators desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5)) hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year)) @@ -107,7 +115,7 @@ class RecomputationQueue: self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: - ctx = Context(dominio, desde, hasta, allow_undecided=True) + ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio)) pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) entrada.update( estado="ok", @@ -134,22 +142,51 @@ class RecomputationQueue: return ran +class _Waker(FileSystemEventHandler): + """Wakes the main loop on any change in the pending-markers directory.""" + + def __init__(self, wake: threading.Event): + self._wake = wake + + def on_any_event(self, event) -> None: + self._wake.set() + + def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") cola = RecomputationQueue() - interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) + cola._pending.mkdir(parents=True, exist_ok=True) + fallback_s = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1": for dominio in DOMAINS: cola.request_run(dominio) stop = threading.Event() - signal.signal(signal.SIGTERM, lambda *_: stop.set()) - signal.signal(signal.SIGINT, lambda *_: stop.set()) - log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base) - while True: - for dominio in cola.serve(): - log.info("%s: %s", dominio, cola.status()[dominio].get("estado")) - if stop.wait(interval): - break + wake = threading.Event() + + def _stop(*_): + stop.set() + wake.set() + + signal.signal(signal.SIGTERM, _stop) + signal.signal(signal.SIGINT, _stop) + + observer = Observer() + observer.schedule(_Waker(wake), str(cola._pending), recursive=False) + observer.start() + log.info("indicadores en vivo: observando %s (respaldo cada %.0f s)", cola._pending, fallback_s) + try: + while True: + for dominio in cola.serve(): + log.info("%s: %s", dominio, cola.status()[dominio].get("estado")) + if stop.is_set(): + break + wake.wait(fallback_s) + wake.clear() + if stop.is_set(): + break + finally: + observer.stop() + observer.join() if __name__ == "__main__": -- 2.53.0 From 9737b5a67ff04bd96b38bd11478cb7330f9d3dc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 15 Nov 2026 05:40:08 -0600 Subject: [PATCH 24/24] The follow-up list identifies each patient by the platform's pac_id, the key the risk route takes; TEA keeps its salted pseudonym --- docker-entrypoint.sh | 7 +++++++ tests/test_seguimiento.py | 6 ++++-- webapi/fhir/tea.py | 8 +++++++- webapi/follow_up/listing.py | 23 ++++++++++++----------- webapi/follow_up/routes.py | 8 ++++---- 5 files changed, 34 insertions(+), 18 deletions(-) diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 204fef9..32e7d21 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -34,6 +34,13 @@ if [ "$1" = "indicadores" ]; then exec uv run --no-sync python -m webapi.recomputation fi +# One-shot training of the CaCu model on the loaded data (compose profile +# `entrenar`): the trained version goes into production and the worker's next +# cycle estimates with it. +if [ "$1" = "entrenar" ]; then + exec uv run --no-sync python -m models run cacu cin2_logistic --export --train --promote +fi + # --no-sync: the environment was synced at build time; syncing at startup # would try to reach the package index (and pull dev deps). for domain in cacu cama tea governance; do diff --git a/tests/test_seguimiento.py b/tests/test_seguimiento.py index 016237a..7362612 100644 --- a/tests/test_seguimiento.py +++ b/tests/test_seguimiento.py @@ -9,7 +9,7 @@ import pytest from conftest import cliente_de LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"} -LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph", +LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph", "dias_toma_diagnostico", "prioridad"} # fmt: skip @@ -31,7 +31,9 @@ def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client): assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"]) assert all(i["prioridad"] is None for i in cuerpo["items"]) - assert "pac_id" not in response.get_data(as_text=True) + # The patient key is the platform's `pac_id`, the one the risk route takes; the hospital's id never leaves. + assert all(i["pac_id"].isdigit() and i["id_seudonimo"] == i["pac_id"] for i in cuerpo["items"]) + assert "pac_id_hospital" not in response.get_data(as_text=True) def test_el_pedido_se_respeta(client): diff --git a/webapi/fhir/tea.py b/webapi/fhir/tea.py index a16d3e8..fe9180c 100644 --- a/webapi/fhir/tea.py +++ b/webapi/fhir/tea.py @@ -10,6 +10,7 @@ Until the domain expert validates the reference ranges, every alteration stays h the alteration filter, the abnormal/normal split, and the metric and electrode observations. """ +import hashlib import os from dataclasses import dataclass from datetime import date @@ -17,7 +18,6 @@ from datetime import date from sqlalchemy import column, select, table from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged -from webapi.follow_up.listing import seudonimo STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"), ("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"), @@ -62,6 +62,12 @@ def salt() -> str: return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT) +def seudonimo(pac_id: int, sal: str) -> str: + """TEA's patient and episode ids: stable for a salt, without saying the `pac_id`. CaCu's follow-up list moved + to the platform's `pac_id`; TEA keeps the pseudonym until its patient resources get their own identity.""" + return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper() + + def _date(value) -> date | None: if value is None or isinstance(value, date): return value diff --git a/webapi/follow_up/listing.py b/webapi/follow_up/listing.py index fde56f0..34503a1 100644 --- a/webapi/follow_up/listing.py +++ b/webapi/follow_up/listing.py @@ -7,15 +7,16 @@ grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la m estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula. -**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta -lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal. +**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//riesgo`; `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` de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna. """ import calendar -import hashlib import json import tomllib from datetime import date, timedelta @@ -85,7 +86,6 @@ class PaginaFuera(LookupError): def seguimiento_de( sesion: Session, *, - sal: str, corte: date | None = None, meses: int | None = None, estatus: str | None = None, @@ -119,7 +119,7 @@ def seguimiento_de( corte = _acotado(sesion, corte or hoy or date.today(), tablas) desde = _meses_antes(corte, meses) + timedelta(days=1) estatus_de = _estatus_al_corte(sesion, corte, valores_estatus) - items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas) + items = _items(sesion, corte, desde, lista, estatus_de, tablas) if estatus is not None: items = [i for i in items if i["estatus"]["codigo"] == estatus] @@ -140,9 +140,9 @@ def seguimiento_de( } -def seudonimo(pac_id: int, sal: str) -> str: - """El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`.""" - return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper() +def identificador(pac_id: int) -> str: + """El identificador que sale en la lista: el `pac_id` de la plataforma, como texto decimal.""" + return str(pac_id) def _validar_reglas(lista: dict) -> None: @@ -164,7 +164,7 @@ def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int, return {pac_id: estatus for pac_id, estatus in filas} -def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]: +def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]: """Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua.""" estudios = _estudios(sesion, corte, lista["fecha_estudio"]) en_ventana: dict[int, dict[str, list]] = {} @@ -187,7 +187,8 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]: mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]]) estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE") items.append({ - "id_seudonimo": seudonimo(pac_id, sal), + "pac_id": identificador(pac_id), + "id_seudonimo": identificador(pac_id), "grupo_edad": edades.get(pac_id, SIN_DATO), "estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]}, "ultima_citologia": None if cito is None else { @@ -201,7 +202,7 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]: "prioridad": None, "_orden": mas_reciente, }) - items.sort(key=lambda i: i["id_seudonimo"]) + items.sort(key=lambda i: int(i["pac_id"])) items.sort(key=lambda i: i.pop("_orden"), reverse=True) return items diff --git a/webapi/follow_up/routes.py b/webapi/follow_up/routes.py index 2f06094..e057c34 100644 --- a/webapi/follow_up/routes.py +++ b/webapi/follow_up/routes.py @@ -3,8 +3,9 @@ GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size= Es dato por paciente, sobre datos simulados: toda respuesta lleva `simulado: true`. La ruta se registra -siempre; quién puede verla lo decidirá una regla de acceso. La lista la arma `webapi.follow_up.listing`; aquí solo se valida, -se abre la sesión y se traducen los errores. +siempre; quién puede verla lo decidirá una regla de acceso. Cada fila trae el `pac_id` de la plataforma, el que +usa la ruta de riesgo individual. La lista la arma `webapi.follow_up.listing`; aquí solo se valida, se abre la +sesión y se traducen los errores. """ import json @@ -19,7 +20,6 @@ from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de from sqlmodel import Session FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") -DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno def in_dev() -> bool: @@ -40,7 +40,7 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint: return jsonify({"error": str(error)}), 400 sesion = get_session() try: - cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido) + cuerpo = seguimiento_de(sesion, **pedido) except PedidoInvalido as error: return jsonify({"error": str(error)}), 400 except PaginaFuera as error: -- 2.53.0