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 /<domain>/indicadores
This commit is contained in:
+18
-25
@@ -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()
|
||||
|
||||
+114
@@ -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:<grado>` 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" }
|
||||
+87
@@ -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 }
|
||||
+1264
File diff suppressed because it is too large
Load Diff
+387
@@ -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"
|
||||
}
|
||||
]
|
||||
Vendored
+7735
File diff suppressed because it is too large
Load Diff
Vendored
+6242
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
@@ -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"
|
||||
|
||||
@@ -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 (`<proyecto>/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
|
||||
@@ -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 (`<proyecto>/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()
|
||||
@@ -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
|
||||
@@ -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")
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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 ---
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+10
-10
@@ -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 = {
|
||||
|
||||
@@ -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")
|
||||
|
||||
+10
-4
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -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_<name>`)."""
|
||||
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],
|
||||
}
|
||||
@@ -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
|
||||
@@ -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/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato=&filtro= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?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_<proyecto>_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/<indicador>/periodos", "get_periodos", get_periodos)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/datos", "get_datos", get_datos)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/metadatos", "get_metadatos", get_metadatos)
|
||||
blueprint.add_url_rule(
|
||||
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
||||
)
|
||||
@@ -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__)
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"""`GET /<domain>/indicadores/<measure_id>`: 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="/<domain>"`. `repositories` is the domain's
|
||||
`persistance.<domain>` 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/<measure_id>")
|
||||
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
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 `<proyecto>.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])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <compiled SQL>` for every model the project's measures read,
|
||||
parents first.
|
||||
|
||||
Those are the project's models semantic models count over (`models/<project>/…`) 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]
|
||||
Reference in New Issue
Block a user