Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d0213eda7 | |||
| 1710cd5ca2 | |||
| 3c28a43cb1 | |||
| 21e6533dab | |||
| b9adedbf6f | |||
| 0cbe390b25 | |||
| 0f00a975fa |
+3
-2
@@ -1,5 +1,5 @@
|
||||
# Build context is the repo root (see docker-compose.yml) so the sibling
|
||||
# packages Core/, Persistance/, Extraction/ and models/
|
||||
# packages Core/, Persistance/, Extraction/, models/ and indicadores_kit/
|
||||
# can be copied.
|
||||
FROM python:3.12-slim
|
||||
|
||||
@@ -15,6 +15,7 @@ COPY Core/ Core/
|
||||
COPY Persistance/ Persistance/
|
||||
COPY Extraction/ Extraction/
|
||||
COPY models/ models/
|
||||
COPY indicadores_kit/ indicadores_kit/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
# One environment for the API, the migrations and the indicator cycle. The SQL
|
||||
@@ -30,7 +31,7 @@ ENV MLFLOW_TRACKING_URI=sqlite:////data/mlflow.db
|
||||
ENV MLFLOW_ARTIFACT_ROOT=/data/mlflow-artefactos
|
||||
# No usage telemetry from MLflow: the server runs on a closed network.
|
||||
ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
|
||||
# Aggregate import log and the live indicator queue (webapi.recomputation).
|
||||
# Aggregate import log and the live indicator queue (webapi.indicadores_vivos).
|
||||
ENV WEBAPI_REPORT_DIR=/data/reportes
|
||||
ENV INDICADORES_DIR=/data/indicadores
|
||||
ENV MLFLOW_DISABLE_AGENT_HINT=1
|
||||
|
||||
@@ -4,9 +4,8 @@ API REST de ISSSTELEON en Flask. Importa datos clínicos de varias fuentes a
|
||||
las bases de CaCu, CaMa y TEA, publica los indicadores ya calculados, guarda
|
||||
una bitácora agregada de cada importación y expone la gobernanza de modelos
|
||||
y de OCR. Usa `Persistance` para las bases, `Extraction` para documentos y
|
||||
EEG y `models` para las cohortes. Los indicadores se definen en dbt (`Transformation`) y se
|
||||
responden bajo pedido (`/<dominio>/indicadores`); `orchestration` carga la plata, las tablas de
|
||||
referencia y las vistas de dbt.
|
||||
EEG, `indicadores_kit` para leer los indicadores y `orquestacion` para
|
||||
recalcularlos.
|
||||
|
||||
## Estructura
|
||||
|
||||
@@ -26,7 +25,7 @@ webapi/
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura
|
||||
│ └── audit.py bitácora agregada (sin datos de pacientes)
|
||||
├── indicadores.py rutas de indicadores (del equipo de indicadores)
|
||||
├── recomputation.py cola y servicio que recalcula indicadores tras cada carga
|
||||
├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga
|
||||
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
|
||||
```
|
||||
|
||||
@@ -80,7 +79,7 @@ for d in cacu cama tea governance; do
|
||||
uv run alembic -c ../Persistance/persistance/$d/alembic.ini upgrade head
|
||||
done
|
||||
uv run python main.py # http://localhost:5050
|
||||
uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal
|
||||
uv run python -m webapi.indicadores_vivos # recálculo de indicadores, en otra terminal
|
||||
```
|
||||
|
||||
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
|
||||
|
||||
@@ -10,11 +10,11 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER
|
||||
esac
|
||||
done
|
||||
|
||||
# The live indicator worker (webapi.recomputation) shares the image; the
|
||||
# The live indicator worker (webapi.indicadores_vivos) shares the image; the
|
||||
# API container runs the migrations, so the worker starts after it.
|
||||
if [ "$1" = "indicadores" ]; then
|
||||
cd /app/WebApi
|
||||
exec uv run --no-sync python -m webapi.recomputation
|
||||
exec uv run --no-sync python -m webapi.indicadores_vivos
|
||||
fi
|
||||
|
||||
cd /app/WebApi
|
||||
|
||||
@@ -8,6 +8,7 @@ dependencies = [
|
||||
"persistance",
|
||||
"models[export]",
|
||||
"extraction",
|
||||
"indicadores-kit",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
"openpyxl>=3.1",
|
||||
@@ -33,6 +34,7 @@ sql-drivers = [
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
+36
-29
@@ -5,8 +5,8 @@
|
||||
`<DOMAIN>_DATABASE_URL` alone has no effect once an engine exists.
|
||||
`wire_domain` resets all three (env var, singleton, cache).
|
||||
|
||||
The `base`/`base_de` family (below `ANIO`) is for `webapi.orchestration`:
|
||||
una base del dominio por prueba, migrada por el paso `migrate`, con el staging
|
||||
The `base`/`base_de` family (below `ANIO`) is for `webapi.orquestacion`:
|
||||
una base del dominio por prueba, migrada por el paso `migrar`, con el staging
|
||||
sintético del kit.
|
||||
"""
|
||||
import os
|
||||
@@ -19,10 +19,10 @@ import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.connection import point_to
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
|
||||
from webapi.orquestacion import Contexto, correr
|
||||
from webapi.orquestacion.conexion import apuntar
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
@@ -40,34 +40,32 @@ class Base:
|
||||
"""El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance."""
|
||||
|
||||
proyecto: str
|
||||
ctx: Context
|
||||
ctx: Contexto
|
||||
dominio: object
|
||||
motor: object
|
||||
|
||||
def run(self, *pasos: str, **cambios) -> dict:
|
||||
def correr(self, *pasos: str, **cambios) -> dict:
|
||||
"""Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una."""
|
||||
return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)}
|
||||
return {p.nombre: p.resumen for p in correr(replace(self.ctx, **cambios), solo=pasos)}
|
||||
|
||||
def staging(self):
|
||||
"""Una sesión sobre la base, para cambiar el staging como lo haría la ingesta."""
|
||||
return Session(self.motor)
|
||||
|
||||
|
||||
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."""
|
||||
def base_de(proyecto: str, carpeta) -> Base:
|
||||
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
|
||||
point_to(proyecto, url)
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto))
|
||||
run(ctx, only=["migrate"])
|
||||
apuntar(proyecto, url)
|
||||
ctx = Contexto(proyecto, ANIO, ANIO, repos=repositorios_de(proyecto))
|
||||
correr(ctx, solo=["migrar"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
(datos or import_module(f"staging.{proyecto}").insertar)(sesion)
|
||||
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"])
|
||||
@pytest.fixture(params=["cacu", "cama", "tea"])
|
||||
def proyecto(request):
|
||||
return request.param
|
||||
|
||||
@@ -134,16 +132,25 @@ MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging."""
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
base = base_de(proyecto, carpeta)
|
||||
base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True)
|
||||
try:
|
||||
from webapi import create_app
|
||||
"""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
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
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()
|
||||
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
# 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
@@ -1,87 +0,0 @@
|
||||
# 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
@@ -1,387 +0,0 @@
|
||||
[
|
||||
{
|
||||
"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
@@ -1 +0,0 @@
|
||||
"""Synthetic staging rows for the tests, one module per domain: written by hand, never real data."""
|
||||
@@ -1,187 +0,0 @@
|
||||
"""Filas sintéticas del staging de CaCu, escritas a mano. Nunca datos reales.
|
||||
|
||||
Seis pacientes y nueve citologías en dos semestres de 2025. Los textos de
|
||||
calidad son provisionales: los valores reales están sin confirmar.
|
||||
|
||||
Pacientes tamizadas: 4 en 2025-S1 y 4 en 2025-S2; de ellas, con muestra
|
||||
insatisfactoria, 2 y 1. Lo que da cada indicador va abajo (`ESPERADO_*`).
|
||||
|
||||
Casos que ejercita: H-003 tiene dos citologías en S1 y cuenta una vez;
|
||||
H-004 tiene una el 1 de julio, que ya es S2; H-001 aparece en los dos
|
||||
semestres.
|
||||
|
||||
Resultados (v0.5.0, T-4): seis citologías tienen reporte y cuatro, VPH;
|
||||
las dos insatisfactorias de H-002 y H-006 no tienen reporte, y la última
|
||||
de H-001 todavía no. Tres biopsias, cada una con la citología que la
|
||||
originó: dos reportadas y una pendiente. Los textos de resultado también
|
||||
son provisionales.
|
||||
|
||||
Cinco notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SATISFACTORIO = "SATISFACTORIO"
|
||||
INSATISFACTORIO = "INSATISFACTORIO"
|
||||
|
||||
PACIENTES = ("H-001", "H-002", "H-003", "H-004", "H-005", "H-006")
|
||||
|
||||
# (pac_id_hospital, fecha de toma, calidad del espécimen)
|
||||
CITOLOGIAS = (
|
||||
("H-001", date(2025, 2, 10), SATISFACTORIO),
|
||||
("H-002", date(2025, 3, 5), INSATISFACTORIO),
|
||||
("H-003", date(2025, 1, 20), INSATISFACTORIO),
|
||||
("H-003", date(2025, 4, 15), SATISFACTORIO),
|
||||
("H-004", date(2025, 5, 30), SATISFACTORIO),
|
||||
("H-004", date(2025, 7, 1), SATISFACTORIO),
|
||||
("H-005", date(2025, 8, 12), SATISFACTORIO),
|
||||
("H-006", date(2025, 9, 1), INSATISFACTORIO),
|
||||
("H-001", date(2025, 10, 2), SATISFACTORIO),
|
||||
)
|
||||
|
||||
# Índice en CITOLOGIAS -> (fecha de reporte, células escamosas, VPH, genotipo 16, genotipo 18).
|
||||
RESULTADOS = {
|
||||
0: (date(2025, 2, 20), "NEGATIVO", None, None, None),
|
||||
2: (date(2025, 2, 1), "ASC-US", "POSITIVO", 1, 0),
|
||||
3: (date(2025, 4, 25), "LIEBG", "POSITIVO", 0, 0),
|
||||
4: (date(2025, 6, 9), "NEGATIVO", None, None, None),
|
||||
5: (date(2025, 7, 11), "LIEAG", "POSITIVO", 0, 1),
|
||||
6: (date(2025, 8, 22), "NEGATIVO", "NEGATIVO", None, None),
|
||||
}
|
||||
|
||||
# (índice de la citología que la originó, fecha de solicitud, fecha de reporte, grado CIN)
|
||||
BIOPSIAS = (
|
||||
(3, date(2025, 5, 1), date(2025, 5, 20), "CIN1"),
|
||||
(5, date(2025, 7, 15), date(2025, 8, 1), "CIN2"),
|
||||
(6, date(2025, 9, 1), None, None),
|
||||
)
|
||||
|
||||
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
|
||||
COLPOSCOPIA, ONCOLOGIA, FAMILIAR = "CLINICA DE MUJER Y COLPOSCOPIA", "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
NOTAS = (
|
||||
("H-004", date(2025, 8, 10), "D06.9", COLPOSCOPIA), # 72 días de su toma de mayo y 40 de la de julio
|
||||
("H-003", date(2024, 12, 1), "C53.9", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
|
||||
("H-001", date(2025, 3, 1), "N87.1", FAMILIAR), # displasia, pero de medicina familiar: no resuelve
|
||||
("H-002", date(2025, 9, 15), "C53", ONCOLOGIA), # a 194 días de su toma: fuera del horizonte
|
||||
("H-005", date(2026, 1, 20), "c539", COLPOSCOPIA), # 161 días de su toma, pero después del corte de fin de año
|
||||
)
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la especialidad de la tercera no está en el catálogo de Core
|
||||
# y queda sin reconocer; la cuarta está pedida y todavía no tiene citología.
|
||||
ORDENES = (
|
||||
(50001, "H-001", date(2025, 2, 3), "MEDICINA FAMILIAR"),
|
||||
(50002, "H-003", date(2025, 4, 10), "CLINICA DE MUJER Y COLPOSCOPIA"),
|
||||
(50003, "H-004", date(2025, 6, 25), "Dermatología"),
|
||||
(50004, "H-005", date(2025, 12, 1), "MEDICINA FAMILIAR"),
|
||||
)
|
||||
|
||||
# Índice en CITOLOGIAS -> número de su orden. Las demás citologías no traen número; la de
|
||||
# H-005 trae uno que no existe entre las órdenes.
|
||||
ORDEN_DE_CITOLOGIA = {0: 50001, 3: 50002, 5: 50003, 6: 59999}
|
||||
|
||||
# periodo -> (denominador, numerador) de IND1, con la lista de `cacu.citologia_anomala`
|
||||
# (ASC-US, ASC-H, LIEBG, LIEAG, CIS). En S1 solo H-003 (su ASC-US y su LIEBG; cuenta una
|
||||
# vez); en S2 solo H-004 (su LIEAG del 1 de julio).
|
||||
ESPERADO_IND1 = {"2025-S1": (4, 1), "2025-S2": (4, 1)}
|
||||
|
||||
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CACU_EU_TIEMPO_REPORTE,
|
||||
# con horizonte de 60 días. Días de toma a resultado: S1 10, 12, 10, 10 (la toma del 5 de
|
||||
# marzo no tiene resultado y a fin de año ya pasó el horizonte: cuenta en la inicial y no en
|
||||
# n); S2 10, 10. A mediados de octubre las tomas de septiembre y octubre sin resultado siguen
|
||||
# dentro del horizonte: no se miden. A mediados de agosto el resultado del 22 todavía no existe.
|
||||
ESPERADO_CACU_TIEMPO = {
|
||||
("2025-S1", "2025-12-31"): (5, 4, 10.0, 10.0, 10.5),
|
||||
("2025-S2", "2025-12-31"): (4, 2, 10.0, 10.0, 10.0),
|
||||
("2025-S2", "2025-10-15"): (2, 2, 10.0, 10.0, 10.0),
|
||||
("2025-S2", "2025-08-15"): (1, 1, 10.0, 10.0, 10.0),
|
||||
}
|
||||
|
||||
# periodo -> (denominador, numerador) de CACU_EU13, con la lista de arranque de
|
||||
# `cacu.deteccion_grados` (LIEAG, CIS, CARCINOMA). Los grados de las biopsias de
|
||||
# este fixture (CIN1, CIN2) son textos provisionales que no están en esa lista:
|
||||
# el numerador es cero. El distinto de cero se prueba con filas escritas a mano
|
||||
# en `cacu/familias/eu13/casos.toml`.
|
||||
ESPERADO_CACU_EU13 = {"2025-S1": (4, 0), "2025-S2": (4, 0)}
|
||||
|
||||
# periodo -> {categoría: pacientes} de CACU_EU7 (solo las que tienen alguna). En S1, H-003
|
||||
# cuenta con el LIEBG de abril (su ASC-US de enero es de una muestra insatisfactoria y,
|
||||
# además, anterior) y H-002 no tiene resultado; en S2, H-006 no tiene resultado y la de
|
||||
# octubre de H-001 todavía no. «NEGATIVO» es un texto provisional de este fixture: no está
|
||||
# en el catálogo (que usa NORMAL, como Core) y sale después de SIN_DATO.
|
||||
ESPERADO_CACU_EU7 = {
|
||||
"2025-S1": {"NEGATIVO": 2, "LIEBG": 1, "SIN_DATO": 1},
|
||||
"2025-S2": {"NEGATIVO": 1, "LIEAG": 1, "SIN_DATO": 2},
|
||||
}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Inserta pacientes, órdenes, citologías y biopsias. `pac_id` se resuelve por `pac_id_hospital`."""
|
||||
pacientes = {
|
||||
hospital: Paciente(
|
||||
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1)
|
||||
)
|
||||
for hospital in PACIENTES
|
||||
}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
OrdenesEstudio(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=numero,
|
||||
ord_tipo_estudio="SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
ord_fecha=fecha,
|
||||
ord_especialidad=especialidad,
|
||||
)
|
||||
for numero, hospital, fecha, especialidad in ORDENES
|
||||
)
|
||||
citologias = []
|
||||
for indice, (hospital, toma, calidad) in enumerate(CITOLOGIAS):
|
||||
reporte, escamosas, vph, genotipo_16, genotipo_18 = RESULTADOS.get(indice, (None,) * 5)
|
||||
citologias.append(
|
||||
CitologiaCervical(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=ORDEN_DE_CITOLOGIA.get(indice),
|
||||
cit_fecha_toma=toma,
|
||||
cit_calidad_especimen=calidad,
|
||||
cit_fecha_reporte=reporte,
|
||||
cit_celulas_escamosas=escamosas,
|
||||
cit_vph_resultado=vph,
|
||||
cit_vph_genotipo_16=genotipo_16,
|
||||
cit_vph_genotipo_18=genotipo_18,
|
||||
)
|
||||
)
|
||||
sesion.add_all(citologias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
citologia = citologias[indice]
|
||||
sesion.add(
|
||||
BiopsiaCervical(
|
||||
pac_id=citologia.pac_id,
|
||||
pac_id_hospital=citologia.pac_id_hospital,
|
||||
cit_id=citologia.cit_id,
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_cin_grado=grado,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
NotaMedica(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
nm_id_hospital=f"NM-{numero:03d}",
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
sesion.commit()
|
||||
@@ -1,171 +0,0 @@
|
||||
"""Filas sintéticas del staging de CaMa, escritas a mano. Nunca datos reales.
|
||||
|
||||
Seis pacientes y nueve mastografías en dos semestres de 2025. Los textos
|
||||
de calidad son provisionales: los valores reales están sin confirmar.
|
||||
|
||||
Mastografías: 5 en 2025-S1 y 4 en 2025-S2; de ellas, satisfactorias, 4 y 2.
|
||||
Lo que da cada indicador va abajo (`ESPERADO_*`).
|
||||
|
||||
Casos que ejercita: H-001 tiene dos mastografías en S1 y cuentan las dos;
|
||||
una del 1 de julio ya es S2; una de S2 no tiene calidad y cuenta en el
|
||||
denominador pero no en el numerador.
|
||||
|
||||
Resultados (v0.5.0, T-4): cada mastografía trae su BI-RADS; tiene fecha
|
||||
de reporte una semana después de la toma, salvo la que no tiene calidad
|
||||
ni BI-RADS y la última, todavía sin reporte.
|
||||
|
||||
Tres biopsias, cada una con la mastografía que la originó: dos con
|
||||
reporte y grado, y una solicitada que todavía no lo tiene.
|
||||
|
||||
Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`:
|
||||
lo único común entre los dos sistemas es `pac_id_hospital`.
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SATISFACTORIO = "SATISFACTORIO"
|
||||
INSATISFACTORIO = "INSATISFACTORIO"
|
||||
|
||||
PACIENTES = ("H-101", "H-102", "H-001", "H-003", "H-103", "H-104")
|
||||
|
||||
# (pac_id_hospital, fecha de toma, calidad de imagen, BI-RADS)
|
||||
MASTOGRAFIAS = (
|
||||
("H-101", date(2025, 1, 15), SATISFACTORIO, "B1"),
|
||||
("H-102", date(2025, 2, 20), SATISFACTORIO, "B2"),
|
||||
("H-001", date(2025, 3, 10), INSATISFACTORIO, "B0"),
|
||||
("H-001", date(2025, 4, 2), SATISFACTORIO, "B1"),
|
||||
("H-003", date(2025, 6, 30), SATISFACTORIO, "B4A"),
|
||||
("H-103", date(2025, 7, 1), SATISFACTORIO, "B1"),
|
||||
("H-103", date(2025, 9, 9), None, None),
|
||||
("H-104", date(2025, 11, 11), INSATISFACTORIO, "B0"),
|
||||
("H-102", date(2025, 12, 31), SATISFACTORIO, "B2"),
|
||||
)
|
||||
|
||||
# (índice de la mastografía que la originó, fecha de solicitud, fecha de reporte, grado histológico)
|
||||
BIOPSIAS = (
|
||||
(2, date(2025, 3, 20), date(2025, 4, 5), "BENIGNO"),
|
||||
(4, date(2025, 7, 10), date(2025, 7, 28), "CARCINOMA_INVASOR"),
|
||||
(7, date(2025, 11, 20), None, None),
|
||||
)
|
||||
|
||||
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
|
||||
# La de H-003 llega con minúscula y punto; la de H-104 no tiene fecha y la de H-101 es de
|
||||
# medicina familiar, que no resuelve la toma.
|
||||
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
NOTAS = (
|
||||
("H-003", date(2025, 8, 4), "c50.4", ONCOLOGIA), # 35 días de su B4A del 30 de junio
|
||||
("H-001", date(2025, 3, 1), "D05.1", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
|
||||
("H-102", date(2025, 9, 30), "C50.9", ONCOLOGIA), # a 222 días de su toma de febrero: fuera del horizonte
|
||||
("H-103", date(2025, 7, 20), "C50.9", ONCOLOGIA), # 19 días de su toma del 1 de julio
|
||||
("H-101", date(2025, 1, 15), "Z12.3", FAMILIAR), # normal, pero de medicina familiar: no resuelve
|
||||
("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta
|
||||
)
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía.
|
||||
ORDENES = (
|
||||
(60001, "H-101", date(2025, 1, 10), "MEDICINA FAMILIAR"),
|
||||
(60002, "H-003", date(2025, 6, 20), "CIRUGIA ONCOLOGICA"),
|
||||
(60003, "H-104", date(2025, 12, 5), "MEDICINA FAMILIAR"),
|
||||
)
|
||||
|
||||
# Índice en MASTOGRAFIAS -> número de su orden. Las demás no traen número; la de H-102 trae
|
||||
# uno que no existe entre las órdenes.
|
||||
ORDEN_DE_MASTOGRAFIA = {0: 60001, 4: 60002, 1: 69999}
|
||||
|
||||
# periodo -> {categoría: pacientes} de CAMA_BIRADS (solo las que tienen alguna).
|
||||
# H-001 tiene B0 y B1 en S1: cuenta en B0, la más grave. H-103 tiene B1 y una toma sin
|
||||
# reporte: cuenta en B1. H-102 tiene en S2 solo una toma sin reporte: SIN_DATO.
|
||||
ESPERADO_CAMA_BIRADS = {
|
||||
"2025-S1": {"B0": 1, "B1": 1, "B2": 1, "B4A": 1},
|
||||
"2025-S2": {"B0": 1, "B1": 1, "SIN_DATO": 1},
|
||||
}
|
||||
|
||||
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CAMA_EU38A, con
|
||||
# horizonte de 60 días. Todo reporte llega siete días después de la toma. A fin de año la
|
||||
# toma del 9 de septiembre ya pasó el horizonte sin reporte (cuenta en la inicial y no en n)
|
||||
# y la del 31 de diciembre sigue en observación. El 15 de septiembre ninguna toma de S2
|
||||
# posterior a julio tiene reporte ni ha vencido: solo se mide la del 1 de julio.
|
||||
ESPERADO_CAMA_EU38A = {
|
||||
("2025-S1", "2025-12-31"): (5, 5, 7.0, 7.0, 7.0),
|
||||
("2025-S2", "2025-12-31"): (3, 2, 7.0, 7.0, 7.0),
|
||||
("2025-S2", "2025-09-15"): (1, 1, 7.0, 7.0, 7.0),
|
||||
}
|
||||
|
||||
# periodo -> (denominador, numerador) de CAMA_CONFIRMACION_BIRADS45, con la lista de arranque de
|
||||
# `cama.birads_sospecha` (B4 con o sin subcategoría, B5). La única mastografía de sospecha es la B4A de H-003 del 30 de
|
||||
# junio, y su biopsia se reportó el 28 de julio: cuenta en S1, el semestre de la mastografía.
|
||||
# Las otras dos biopsias salen de mastografías B0, que no están en la lista. En S2 no hay
|
||||
# ninguna de sospecha: sin denominador, el reporte sale suprimido y no se compara.
|
||||
ESPERADO_CAMA_CONFIRMACION_BIRADS45 = {"2025-S1": (1, 1)}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Inserta pacientes, órdenes, mastografías, biopsias y notas. `pac_id` se resuelve por `pac_id_hospital`."""
|
||||
pacientes = {
|
||||
hospital: Paciente(
|
||||
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1975, 1, 1)
|
||||
)
|
||||
for hospital in PACIENTES
|
||||
}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
OrdenesEstudio(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=numero,
|
||||
ord_tipo_estudio="MASTOGRAFIA",
|
||||
ord_fecha=fecha,
|
||||
ord_especialidad=especialidad,
|
||||
)
|
||||
for numero, hospital, fecha, especialidad in ORDENES
|
||||
)
|
||||
mastografias = []
|
||||
for indice, (hospital, toma, calidad, birads) in enumerate(MASTOGRAFIAS):
|
||||
sin_reporte = birads is None or indice == len(MASTOGRAFIAS) - 1
|
||||
mastografias.append(
|
||||
Mastografia(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=ORDEN_DE_MASTOGRAFIA.get(indice),
|
||||
mast_fecha_toma=toma,
|
||||
mast_calidad_imagen=calidad,
|
||||
mast_birads=birads,
|
||||
mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7),
|
||||
)
|
||||
)
|
||||
sesion.add_all(mastografias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
mastografia = mastografias[indice]
|
||||
sesion.add(
|
||||
BiopsiaMama(
|
||||
pac_id=mastografia.pac_id,
|
||||
pac_id_hospital=mastografia.pac_id_hospital,
|
||||
mast_id=mastografia.mast_id,
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_grado_histologico=grado,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
NotaMedica(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
nm_id_hospital=f"NM-{numero:03d}",
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
sesion.commit()
|
||||
@@ -1,87 +0,0 @@
|
||||
"""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 `event_models` (dbt's views); `manifest`, dbt's
|
||||
`manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published
|
||||
numbers for each measure and period (counts only; suppression off).
|
||||
"""
|
||||
|
||||
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 = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def 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
|
||||
@@ -0,0 +1,120 @@
|
||||
"""`commit_discovered_fields`: writes captions no known field claims
|
||||
straight into `procedimiento`/`observacion`, tagged apart from every
|
||||
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
|
||||
patient's discovered fields stop landing there, or if an unmatched one
|
||||
stops growing the catalog instead of being silently dropped.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from indicadores_kit.registry import catalogos
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||
return ExtractedRecord(
|
||||
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_catalog(tmp_path, monkeypatch):
|
||||
"""`add_resultado`/`sincronizar` write real rows and a real file:
|
||||
kept off the checked-in `cacu.toml` and off any other domain's data."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text(
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def known_patient(wire_domain):
|
||||
wire_domain("cacu")
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
return "DOC-FB-1"
|
||||
|
||||
|
||||
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
|
||||
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
|
||||
assert procedimiento.fuente_id == known_patient
|
||||
|
||||
|
||||
def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert result.fields_minted == 1
|
||||
nombres = set(catalogos._leer(cacu_catalog)["citologia"]["resultados"])
|
||||
assert nombres == {"calidad_muestra", "tipo_de_fijador"} # the fixture's field, plus the minted one
|
||||
minted_id = "citologia.tipo_de_fijador"
|
||||
|
||||
catalogo = catalogos.catalogo_desde_toml(cacu_catalog, tablas=tablas_de("cacu"))
|
||||
assert minted_id in {r.resultado_id for r in catalogo.resultados}
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == minted_id
|
||||
assert observacion.valor_texto == "Formol"
|
||||
|
||||
|
||||
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.records_without_patient) == (0, 1)
|
||||
|
||||
|
||||
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
|
||||
assert result.records_written == 0
|
||||
|
||||
|
||||
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
|
||||
"""A static label printed on several pages of the same document (a date,
|
||||
a signature line) discovers as one `DiscoveredField` per occurrence,
|
||||
on purpose (`discover_captions`'s docstring). Fails if this stops
|
||||
folding repeats before writing: `observacion` has one row per
|
||||
`(procedimiento, resultado_id)`, so a second occurrence of the same
|
||||
resultado_id raises `IntegrityError` and the whole record's fields —
|
||||
including the ones that weren't duplicated — are lost."""
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
|
||||
proyecto="cacu",
|
||||
estudio_id="citologia",
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
@@ -0,0 +1,90 @@
|
||||
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
|
||||
catalog field for an OCR caption that's clearly the same thing worded
|
||||
differently, or if an unmatched caption stops being added to the catalog
|
||||
and silently drops its value instead.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from indicadores_kit.registry import catalogos
|
||||
from indicadores_kit.registry.catalogos import Catalogo
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _field(caption: str, value: str) -> DiscoveredField:
|
||||
return DiscoveredField(caption, value, EVIDENCE)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo() -> Catalogo:
|
||||
tablas = tablas_de("cacu")
|
||||
return Catalogo(
|
||||
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
|
||||
resultados=[
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
|
||||
etiqueta="Calidad de la muestra", tipo_valor="codigo",
|
||||
),
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
|
||||
etiqueta="Células glandulares", tipo_valor="texto",
|
||||
),
|
||||
],
|
||||
valores=[
|
||||
tablas.CatValor(
|
||||
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
|
||||
etiqueta="Satisfactoria", orden=1, estado="vigente",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_toml(tmp_path, monkeypatch):
|
||||
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
|
||||
assert matched.observacion["valor_id"] == "SATISFACTORIO"
|
||||
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
|
||||
|
||||
|
||||
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.is_new and matched.resultado_id.startswith("citologia.")
|
||||
assert matched.observacion["valor_texto"] == "Formol"
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
|
||||
|
||||
|
||||
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
|
||||
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
|
||||
|
||||
|
||||
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
|
||||
fecha, numero, texto = match_or_mint(
|
||||
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
|
||||
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
|
||||
)
|
||||
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
|
||||
assert numero.observacion["valor_numerico"] == 12.5
|
||||
assert texto.observacion["valor_texto"] == "ninguna"
|
||||
@@ -0,0 +1,165 @@
|
||||
"""`DocumentConnector` reading its documents from a SQL source instead of
|
||||
uploaded files: one document per row, read from a column that may hold a
|
||||
PDF (`varbinary(max)`) or already be plain text, both without a filesystem
|
||||
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||
plain-text column stops reaching the same field extraction a PDF does.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
REPORT = text_pdf(
|
||||
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table shaped like ISSSTELEON's: one row per study, its
|
||||
report in a binary column, plus a plain-text variant of the same
|
||||
report in another row, both alongside the row's own key column."""
|
||||
db_path = tmp_path / "estudios.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{"id": "ROW-1", "reporte": REPORT},
|
||||
)
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{
|
||||
"id": "ROW-2",
|
||||
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
||||
},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[first, second] = body["records"]
|
||||
assert first["key"] == "SQL-0001"
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||
"""Fails if a source whose bundle is a plain string (not binary at
|
||||
all) stops producing fields, since ISSSTELEON's column may not always
|
||||
be a PDF (`extraction.readers.TextReader`)."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[_, second] = body["records"]
|
||||
assert second["key"] == "SQL-0002"
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
||||
"label": "estudios",
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
|
||||
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
||||
)
|
||||
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
payload = _sql_payload(sqlite_studies_table)
|
||||
del payload["column"]
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||
fijador`) still reaches the silver layer through the open-catalog
|
||||
path, alongside the recognized fields `commit_sources` writes as
|
||||
before. Fails if `/imports/commit` stops wiring that second path in.
|
||||
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||
the module's other tests sharing this `client`'s database."""
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import create_engine, text as sa_text
|
||||
from sqlmodel import select
|
||||
|
||||
from indicadores_kit.registry import catalogos
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text('[citologia]\netiqueta = "Citología cervical"\n', encoding="utf-8")
|
||||
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||
|
||||
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
||||
with create_engine(db_url).begin() as conn:
|
||||
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
||||
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
||||
"label": "estudios_extra",
|
||||
}
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1, body
|
||||
|
||||
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert report["records_written"] == 1 and report["fields_minted"] == 1
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[minted] = list(
|
||||
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
||||
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
||||
)))
|
||||
)
|
||||
assert minted.resultado_id == "citologia.tipo_de_fijador" and minted.valor_texto == "Formol"
|
||||
@@ -183,19 +183,6 @@ 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"
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""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
|
||||
@@ -0,0 +1,229 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,169 @@
|
||||
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
|
||||
@@ -1,135 +0,0 @@
|
||||
"""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")
|
||||
@@ -1,100 +0,0 @@
|
||||
"""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 (`catalogs` … `event_models`; 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.run("catalogs", "load", "registry", "definitions", "event_models", parameters=sin_supresion,
|
||||
allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
for key, value in case.get("parametros", {}).items():
|
||||
connection.execute(text("update def_parametro set valor = :v where clave = :k"),
|
||||
{"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()
|
||||
@@ -1,474 +0,0 @@
|
||||
"""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 `event_models` (which creates dbt's event models);
|
||||
`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13
|
||||
and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against.
|
||||
"""
|
||||
|
||||
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.orchestration import run
|
||||
|
||||
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
|
||||
STATUS = "estatus_seguimiento"
|
||||
HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"]
|
||||
SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json"
|
||||
|
||||
|
||||
@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.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@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 `load`: a new load, known later than everything before."""
|
||||
time.sleep(0.01)
|
||||
with Session(base.motor) as session:
|
||||
change(session)
|
||||
session.commit()
|
||||
run(base.ctx, only=["load"])
|
||||
|
||||
|
||||
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_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7):
|
||||
"""Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't
|
||||
enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the
|
||||
stratum values the catalog lacks."""
|
||||
for d in (eu13, eu7):
|
||||
ask(base, d, "2025-S1")
|
||||
with base.motor.connect() as connection:
|
||||
written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar()
|
||||
broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all()
|
||||
assert written > 0
|
||||
assert broken == []
|
||||
|
||||
|
||||
def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7):
|
||||
"""Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same
|
||||
answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing."""
|
||||
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 webapi.follow_up.status import estatus_al, reglas_de
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
from webapi.follow_up.listing import leer_estrato
|
||||
from sqlalchemy import bindparam
|
||||
|
||||
rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
|
||||
|
||||
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,23 @@
|
||||
"""What this module covers: the whole cycle on the CaCu fixture database, in order, once and again.
|
||||
"""El ciclo deja los mismos reportes que la base de demostración del kit.
|
||||
|
||||
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.
|
||||
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.
|
||||
"""
|
||||
|
||||
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 webapi.orchestration import Context, run
|
||||
from webapi.orchestration.connection import point_to
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
from webapi.orquestacion import Contexto, correr
|
||||
from webapi.orquestacion.conexion import apuntar
|
||||
|
||||
ANIO = 2025
|
||||
# Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas).
|
||||
@@ -25,42 +27,51 @@ 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"])
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama", "tea"])
|
||||
def bases(request, tmp_path_factory):
|
||||
proyecto = request.param
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
url = f"sqlite:///{carpeta / 'orquestada.db'}"
|
||||
point_to(proyecto, url)
|
||||
# `observe` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de
|
||||
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 = Context(proyecto, ANIO, ANIO, allow_undecided=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"]))
|
||||
run(ctx, only=["migrate"])
|
||||
ctx = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True)
|
||||
correr(ctx, solo=["migrar"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
import_module(f"staging.{proyecto}").insertar(sesion)
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
pasos = run(ctx)
|
||||
return proyecto, ctx, motor, None, pasos
|
||||
pasos = correr(ctx)
|
||||
demostracion = create_engine(f"sqlite:///{carpeta / 'demostracion.db'}")
|
||||
base_de_prueba(demostracion, proyecto)
|
||||
return proyecto, ctx, motor, demostracion, pasos
|
||||
|
||||
|
||||
def test_corre_todos_los_pasos_en_orden(bases):
|
||||
proyecto, _, _, _, pasos = bases
|
||||
nombres = [p.name for p in pasos]
|
||||
# `migrate` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9).
|
||||
assert nombres[0] == "migrate" and nombres.index("catalogs") < nombres.index("load")
|
||||
assert nombres.index("load") < nombres.index("event_models") and "calcular" not in nombres
|
||||
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")
|
||||
|
||||
|
||||
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()
|
||||
run(ctx)
|
||||
correr(ctx)
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
|
||||
|
||||
@@ -68,15 +79,46 @@ def test_volver_a_correr_no_agrega_reportes(bases):
|
||||
def test_en_cacu_arma_su_cohorte_una_vez(bases):
|
||||
proyecto, ctx, motor, _, pasos = bases
|
||||
if proyecto != "cacu":
|
||||
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
assert "cohortes" not in [p.nombre for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
return
|
||||
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
|
||||
(armado_id, nuevo), = [p.resumen for p in pasos if p.nombre == "cohortes"][0].values()
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
|
||||
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
|
||||
|
||||
+118
-23
@@ -1,4 +1,4 @@
|
||||
"""Los pasos de oro sobre la base del dominio: el registro y las definiciones (el catálogo, del manifiesto de dbt).
|
||||
"""Los pasos de oro sobre la base del dominio: el registro, las definiciones y el cálculo.
|
||||
|
||||
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,50 +7,107 @@ repositorios de Persistance, como lo leería `WebApi`.
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.silver.loads import tablas_de_staging
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, valores_del_archivo
|
||||
from webapi.orchestration.reference.periods import periodos_de_tipos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from webapi.orchestration.project import period_types
|
||||
from 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 ("load",)
|
||||
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):
|
||||
base.run("registry")
|
||||
base.run("registry", year_from=ANIO - 1)
|
||||
base.correr("registro")
|
||||
base.correr("registro", anio_inicio=ANIO - 1)
|
||||
|
||||
tablas = tablas_de(base.proyecto)
|
||||
esperados = periodos_de_tipos(period_types(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas)
|
||||
esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto), ANIO - 1, ANIO, tablas=tablas)
|
||||
assert base.dominio.dim_periodo_repository.count() == len(esperados)
|
||||
assert base.dominio.measure_report_repository.count() == 0
|
||||
|
||||
|
||||
def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base):
|
||||
"""I-MD27 (T-24f): de `comun.dim_fecha.desde` al fin del último año, y los grupos de `<proyecto>.grupos_edad`."""
|
||||
base.run("registry")
|
||||
base.run("registry", year_to=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
|
||||
base.correr("registro")
|
||||
base.correr("registro", anio_fin=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
|
||||
|
||||
valores = valores_del_archivo(RUTA_PARAMETROS)
|
||||
desde = date.fromisoformat(valores["comun.dim_fecha.desde"])
|
||||
@@ -63,35 +120,73 @@ 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):
|
||||
base.run("registry")
|
||||
base.correr("registro")
|
||||
periodos = base.dominio.dim_periodo_repository.count()
|
||||
malo = tmp_path / "malo.toml"
|
||||
malo.write_text('[comun.x]\nvalor = 1\nestado = "provisional"\n', encoding="utf-8")
|
||||
|
||||
with pytest.raises(ValueError, match="fuente"):
|
||||
base.run("registry", year_from=ANIO - 1, year_to=ANIO + 1, parameters=malo)
|
||||
base.correr("registro", anio_inicio=ANIO - 1, anio_fin=ANIO + 1, parametros=malo)
|
||||
|
||||
assert base.dominio.def_parametro_repository.get("comun.x") is None
|
||||
assert base.dominio.def_parametro_repository.get("comun.umbral_supresion") is not None
|
||||
assert base.dominio.dim_periodo_repository.count() == periodos
|
||||
|
||||
|
||||
def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
"""Pins down: `definitions` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a
|
||||
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
def test_las_definiciones_son_las_de_los_toml(base):
|
||||
resumen = base.correr("definiciones")["definiciones"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: its seven measures, without strata.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto]
|
||||
assert resumen["definiciones"] == len(measures_de(base.proyecto))
|
||||
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
|
||||
assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
assert base.dominio.cat_measure_repository.count() == len(measures_de(base.proyecto))
|
||||
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
|
||||
|
||||
@@ -3,38 +3,38 @@
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
from webapi.orchestration import cycle, steps_of
|
||||
from webapi.orquestacion import ciclo, pasos_de
|
||||
|
||||
|
||||
def dependencias(proyecto: str) -> dict[str, set[str]]:
|
||||
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
||||
dr = driver.Builder().with_modules(ciclo).with_config({"con_cohortes": proyecto == "cacu"}).build()
|
||||
return {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
||||
|
||||
|
||||
def antes(deps: dict[str, set[str]], paso: str) -> set[str]:
|
||||
"""Todos los pasos que corren antes de `paso`."""
|
||||
previos = set()
|
||||
pending = list(deps[paso])
|
||||
while pending:
|
||||
anterior = pending.pop()
|
||||
pendientes = list(deps[paso])
|
||||
while pendientes:
|
||||
anterior = pendientes.pop()
|
||||
if anterior not in previos:
|
||||
previos.add(anterior)
|
||||
pending.extend(deps[anterior])
|
||||
pendientes.extend(deps[anterior])
|
||||
return previos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
deps = dependencias(proyecto)
|
||||
assert deps["migrate"] == set()
|
||||
assert {"migrate", "catalogs"} <= antes(deps, "load") # decisión 6 de §9
|
||||
assert {"load"} <= antes(deps, "event_models")
|
||||
assert {"registry"} <= antes(deps, "observe")
|
||||
assert {"load", "catalogs"} <= antes(deps, "check_silver")
|
||||
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")
|
||||
|
||||
|
||||
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
|
||||
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
|
||||
assert {"cohortes", "estimar"} <= set(pasos_de("cacu"))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
|
||||
assert not {"cohortes", "estimar"} & set(pasos_de(proyecto))
|
||||
|
||||
@@ -10,15 +10,16 @@ from datetime import date
|
||||
|
||||
import pytest
|
||||
from conftest import base_de
|
||||
from webapi.orchestration.silver.loads import tablas_de_staging
|
||||
from webapi.orchestration.silver.observation_periods import (
|
||||
from indicadores_kit.plata.carga import tablas_de_staging
|
||||
from indicadores_kit.plata.periodo_observacion import (
|
||||
TIPO_EXTRACCION,
|
||||
ObservacionSinCorte,
|
||||
clave_de_inicio,
|
||||
)
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, ParametroSinDefinir
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from 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
|
||||
|
||||
@@ -26,12 +27,13 @@ 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)
|
||||
|
||||
|
||||
def ultima_carga(base):
|
||||
return max(base.ctx.repos.silver.loads.list(limit=100), key=lambda c: c.carga_id)
|
||||
return max(base.ctx.repos.plata.carga.list(limit=100), key=lambda c: c.carga_id)
|
||||
|
||||
|
||||
def contar(base, sql: str) -> int:
|
||||
@@ -60,7 +62,7 @@ def cambiar_staging(base) -> str:
|
||||
|
||||
def filas_del_catalogo(base) -> dict[str, int]:
|
||||
"""Cuántas filas tiene cada tabla de catálogo en la base."""
|
||||
plata = base.ctx.repos.silver.catalogs
|
||||
plata = base.ctx.repos.plata.catalogos
|
||||
with base.staging() as sesion:
|
||||
return {
|
||||
"estudios": len(sesion.exec(select(plata.model)).all()),
|
||||
@@ -74,15 +76,15 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
|
||||
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
|
||||
"valores": len(catalogo.valores)}
|
||||
|
||||
assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
|
||||
assert base.correr("catalogos")["catalogos"] == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.run("catalogs")
|
||||
base.correr("catalogos")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
assert base.run("catalogs")["catalogs"]["retirados"] == 0
|
||||
assert base.correr("catalogos")["catalogos"]["retirados"] == 0
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
@@ -90,14 +92,14 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
|
||||
|
||||
def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
|
||||
base.run("catalogs")
|
||||
carga = base.run("load")["load"]
|
||||
base.correr("catalogos")
|
||||
carga = base.correr("cargar")["cargar"]
|
||||
|
||||
procedimientos, observaciones = plata_de(base)
|
||||
assert procedimientos and observaciones
|
||||
assert carga.fin is not None and (carga.filas_nuevas, carga.filas_cambiadas, carga.filas_sin_cambio) == (
|
||||
procedimientos, 0, 0)
|
||||
assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronze.staging.read(
|
||||
assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronce.staging.leer(
|
||||
{"p": tablas_de_staging(base.proyecto)[0]})["p"])
|
||||
# Ningún reporte ni parte sin su toma (salvo los huérfanos, que no se escriben).
|
||||
assert contar(base, "SELECT COUNT(*) FROM procedimiento WHERE clase IN ('reporte', 'parte') AND padre_id IS NULL") == 0
|
||||
@@ -105,13 +107,20 @@ 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):
|
||||
base.run("catalogs", "load")
|
||||
base.correr("catalogos", "cargar")
|
||||
antes = plata_de(base)
|
||||
|
||||
segunda = base.run("load")["load"]
|
||||
segunda = base.correr("cargar")["cargar"]
|
||||
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 0, antes[0])
|
||||
assert plata_de(base) == antes
|
||||
for tabla in ("procedimiento", "observacion_clinica"):
|
||||
@@ -119,26 +128,36 @@ def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
|
||||
|
||||
|
||||
def test_un_cambio_en_staging_toca_un_procedimiento(base):
|
||||
base.run("catalogs", "load")
|
||||
base.correr("catalogos", "cargar")
|
||||
antes = plata_de(base)
|
||||
cambiar_staging(base)
|
||||
|
||||
segunda = base.run("load")["load"]
|
||||
segunda = base.correr("cargar")["cargar"]
|
||||
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 1, antes[0] - 1)
|
||||
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 ---
|
||||
|
||||
|
||||
def test_las_vistas_se_construyen_y_se_pueden_repetir(base):
|
||||
primera = base.run("views")["views"]
|
||||
primera = base.correr("vistas")["vistas"]
|
||||
|
||||
assert base.run("views")["views"] == primera
|
||||
# Only `v_persona`: the published numbers are answered on request, so the publication views aren't built.
|
||||
assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"]
|
||||
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"]
|
||||
|
||||
|
||||
# --- observar ---
|
||||
@@ -166,9 +185,9 @@ observables = pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
|
||||
@observables
|
||||
def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
base.correr("cargar", "registro", parametros=con_regla("2024-06-01"))
|
||||
|
||||
cuantos = base.run("observe", cutoff=CORTE)["observe"]
|
||||
cuantos = base.correr("observar", corte=CORTE)["observar"]
|
||||
|
||||
periodos = base.dominio.periodo_observacion_repository.list()
|
||||
assert cuantos == len(periodos) == base.dominio.persona_repository.count()
|
||||
@@ -178,9 +197,9 @@ def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
|
||||
|
||||
@observables
|
||||
def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla())
|
||||
base.correr("cargar", "registro", parametros=con_regla())
|
||||
|
||||
base.run("observe")
|
||||
base.correr("observar")
|
||||
|
||||
carga = ultima_carga(base)
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {
|
||||
@@ -189,10 +208,10 @@ def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_re
|
||||
|
||||
@observables
|
||||
def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla())
|
||||
base.correr("cargar", "registro", parametros=con_regla())
|
||||
|
||||
primera = base.run("observe", cutoff=date(2025, 6, 30))["observe"]
|
||||
segunda = base.run("observe", cutoff=CORTE)["observe"]
|
||||
primera = base.correr("observar", corte=date(2025, 6, 30))["observar"]
|
||||
segunda = base.correr("observar", corte=CORTE)["observar"]
|
||||
|
||||
assert primera == segunda == base.dominio.periodo_observacion_repository.count()
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE}
|
||||
@@ -200,37 +219,37 @@ def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
|
||||
|
||||
@observables
|
||||
def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base):
|
||||
base.run("load", "registry")
|
||||
base.correr("cargar", "registro")
|
||||
|
||||
with pytest.raises(ParametroSinDefinir, match="inicio_datos"):
|
||||
base.run("observe", cutoff=CORTE)
|
||||
assert base.run("observe", cutoff=CORTE, allow_undecided=True)["observe"] == (
|
||||
base.correr("observar", corte=CORTE)
|
||||
assert base.correr("observar", corte=CORTE, permitir_sin_definir=True)["observar"] == (
|
||||
base.dominio.persona_repository.count())
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_el_registro_observar_dice_que_falta(base):
|
||||
base.run("load")
|
||||
base.correr("cargar")
|
||||
|
||||
with pytest.raises(KeyError, match="preparar_registro|registro"):
|
||||
base.run("observe", cutoff=CORTE)
|
||||
base.correr("observar", corte=CORTE)
|
||||
|
||||
|
||||
@observables
|
||||
def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
base.correr("cargar", "registro", parametros=con_regla("2024-06-01"))
|
||||
|
||||
with pytest.raises(ValueError, match="anterior al inicio"):
|
||||
base.run("observe", cutoff=date(2024, 5, 31))
|
||||
base.correr("observar", corte=date(2024, 5, 31))
|
||||
assert base.dominio.periodo_observacion_repository.count() == 0
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
|
||||
base.run("registry", parameters=con_regla())
|
||||
base.correr("registro", parametros=con_regla())
|
||||
|
||||
with pytest.raises(ObservacionSinCorte):
|
||||
base.run("observe")
|
||||
base.correr("observar")
|
||||
|
||||
|
||||
# --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA ---
|
||||
@@ -239,7 +258,7 @@ def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_verificar_plata_en_cacu_cuenta_los_valores_fuera_de_catalogo_del_fixture(base):
|
||||
conteos = base.run("catalogs", "load", "check_silver")["check_silver"]
|
||||
conteos = base.correr("catalogos", "cargar", "verificar_plata")["verificar_plata"]
|
||||
|
||||
# I-MD16 (textos del fixture fuera del catálogo) e I-MD18 (especialidades que el alias no reconoce): en la
|
||||
# plata, una observación de código sin `valor_id` y con su `valor_fuente`.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`.
|
||||
|
||||
Las subclases viven en `persistance/edges/` y Persistance las instancia con su
|
||||
fábrica de sesión (ADR-MD-005). Solo `connection.py` nombra a `persistance.db`: cambia a
|
||||
Las subclases viven en `persistance/aristas/` y Persistance las instancia con su
|
||||
fábrica de sesión (ADR-MD-005). Solo `conexion.py` nombra a `persistance.db`: cambia a
|
||||
qué base apunta Persistance (`<PROYECTO>_DATABASE_URL` en memoria); no es un paso.
|
||||
"""
|
||||
|
||||
@@ -10,10 +10,10 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
PAQUETE = Path(__file__).parents[1] / "webapi" / "orchestration"
|
||||
EXENTOS = {"connection.py"}
|
||||
PAQUETE = Path(__file__).parents[1] / "webapi" / "orquestacion"
|
||||
EXENTOS = {"conexion.py"}
|
||||
PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db")
|
||||
|
||||
|
||||
@@ -23,8 +23,8 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
|
||||
assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)])
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)])
|
||||
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
|
||||
repos = repositories_of(proyecto)
|
||||
assert (repos.gold.cohorts is not None) == con_cohortes
|
||||
assert repos.gold.calculation.model.__tablename__ == "measure_report"
|
||||
repos = repositorios_de(proyecto)
|
||||
assert (repos.oro.cohorte is not None) == con_cohortes
|
||||
assert repos.oro.calculo.model.__tablename__ == "measure_report"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba.
|
||||
"""El paso `estimar` y la orden `confirmar-riesgos` (ADR-MD-008), con un estimador de prueba.
|
||||
|
||||
El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow.
|
||||
"""
|
||||
@@ -8,7 +8,7 @@ from dataclasses import dataclass
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orchestration.__main__ import confirm_risks, main
|
||||
from webapi.orquestacion.__main__ import confirmar_riesgos, main
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
|
||||
@@ -43,7 +43,7 @@ class EstimadorFijo:
|
||||
|
||||
@pytest.fixture
|
||||
def cacu(base):
|
||||
base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True)
|
||||
base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True)
|
||||
return base
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ def cuenta(base, sql):
|
||||
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
estimador = EstimadorFijo()
|
||||
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
|
||||
(lote_id, nuevo) = cacu.correr("estimar", estimadores={URL: estimador})["estimar"][URL]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
@@ -68,23 +68,23 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(primero, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
|
||||
|
||||
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
|
||||
assert cacu.run("estimate")["estimate"] == {}
|
||||
assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False)
|
||||
assert cacu.correr("estimar")["estimar"] == {}
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(lote_id, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
|
||||
main(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "revisado"])
|
||||
assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros
|
||||
|
||||
assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros
|
||||
assert confirmar_riesgos("cacu", lote_id, "error de captura", anular=True) == miembros
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
|
||||
|
||||
|
||||
@@ -95,3 +95,21 @@ 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,72 +1,64 @@
|
||||
"""What this module covers: the timeline `repositories_of` wires into `ctx.repos.silver` is dbt's view
|
||||
`cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's
|
||||
facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them.
|
||||
"""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.
|
||||
|
||||
Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created
|
||||
(`catalogs`, `load`, `event_models`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on
|
||||
that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time).
|
||||
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.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
from indicadores_kit.oro.cohortes.armado import filas_de_linea
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from sqlmodel import Session
|
||||
|
||||
CORTE = date(2025, 12, 31)
|
||||
INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"}
|
||||
KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proyecto():
|
||||
return "cacu"
|
||||
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 loaded(base):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base.run("catalogs", "load", "event_models")
|
||||
return base
|
||||
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 kit_rows():
|
||||
return json.loads(KIT_ROWS.read_text(encoding="utf-8"))
|
||||
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.
|
||||
|
||||
|
||||
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.silver.timeline.read(until=CORTE)
|
||||
assert as_kit(rows) == kit_rows
|
||||
assert {row["tipo"] for row in rows} & INFERRED
|
||||
assert all(isinstance(row["fecha"], date) for row in rows)
|
||||
|
||||
|
||||
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.silver.timeline.read(patients=patients, until=CORTE)
|
||||
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)
|
||||
assert {row["pac_id"] for row in rows} == set(patients)
|
||||
assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients]
|
||||
assert rows == kit_rows(base, pacientes=patients, hasta=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.silver.timeline
|
||||
everything = timeline.read(until=CORTE)
|
||||
known = {row["conocida_en"] for row in everything}
|
||||
assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known)
|
||||
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
|
||||
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)
|
||||
|
||||
+10
-22
@@ -2,9 +2,8 @@
|
||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
||||
there.
|
||||
|
||||
Fixtures: `client`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`:
|
||||
a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the
|
||||
same app without `DEV_REVISION`.
|
||||
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
|
||||
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
@@ -19,8 +18,9 @@ HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@@ -47,25 +47,19 @@ def seeded(client):
|
||||
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
batch, _ = cacu.cohorte_repository.guardar_lote(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
||||
cacu.cohorte_repository.cambiar_estado(batch, "final", "revisado")
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in
|
||||
ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which
|
||||
would break the WebApp's validation."""
|
||||
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
|
||||
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
|
||||
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
|
||||
the WebApp's validation."""
|
||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
||||
|
||||
body = response.get_json()
|
||||
@@ -91,9 +85,3 @@ def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
||||
def test_an_unknown_patient_is_404(client, seeded):
|
||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
||||
|
||||
|
||||
def test_outside_dev_the_route_does_not_exist(fuera_de_dev):
|
||||
"""Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside
|
||||
the simulated DEV deployment."""
|
||||
assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404
|
||||
|
||||
@@ -97,18 +97,16 @@ def test_report_endpoints(client):
|
||||
|
||||
|
||||
def test_indicators_recompute_from_imported_rows(client):
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
|
||||
cola = RecomputationQueue()
|
||||
cola = ColaDeRecalculo()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.serve() == ["cacu"]
|
||||
assert cola.atender() == ["cacu"]
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
|
||||
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
|
||||
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert client.get("/cacu/indicadores").get_json()
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
||||
|
||||
+10
-10
@@ -142,16 +142,6 @@ 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
|
||||
@@ -164,6 +154,16 @@ 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,8 +34,6 @@ 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")
|
||||
|
||||
+13
-12
@@ -1,7 +1,8 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y siempre simulada.
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: cuándo existe, la forma y los códigos de error.
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: que existe sin `DEV_REVISION`, la forma y los códigos
|
||||
de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostración de CaCu.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
@@ -14,19 +15,15 @@ LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia",
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
"""Fija: sin `DEV_REVISION` la ruta existe, con la forma del contrato y `simulado: true`. Falla si la ruta
|
||||
vuelve a depender de una variable de entorno o cambia un campo."""
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||
@@ -63,5 +60,9 @@ def test_una_pagina_de_mas_da_404(client):
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
|
||||
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
|
||||
def test_en_dev_esta_obsoleta():
|
||||
"""Fija: `en_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
|
||||
from webapi.seguimiento import en_dev
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
en_dev()
|
||||
|
||||
@@ -1120,6 +1120,34 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/55/ecca97ae19075f1fac62def77731e7f535e6c1fb8f92ff08160c5e6dade8/importlib_metadata-9.0.1-py3-none-any.whl", hash = "sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0", size = 27920, upload-time = "2026-08-28T15:30:33.433Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indicadores-kit"
|
||||
version = "0.8.0"
|
||||
source = { editable = "../indicadores_kit" }
|
||||
dependencies = [
|
||||
{ name = "core" },
|
||||
{ name = "pandas" },
|
||||
{ name = "pandera" },
|
||||
{ name = "persistance" },
|
||||
{ name = "plotly" },
|
||||
{ name = "sqlalchemy-utils" },
|
||||
{ name = "sqlmodel" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "core", editable = "../Core" },
|
||||
{ name = "pandas", specifier = "==3.0.6" },
|
||||
{ name = "pandera", specifier = "==0.33.1" },
|
||||
{ name = "persistance", editable = "../Persistance" },
|
||||
{ name = "plotly", specifier = "==7.1.0" },
|
||||
{ name = "sqlalchemy-utils", specifier = "==0.42.1" },
|
||||
{ name = "sqlmodel", specifier = "==0.0.47" },
|
||||
]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [{ name = "pytest", specifier = "==9.1.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "iniconfig"
|
||||
version = "2.3.0"
|
||||
@@ -2145,6 +2173,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "plotly"
|
||||
version = "7.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "narwhals" },
|
||||
{ name = "packaging" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/49/c3/72b369f5ed7701b04ab0ea3dcf83e9bbce71c0b3bc6f07f87568550d09ea/plotly-7.1.0.tar.gz", hash = "sha256:f860166a4a3d78c69cb1f4a15f28a5c8283eade98a282a698f3bb853a449ace5", size = 6689315, upload-time = "2026-09-15T19:21:21.75Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl", hash = "sha256:dbb7fa18afce40d0a8e80d1bf162eceb3faa0ce5a77fe741ad09a74cf78f53f3", size = 9692368, upload-time = "2026-09-15T19:21:18.331Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.6.0"
|
||||
@@ -3064,6 +3105,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/24/a1/bd5e3e99bc9c8863b51ac5b9b03008a7f2da8c6b59695992f5c654e1265b/sqlalchemy-2.0.54-py3-none-any.whl", hash = "sha256:7e33a631ab1474f8fe6b910bd1a07b7b8009c4c78cdd3fb18001b03e3bc2e1d2", size = 1958015, upload-time = "2026-09-15T22:24:22.95Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlalchemy-utils"
|
||||
version = "0.42.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "sqlalchemy" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/7d/eb9565b6a49426552a5bf5c57e7c239c506dc0e4e5315aec6d1e8241dc7c/sqlalchemy_utils-0.42.1.tar.gz", hash = "sha256:881f9cd9e5044dc8f827bccb0425ce2e55490ce44fc0bb848c55cc8ee44cc02e", size = 130789, upload-time = "2025-12-13T03:14:13.591Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/25/7400c18c3ee97914cc99c90007795c00a4ec5b60c853b49db7ba24d11179/sqlalchemy_utils-0.42.1-py3-none-any.whl", hash = "sha256:243cfe1b3a1dae3c74118ae633f1d1e0ed8c787387bc33e556e37c990594ac80", size = 91761, upload-time = "2025-12-13T03:14:15.014Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlglot"
|
||||
version = "30.27.0"
|
||||
@@ -3262,6 +3315,7 @@ dependencies = [
|
||||
{ name = "flask" },
|
||||
{ name = "flask-cors" },
|
||||
{ name = "gunicorn" },
|
||||
{ name = "indicadores-kit" },
|
||||
{ name = "models", extra = ["export"] },
|
||||
{ name = "openpyxl" },
|
||||
{ name = "pandas" },
|
||||
@@ -3295,6 +3349,7 @@ requires-dist = [
|
||||
{ name = "flask", specifier = ">=3.0" },
|
||||
{ name = "flask-cors", specifier = ">=4.0" },
|
||||
{ name = "gunicorn", specifier = ">=23.0" },
|
||||
{ name = "indicadores-kit", editable = "../indicadores_kit" },
|
||||
{ name = "models", extras = ["export"], editable = "../models" },
|
||||
{ name = "openpyxl", specifier = ">=3.1" },
|
||||
{ name = "pandas", specifier = ">=2.0" },
|
||||
|
||||
+14
-21
@@ -6,11 +6,13 @@ 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.reports import reports_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint, in_dev
|
||||
from webapi.blueprints.reportes import reportes_bp
|
||||
from webapi.blueprints.tea import tea_bp
|
||||
from webapi.seguimiento import blueprint_de_seguimiento
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
@@ -69,29 +71,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(reports_bp, url_prefix="/reportes")
|
||||
# The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest.
|
||||
if os.environ.get("DBT_MANIFEST"):
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
app.register_blueprint(reportes_bp, url_prefix="/reportes")
|
||||
# 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
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
from webapi.kpis import kpis_blueprint
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
for domain in ("cacu", "cama"):
|
||||
app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"),
|
||||
Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}")
|
||||
# Patient-level follow-up list and individual risk: only in DEV, with simulated data.
|
||||
if in_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
from persistance import cacu as cacu_repositories
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
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)
|
||||
@@ -4,9 +4,11 @@ import json
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
from indicadores_kit.registry.catalogos import CatalogoInvalido
|
||||
from webapi.imports import audit as import_audit
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
@@ -14,6 +16,7 @@ from webapi.imports.connectors.pdf import PdfConnector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
|
||||
from webapi.imports.services.import_service import (
|
||||
DatabaseRefused,
|
||||
ImportRequestError,
|
||||
@@ -21,7 +24,7 @@ from webapi.imports.services.import_service import (
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.recomputation import DOMAINS, RecomputationQueue
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
@@ -251,11 +254,13 @@ def document_extract():
|
||||
"""Reads the documents, splits them into patient records and extracts
|
||||
the target's fields: `{files: [{name, file_base64}], target,
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||
`files` may be `sql` instead: `{connection details, table|query, column,
|
||||
key_column}`, one document per row (a PDF or plain-text column).
|
||||
Each record comes back with per-field confidence and evidence, conflicts
|
||||
between sources, and the images found on its pages."""
|
||||
body = _json_body()
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
if not body.get("files") and not body.get("sql"):
|
||||
raise BadRequest("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
@@ -302,6 +307,41 @@ def validate():
|
||||
)
|
||||
|
||||
|
||||
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
|
||||
"""For every `document` source in the request (uploaded, or reading a
|
||||
SQL column — same connector either way), writes the captions no known
|
||||
field claimed straight into the silver layer (`catalog_commit_service`),
|
||||
matched or minted against the project's catalog. Best-effort: the
|
||||
structured fields already landed through `commit_sources`, so a failure
|
||||
here is reported, not raised."""
|
||||
reports = []
|
||||
for raw in raw_sources:
|
||||
if not isinstance(raw, dict) or raw.get("source_type") != "document":
|
||||
continue
|
||||
target = raw.get("target") or ""
|
||||
domain = target.split(".", 1)[0]
|
||||
if not domain:
|
||||
continue
|
||||
payload = {**(raw.get("payload") or {}), "target": target}
|
||||
try:
|
||||
connector = build_connector("document", payload)
|
||||
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
|
||||
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError) as exc:
|
||||
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
|
||||
continue
|
||||
reports.append(
|
||||
{
|
||||
"label": raw.get("label"),
|
||||
"domain": result.proyecto,
|
||||
"records_written": result.records_written,
|
||||
"records_without_patient": result.records_without_patient,
|
||||
"fields_matched": result.fields_matched,
|
||||
"fields_minted": result.fields_minted,
|
||||
}
|
||||
)
|
||||
return reports
|
||||
|
||||
|
||||
@imports_bp.post("/commit")
|
||||
def commit():
|
||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||
@@ -321,9 +361,9 @@ def commit():
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
recalculating = False
|
||||
if audit.domain in DOMAINS and any(r.created or r.updated for r in results):
|
||||
if audit.domain and any(r.created or r.updated for r in results):
|
||||
try:
|
||||
RecomputationQueue().request_run(audit.domain)
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
recalculating = True
|
||||
except OSError:
|
||||
# The rows are already saved; failing here would invite a duplicate retry.
|
||||
@@ -333,6 +373,7 @@ def commit():
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": recalculating,
|
||||
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -3,13 +3,13 @@ indicator recomputation. Nothing here returns row-level data."""
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from webapi.imports import audit as import_audit
|
||||
from webapi.recomputation import DOMAINS, RecomputationQueue
|
||||
from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo
|
||||
|
||||
reports_bp = Blueprint("reportes", __name__)
|
||||
reportes_bp = Blueprint("reportes", __name__)
|
||||
|
||||
|
||||
@reports_bp.get("/importaciones")
|
||||
def import_log():
|
||||
@reportes_bp.get("/importaciones")
|
||||
def importaciones():
|
||||
"""Totals per target over every logged attempt, plus the latest attempts
|
||||
(`?limite=50`, newest first; `?dominio=cacu` to filter)."""
|
||||
records = import_audit.default_sink().read()
|
||||
@@ -23,8 +23,8 @@ def import_log():
|
||||
return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]})
|
||||
|
||||
|
||||
@reports_bp.get("/importaciones/descarga")
|
||||
def import_log_download():
|
||||
@reportes_bp.get("/importaciones/descarga")
|
||||
def importaciones_descarga():
|
||||
"""The raw log, one JSON object per line."""
|
||||
sink = import_audit.default_sink()
|
||||
body = sink.path.read_bytes() if sink.path.exists() else b""
|
||||
@@ -35,15 +35,15 @@ def import_log_download():
|
||||
)
|
||||
|
||||
|
||||
@reports_bp.get("/indicadores")
|
||||
def recomputation_status():
|
||||
@reportes_bp.get("/indicadores")
|
||||
def indicadores_estado():
|
||||
"""Per domain: state of the last recomputation and whether another is pending."""
|
||||
return jsonify(RecomputationQueue().status())
|
||||
return jsonify(ColaDeRecalculo().estado())
|
||||
|
||||
|
||||
@reports_bp.post("/indicadores/<dominio>/recalcular")
|
||||
def recompute(dominio: str):
|
||||
if dominio not in DOMAINS:
|
||||
@reportes_bp.post("/indicadores/<dominio>/recalcular")
|
||||
def indicadores_recalcular(dominio: str):
|
||||
if dominio not in DOMINIOS:
|
||||
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
||||
RecomputationQueue().request_run(dominio)
|
||||
ColaDeRecalculo().solicitar(dominio)
|
||||
return jsonify({"pendiente": True}), 202
|
||||
@@ -0,0 +1,7 @@
|
||||
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)
|
||||
@@ -1,329 +0,0 @@
|
||||
"""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],
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
"""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,7 +0,0 @@
|
||||
"""CaCu's follow-up list (`GET /cacu/seguimiento`): one row per patient, with her ASCCP status and her latest studies.
|
||||
|
||||
routes.py the route: validates the request and answers
|
||||
listing.py the list: who enters it, what each row shows
|
||||
status.py the ASCCP status of each patient at a date
|
||||
silver.py, pivot.py, view.py, functions.py the silver queries they read
|
||||
"""
|
||||
@@ -1,53 +0,0 @@
|
||||
# Los estratos que un indicador puede declarar en `extension.estratos`.
|
||||
# Cada uno es una función de SQLAlchemy que devuelve una CTE con
|
||||
# (unidad_id, estrato); el cálculo la cruza con las poblaciones sin
|
||||
# tocarlas (mart/estratos.py).
|
||||
#
|
||||
# expression "modulo.del.kit:funcion"
|
||||
# unidad la unidad de los indicadores a los que sirve (`basis`)
|
||||
# fechas lo que el estrato cruza con dim_fecha, si lo lee
|
||||
# parametros sus reglas: parámetro de la consulta -> clave de parametros.toml (la
|
||||
# función las recibe resueltas y entran a la huella del reporte)
|
||||
# valores sus valores con su etiqueta, en orden, si no salen de otra regla
|
||||
# etiqueta cómo se llama en pantalla (la leyenda, el selector de filtros); sin ella, su nombre
|
||||
#
|
||||
# Sección `comun`: para todos los proyectos; `<proyecto>`: solo ese, y
|
||||
# gana sobre `comun` si se llaman igual.
|
||||
|
||||
[comun.grupo_edad]
|
||||
etiqueta = "Grupo de edad"
|
||||
expression = "comun.estratos.grupo_edad:estrato"
|
||||
unidad = "paciente"
|
||||
fechas = { hechos = ["v_persona.fecha_nacimiento"], parametros = ["periodo_inicio"] }
|
||||
|
||||
# Estatus de seguimiento ASCCP de la paciente (T-24c): `cacu/seguimiento.py`. Sus reglas son de
|
||||
# `parametros.toml` (§2bis) y entran a la huella del reporte. Excluyente y exhaustivo: sin `sin_dato`.
|
||||
[cacu.estatus_seguimiento]
|
||||
etiqueta = "Estatus de seguimiento"
|
||||
expression = "cacu.seguimiento:estrato"
|
||||
unidad = "paciente"
|
||||
valores = [
|
||||
{ valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" },
|
||||
{ valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" },
|
||||
{ valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" },
|
||||
{ valor = "INFO_INSUFICIENTE", etiqueta = "Información insuficiente" },
|
||||
]
|
||||
|
||||
[cacu.estatus_seguimiento.parametros]
|
||||
seguimiento_marco = "cacu.seguimiento.marco"
|
||||
seguimiento_referencia = "cacu.seguimiento.referencia"
|
||||
seguimiento_precedencia = "cacu.seguimiento.precedencia"
|
||||
seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias"
|
||||
seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito"
|
||||
seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito"
|
||||
seguimiento_cie_valoracion = "cacu.diagnostico.cie"
|
||||
seguimiento_especialidades_valoracion = "cacu.diagnostico.especialidades"
|
||||
seguimiento_horizonte_valoracion = "cacu.horizontes.toma_diagnostico_dias"
|
||||
seguimiento_motivos = "cacu.seguimiento.colposcopia.motivos"
|
||||
seguimiento_especialidades_colposcopia = "cacu.seguimiento.colposcopia.especialidades"
|
||||
seguimiento_cie_colposcopia = "cacu.seguimiento.colposcopia.cie"
|
||||
seguimiento_diagnosticos = "cacu.seguimiento.colposcopia.diagnosticos"
|
||||
seguimiento_fuentes_tratamiento = "cacu.seguimiento.tratamiento.fuentes"
|
||||
seguimiento_cie_tratamiento = "cacu.seguimiento.tratamiento.cie"
|
||||
seguimiento_insuficiente = "cacu.seguimiento.insuficiente.regla"
|
||||
seguimiento_especialidades_vigilancia = "cacu.seguimiento.vigilancia.especialidades"
|
||||
@@ -1,100 +0,0 @@
|
||||
"""Lo que cada motor escribe distinto, como una función con una regla por motor.
|
||||
|
||||
SQLAlchemy traduce la sintaxis, no las funciones de fecha. Aquí van las
|
||||
que el kit necesita. Agregar un motor es agregar su regla; ninguna
|
||||
definición cambia. Sin regla para un motor queda la forma neutra, que es
|
||||
la que lee el registro de huellas y no se puede ejecutar. Solo la regla
|
||||
de SQLite se ejecuta en las pruebas (D-S5).
|
||||
"""
|
||||
|
||||
from sqlalchemy import Integer
|
||||
from sqlalchemy.ext.compiler import compiles
|
||||
from sqlalchemy.sql.expression import FunctionElement
|
||||
|
||||
|
||||
class dias_entre(FunctionElement):
|
||||
"""Días enteros de `inicio` a `fin`: `dias_entre(inicio, fin)`."""
|
||||
|
||||
type = Integer()
|
||||
inherit_cache = True
|
||||
|
||||
|
||||
def _partes(elemento, compilador, opciones) -> tuple[str, str]:
|
||||
inicio, fin = list(elemento.clauses)
|
||||
return compilador.process(inicio, **opciones), compilador.process(fin, **opciones)
|
||||
|
||||
|
||||
@compiles(dias_entre)
|
||||
def _neutra(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"dias_entre({inicio}, {fin})"
|
||||
|
||||
|
||||
@compiles(dias_entre, "sqlite")
|
||||
def _sqlite(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(dias_entre, "postgresql")
|
||||
def _postgresql(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))"
|
||||
|
||||
|
||||
@compiles(dias_entre, "mysql", "mariadb")
|
||||
def _mysql(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"DATEDIFF({fin}, {inicio})"
|
||||
|
||||
|
||||
@compiles(dias_entre, "mssql")
|
||||
def _mssql(elemento, compilador, **opciones) -> str:
|
||||
inicio, fin = _partes(elemento, compilador, opciones)
|
||||
return f"DATEDIFF(day, {inicio}, {fin})"
|
||||
|
||||
|
||||
class entero_de_json(FunctionElement):
|
||||
"""Un entero de un objeto JSON guardado como texto: `entero_de_json(columna, "clave")`.
|
||||
|
||||
PostgreSQL no aplica `->>` a `text` y SQL Server no tiene tipo JSON: cada
|
||||
motor lee la clave con su propia función.
|
||||
"""
|
||||
|
||||
type = Integer()
|
||||
inherit_cache = True
|
||||
|
||||
|
||||
def _columna_y_clave(elemento, compilador, opciones) -> tuple[str, str]:
|
||||
columna, clave = list(elemento.clauses)
|
||||
return compilador.process(columna, **opciones), clave.value
|
||||
|
||||
|
||||
@compiles(entero_de_json)
|
||||
def _entero_neutro(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"entero_de_json({columna}, '{clave}')"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "sqlite")
|
||||
def _entero_sqlite(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(json_extract({columna}, '$.{clave}') AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "mysql", "mariadb")
|
||||
def _entero_mysql(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(JSON_UNQUOTE(JSON_EXTRACT({columna}, '$.{clave}')) AS SIGNED)"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "postgresql")
|
||||
def _entero_postgresql(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(CAST({columna} AS JSON) ->> '{clave}' AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(entero_de_json, "mssql")
|
||||
def _entero_mssql(elemento, compilador, **opciones) -> str:
|
||||
columna, clave = _columna_y_clave(elemento, compilador, opciones)
|
||||
return f"CAST(JSON_VALUE({columna}, '$.{clave}') AS INT)"
|
||||
@@ -1,296 +0,0 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, una fila por paciente.
|
||||
|
||||
El contrato es T-24a. Es una consulta al
|
||||
vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada paciente con al menos un
|
||||
estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su
|
||||
grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del
|
||||
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
|
||||
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
|
||||
|
||||
**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta
|
||||
lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal.
|
||||
|
||||
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
|
||||
de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna.
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import hashlib
|
||||
import json
|
||||
import tomllib
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.follow_up.silver import citologias, notas
|
||||
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.view import P
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import valor_de
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
RAIZ = Path(__file__).resolve().parent # `estratos.toml` is next to this module
|
||||
SIN_DATO = "sin_dato"
|
||||
|
||||
|
||||
def leer_estrato(proyecto: str, nombre: str) -> SimpleNamespace:
|
||||
"""The stratum's rules and values in `estratos.toml` (the project's, or the common one)."""
|
||||
with open(RAIZ / "estratos.toml", "rb") as archivo:
|
||||
secciones = tomllib.load(archivo)
|
||||
for seccion in (proyecto, "comun"):
|
||||
if nombre in secciones.get(seccion, {}):
|
||||
entrada = secciones[seccion][nombre]
|
||||
return SimpleNamespace(parametros=entrada.get("parametros", {}), valores=entrada.get("valores", []))
|
||||
raise KeyError(f"No hay estrato {nombre!r} para {proyecto!r} en estratos.toml.")
|
||||
|
||||
|
||||
def ejecutar(sesion: Session, consulta, parametros: dict):
|
||||
"""Runs with the parameters the query names."""
|
||||
nombrados = set(consulta.compile().params)
|
||||
return sesion.execute(consulta, {n: v for n, v in parametros.items() if n in nombrados})
|
||||
|
||||
VENTANAS = (1, 3, 6, 12)
|
||||
FECHAS_DE_ESTUDIO = ("toma", "reporte")
|
||||
ESTUDIOS = ("citologia", "vph")
|
||||
RESULTADOS_MOSTRADOS = ("ultimo", "mas_grave")
|
||||
PAGINA_MAXIMA = 200
|
||||
# Nombre en esta lista -> clave en `parametros.toml`.
|
||||
PARAMETROS_DE_LA_LISTA = {
|
||||
"ventana_meses": "cacu.seguimiento.ventana_meses",
|
||||
"fecha_estudio": "cacu.seguimiento.fecha_estudio",
|
||||
"estudios": "cacu.seguimiento.estudios",
|
||||
"resultado_mostrado": "cacu.seguimiento.resultado_mostrado",
|
||||
"grupos_edad": "cacu.grupos_edad",
|
||||
"catalogo": "cacu.catalogos.citologia",
|
||||
"cie_diagnostico": "cacu.diagnostico.cie",
|
||||
"especialidades_diagnostico": "cacu.diagnostico.especialidades",
|
||||
"cie_antecedente": "cacu.diagnostico.cie_antecedente",
|
||||
"horizonte_dias": "cacu.horizontes.toma_diagnostico_dias",
|
||||
}
|
||||
ESTRATO = "estatus_seguimiento"
|
||||
|
||||
|
||||
class PedidoInvalido(ValueError):
|
||||
"""Un parámetro del pedido fuera de lo que admite el contrato (400)."""
|
||||
|
||||
|
||||
class PaginaFuera(LookupError):
|
||||
"""Una página mayor que la última, habiendo pacientes (404)."""
|
||||
|
||||
|
||||
def seguimiento_de(
|
||||
sesion: Session,
|
||||
*,
|
||||
sal: str,
|
||||
corte: date | None = None,
|
||||
meses: int | None = None,
|
||||
estatus: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
hoy: date | None = None,
|
||||
tablas: TablasKit = TABLAS,
|
||||
) -> dict:
|
||||
"""La lista de seguimiento al `corte`, lista para `json.dumps` (contrato §2).
|
||||
|
||||
`corte` por omisión es `hoy`; en los dos casos se acota a la última fecha con datos de la plata.
|
||||
`meses` por omisión es `cacu.seguimiento.ventana_meses`.
|
||||
|
||||
Raises:
|
||||
PedidoInvalido: `meses`, `estatus`, `page` o `page_size` fuera de rango.
|
||||
PaginaFuera: `page` mayor que la última página, habiendo pacientes.
|
||||
ReglaDesconocida: una regla de `parametros.toml` con una opción que el código no sabe aplicar.
|
||||
"""
|
||||
lista = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in PARAMETROS_DE_LA_LISTA.items()}
|
||||
del_estatus = leer_estrato("cacu", ESTRATO).parametros
|
||||
valores_estatus = {nombre: valor_de(sesion, clave, tablas=tablas) for nombre, clave in del_estatus.items()}
|
||||
_validar_reglas(lista)
|
||||
meses = lista["ventana_meses"] if meses is None else meses
|
||||
if meses not in VENTANAS:
|
||||
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
|
||||
if estatus is not None and estatus not in ESTATUS:
|
||||
raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.")
|
||||
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
|
||||
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
|
||||
|
||||
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
|
||||
desde = _meses_antes(corte, meses) + timedelta(days=1)
|
||||
estatus_de = _estatus_al_corte(sesion, corte, valores_estatus)
|
||||
items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas)
|
||||
if estatus is not None:
|
||||
items = [i for i in items if i["estatus"]["codigo"] == estatus]
|
||||
|
||||
total = len(items)
|
||||
paginas = -(-total // page_size)
|
||||
if total and page > paginas:
|
||||
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
|
||||
etiquetas = _etiquetas_de_estatus()
|
||||
return {
|
||||
"simulado": True,
|
||||
"corte": corte.isoformat(),
|
||||
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
||||
"filtros": {"estatus": estatus},
|
||||
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
|
||||
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
|
||||
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
|
||||
"items": items[(page - 1) * page_size : page * page_size],
|
||||
}
|
||||
|
||||
|
||||
def seudonimo(pac_id: int, sal: str) -> str:
|
||||
"""El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`."""
|
||||
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
|
||||
|
||||
|
||||
def _validar_reglas(lista: dict) -> None:
|
||||
exigir_opcion("cacu.seguimiento.ventana_meses", lista["ventana_meses"], VENTANAS)
|
||||
exigir_opcion("cacu.seguimiento.fecha_estudio", lista["fecha_estudio"], FECHAS_DE_ESTUDIO)
|
||||
exigir_opciones("cacu.seguimiento.estudios", lista["estudios"], ESTUDIOS)
|
||||
exigir_opcion("cacu.seguimiento.resultado_mostrado", lista["resultado_mostrado"], RESULTADOS_MOSTRADOS)
|
||||
|
||||
|
||||
def _acotado(sesion: Session, corte: date, tablas: TablasKit) -> date:
|
||||
"""El corte, sin pasar de la última fecha con datos de la plata (si hay datos)."""
|
||||
ultima = sesion.execute(select(func.max(tablas.Procedimiento.fecha))).scalar()
|
||||
return corte if ultima is None else min(corte, _fecha(ultima))
|
||||
|
||||
|
||||
def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int, str]:
|
||||
cte = estatus_al(P("corte_seguimiento"), reglas_de(valores), incluye_referencia=True)
|
||||
filas = ejecutar(sesion, select(cte.c.pac_id, cte.c.estatus), {**valores, "corte_seguimiento": corte.isoformat()})
|
||||
return {pac_id: estatus for pac_id, estatus in filas}
|
||||
|
||||
|
||||
def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
|
||||
"""Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua."""
|
||||
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
|
||||
en_ventana: dict[int, dict[str, list]] = {}
|
||||
for e in estudios:
|
||||
if desde <= e["fecha"] <= corte:
|
||||
de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []})
|
||||
if "citologia" in lista["estudios"]:
|
||||
de_la_paciente["citologia"].append(e)
|
||||
if "vph" in lista["estudios"] and e["vph"] is not None:
|
||||
de_la_paciente["vph"].append(e)
|
||||
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
|
||||
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
|
||||
notas_de = _notas_por_paciente(sesion, corte)
|
||||
items = []
|
||||
for pac_id, de_la_paciente in en_ventana.items():
|
||||
if not de_la_paciente["citologia"] and not de_la_paciente["vph"]:
|
||||
continue
|
||||
cito = _mostrada(de_la_paciente["citologia"], lista["resultado_mostrado"], gravedad)
|
||||
vph = max(de_la_paciente["vph"], key=lambda e: e["fecha"], default=None)
|
||||
mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]])
|
||||
estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE")
|
||||
items.append({
|
||||
"id_seudonimo": seudonimo(pac_id, sal),
|
||||
"grupo_edad": edades.get(pac_id, SIN_DATO),
|
||||
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
|
||||
"ultima_citologia": None if cito is None else {
|
||||
"fecha": cito["fecha"].isoformat(), "bethesda": cito["resultado"], "calidad": cito["calidad"],
|
||||
},
|
||||
"ultimo_vph": None if vph is None else {
|
||||
"fecha": vph["fecha"].isoformat(), "resultado": vph["vph"],
|
||||
"genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]),
|
||||
},
|
||||
"dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista),
|
||||
"prioridad": None,
|
||||
"_orden": mas_reciente,
|
||||
})
|
||||
items.sort(key=lambda i: i["id_seudonimo"])
|
||||
items.sort(key=lambda i: i.pop("_orden"), reverse=True)
|
||||
return items
|
||||
|
||||
|
||||
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
|
||||
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
|
||||
c = citologias()
|
||||
filas = sesion.execute(select(
|
||||
c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18,
|
||||
)).all()
|
||||
estudios = []
|
||||
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
|
||||
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)
|
||||
conocido = reporte is not None and reporte <= corte
|
||||
fecha = toma if fecha_estudio == "toma" else reporte
|
||||
if fecha is None or toma > corte or (fecha_estudio == "reporte" and not conocido):
|
||||
continue
|
||||
estudios.append({
|
||||
"pac_id": pac_id, "fecha": fecha, "toma": toma, "calidad": calidad,
|
||||
"resultado": resultado if conocido else None,
|
||||
"vph": vph if conocido else None, "genotipo_16_18": genotipo if conocido else None,
|
||||
})
|
||||
return estudios
|
||||
|
||||
|
||||
def _mostrada(citologias_: list[dict], resultado_mostrado: str, gravedad: dict[str, int]) -> dict | None:
|
||||
if not citologias_:
|
||||
return None
|
||||
if resultado_mostrado == "ultimo":
|
||||
return max(citologias_, key=lambda e: e["fecha"])
|
||||
return max(citologias_, key=lambda e: (gravedad.get(e["resultado"], -1), e["fecha"]))
|
||||
|
||||
|
||||
def _grupo_de_edad(sesion: Session, corte: date, cortes, tablas: TablasKit) -> dict[int, str]:
|
||||
"""El grupo de edad de cada paciente con fecha de nacimiento, con la edad cumplida al corte."""
|
||||
grupos = grupos_de_cortes(cortes, tablas=tablas)
|
||||
edades = {}
|
||||
for pac_id, nacimiento in sesion.execute(select(tablas.Persona.pac_id, tablas.Persona.fecha_nacimiento)):
|
||||
if nacimiento is None:
|
||||
continue
|
||||
nacimiento = _fecha(nacimiento)
|
||||
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
|
||||
edades[pac_id] = next((g.etiqueta for g in grupos if g.edad_min <= edad <= g.edad_max), SIN_DATO)
|
||||
return edades
|
||||
|
||||
|
||||
def _notas_por_paciente(sesion: Session, corte: date) -> dict[int, list[tuple[date, str, str]]]:
|
||||
n = notas()
|
||||
de = {}
|
||||
filas = sesion.execute(select(n.c.pac_id, n.c.fecha, n.c.cie_codigo, n.c.especialidad))
|
||||
for pac_id, fecha, cie, especialidad in filas:
|
||||
if fecha is not None and _fecha(fecha) <= corte:
|
||||
de.setdefault(pac_id, []).append((_fecha(fecha), cie, especialidad))
|
||||
return de
|
||||
|
||||
|
||||
def _dias_a_la_valoracion(cito: dict, notas_de: dict, lista: dict) -> int | None:
|
||||
"""Días de la toma a la primera nota que la resuelve, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO; nulo si aún no.
|
||||
|
||||
También nulo si la paciente ya tenía un diagnóstico de cáncer antes de la toma: esa toma no se mide.
|
||||
"""
|
||||
toma, propias = cito["toma"], notas_de.get(cito["pac_id"], [])
|
||||
if any(f < toma and cie in lista["cie_antecedente"] for f, cie, _ in propias):
|
||||
return None
|
||||
dias = [
|
||||
(f - toma).days for f, cie, especialidad in propias
|
||||
if f > toma and (f - toma).days < lista["horizonte_dias"]
|
||||
and cie in lista["cie_diagnostico"] and especialidad in lista["especialidades_diagnostico"]
|
||||
]
|
||||
return min(dias, default=None)
|
||||
|
||||
|
||||
def _reglas_usadas(sesion: Session, claves: list[str], tablas: TablasKit) -> list[dict]:
|
||||
filas = [sesion.get(tablas.DefParametro, clave) for clave in dict.fromkeys(claves)]
|
||||
return [{"clave": f.clave, "valor": json.loads(f.valor), "estado": f.estado} for f in filas if f is not None]
|
||||
|
||||
|
||||
def _etiquetas_de_estatus() -> dict[str, str]:
|
||||
"""Código -> etiqueta, en orden de presentación: los `valores` del estrato en `estratos.toml`."""
|
||||
return {v["valor"]: v["etiqueta"] for v in leer_estrato("cacu", ESTRATO).valores}
|
||||
|
||||
|
||||
def _meses_antes(fecha: date, meses: int) -> date:
|
||||
"""La misma fecha `meses` meses antes; si ese mes es más corto, su último día."""
|
||||
total = fecha.year * 12 + fecha.month - 1 - meses
|
||||
anio, mes = divmod(total, 12)
|
||||
return date(anio, mes + 1, min(fecha.day, calendar.monthrange(anio, mes + 1)[1]))
|
||||
|
||||
|
||||
def _fecha(valor) -> date:
|
||||
"""Una fecha de la base, venga como `date` o como texto ISO (SQLite)."""
|
||||
return valor if isinstance(valor, date) else date.fromisoformat(str(valor)[:10])
|
||||
@@ -1,110 +0,0 @@
|
||||
"""Bloques de consulta sobre la plata de dos tablas (F5, ADR-MD-007).
|
||||
|
||||
Una consulta de indicador no escribe a mano los `JOIN` entre `procedimiento` y
|
||||
`observacion`: pide un **pivote**, una fila por procedimiento de un estudio y una
|
||||
clase, con una columna por resultado del catálogo. El valor de cada columna sale de
|
||||
la columna de `observacion` que le toca según `tipo_valor`:
|
||||
|
||||
codigo valor_id, o el texto tal como llegó si no está en el catálogo (valor_fuente)
|
||||
booleano valor_numerico, como entero (0 o 1)
|
||||
numero valor_numerico
|
||||
fecha valor_fecha
|
||||
texto valor_texto
|
||||
externo valor_texto
|
||||
|
||||
Las fechas salen sin tipo (`sin_tipo`), como en las vistas por tipo, para que los parámetros
|
||||
de periodo se liguen igual que antes. Con eso, el vocabulario de cada proyecto (`<p>/consultas/plata.py`) se rearma como
|
||||
CTE, sin vistas en la base: las dos tablas ya son el estado actual (sin versiones de
|
||||
fila). Solo se arman expresiones de SQLAlchemy; no se lee ni se escribe nada.
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from functools import cache
|
||||
|
||||
from sqlalchemy import Integer, Subquery, and_, case, cast, func, select, type_coerce
|
||||
from sqlalchemy.types import NullType
|
||||
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.tables import PROJECTS, TablasKit, tablas_de
|
||||
|
||||
COLUMNAS_DEL_PROCEDIMIENTO = ("procedimiento_id", "padre_id", "pac_id", "fecha", "fuente_tabla", "fuente_id")
|
||||
|
||||
|
||||
class TipoDeResultadoAmbiguo(ValueError):
|
||||
"""Un mismo `resultado_id` con dos `tipo_valor` distintos en dos catálogos."""
|
||||
|
||||
|
||||
@cache
|
||||
def tipos_de_resultado() -> dict[str, str]:
|
||||
"""`resultado_id` -> `tipo_valor`, de los catálogos de los tres proyectos (deben coincidir donde se repiten)."""
|
||||
tipos: dict[str, str] = {}
|
||||
for proyecto in PROJECTS:
|
||||
for resultado in catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas_de(proyecto)).resultados:
|
||||
previo = tipos.setdefault(resultado.resultado_id, resultado.tipo_valor)
|
||||
if previo != resultado.tipo_valor:
|
||||
raise TipoDeResultadoAmbiguo(f"{resultado.resultado_id}: {previo} y {resultado.tipo_valor}.")
|
||||
return tipos
|
||||
|
||||
|
||||
def sin_tipo(columna):
|
||||
"""Una fecha sin tipo de SQLAlchemy, como las columnas de las vistas por tipo (`consultas.vista.vista`).
|
||||
|
||||
Así un parámetro de la definición (`P("periodo_inicio")`) se liga como lo da el cálculo (texto ISO)
|
||||
y no como `Date`, y las consultas de los indicadores comparan fechas igual que antes (T-18r).
|
||||
"""
|
||||
return type_coerce(columna, NullType()).label(columna.key) if hasattr(columna, "key") else type_coerce(columna, NullType())
|
||||
|
||||
|
||||
def valor(observacion, tipo_valor: str):
|
||||
"""La expresión del valor de una observación según su tipo."""
|
||||
if tipo_valor == "codigo":
|
||||
return func.coalesce(observacion.c.valor_id, observacion.c.valor_fuente)
|
||||
if tipo_valor == "booleano":
|
||||
return cast(observacion.c.valor_numerico, Integer)
|
||||
if tipo_valor == "numero":
|
||||
return observacion.c.valor_numerico
|
||||
if tipo_valor == "fecha":
|
||||
return sin_tipo(observacion.c.valor_fecha)
|
||||
return observacion.c.valor_texto
|
||||
|
||||
|
||||
def pivote(
|
||||
tablas: TablasKit, estudio_id: str, clase: str, resultados: Mapping[str, str | tuple[str, str]] | None = None, *,
|
||||
nombre: str | None = None, columnas: tuple[str, ...] = (),
|
||||
) -> Subquery:
|
||||
"""Una fila por procedimiento del estudio y la clase, con una columna por resultado.
|
||||
|
||||
`resultados`: nombre de la columna -> `resultado_id` (`{"resultado": "citologia.bethesda"}`), o
|
||||
-> `(resultado_id, columna)` para leer una columna de `observacion` en particular
|
||||
(`("nota_medica.especialidad", "valor_id")`: el código, nulo si no se reconoció).
|
||||
Las columnas del procedimiento van siempre: `procedimiento_id`, `padre_id`, `pac_id`,
|
||||
`fecha`, `fuente_tabla` y `fuente_id`, más las de `columnas` (`("orden_numero",)`). Un resultado
|
||||
sin observación da nulo.
|
||||
"""
|
||||
resultados = dict(resultados or {})
|
||||
p = tablas.Procedimiento.__table__
|
||||
o = tablas.Observacion.__table__.alias(f"o_{estudio_id}_{clase}")
|
||||
tipos = tipos_de_resultado()
|
||||
columnas = [sin_tipo(p.c[c]) if c == "fecha" else p.c[c] for c in (*COLUMNAS_DEL_PROCEDIMIENTO, *columnas)]
|
||||
if not resultados:
|
||||
consulta = select(*columnas).where(p.c.estudio_id == estudio_id, p.c.clase == clase)
|
||||
return consulta.subquery(nombre or f"{estudio_id}_{clase}")
|
||||
pares = {columna: r if isinstance(r, tuple) else (r, None) for columna, r in resultados.items()}
|
||||
pivoteadas = [
|
||||
func.max(case((o.c.resultado_id == resultado_id,
|
||||
o.c[especifica] if especifica else valor(o, tipos[resultado_id])))).label(columna)
|
||||
for columna, (resultado_id, especifica) in pares.items()
|
||||
]
|
||||
consulta = (
|
||||
select(*columnas, *pivoteadas)
|
||||
.select_from(p.outerjoin(o, and_(o.c.procedimiento_id == p.c.procedimiento_id,
|
||||
o.c.resultado_id.in_([r for r, _ in pares.values()]))))
|
||||
.where(p.c.estudio_id == estudio_id, p.c.clase == clase)
|
||||
.group_by(*(p.c[c.key] if c.key == "fecha" else c for c in columnas))
|
||||
)
|
||||
return consulta.subquery(nombre or f"{estudio_id}_{clase}")
|
||||
|
||||
|
||||
def hijos_de(padre: Subquery, hijo: Subquery):
|
||||
"""La condición de unión de un procedimiento con sus hijos (el reporte con su toma)."""
|
||||
return hijo.c.padre_id == padre.c.procedimiento_id
|
||||
@@ -1,99 +0,0 @@
|
||||
"""El vocabulario de CaCu sobre la plata de dos tablas (F5, ADR-MD-007): citologías, biopsias, notas y órdenes.
|
||||
|
||||
Lo que leen las familias reescritas, armado con `plata.consultas.pivote` como subconsultas
|
||||
(sin vistas en la base). Los nombres de columna son los del concepto, no los de una tabla
|
||||
por tipo: `fecha_toma`, `resultado`, `grado`. Cada uno lleva `procedimiento_id` y
|
||||
`pac_id`; los que cuelgan de una toma llevan también la de su toma.
|
||||
"""
|
||||
|
||||
from sqlalchemy import Subquery, select
|
||||
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.pivot import hijos_de, pivote
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
|
||||
def citologias(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por citología tomada, con su calidad, su resultado (Bethesda) y su VPH si ya los tiene.
|
||||
|
||||
Lo mismo que la vista por tipo `v_citologia_con_resultado`, desde las dos tablas.
|
||||
"""
|
||||
toma = pivote(tablas, "citologia", "toma", {"calidad_muestra": "citologia.calidad_muestra"},
|
||||
columnas=("orden_numero",), nombre="toma_citologia")
|
||||
reporte = pivote(tablas, "citologia", "reporte", {"resultado": "citologia.bethesda"}, nombre="reporte_citologia")
|
||||
vph = pivote(tablas, "vph", "reporte", {
|
||||
"vph": "vph.resultado", "genotipo_16_18": "vph.genotipo_16_18",
|
||||
"genotipo_16": "vph.genotipo_16", "genotipo_18": "vph.genotipo_18",
|
||||
}, nombre="reporte_vph")
|
||||
return select(
|
||||
toma.c.procedimiento_id, toma.c.fuente_tabla, toma.c.fuente_id, toma.c.pac_id,
|
||||
toma.c.fecha.label("fecha_toma"), toma.c.calidad_muestra, toma.c.orden_numero,
|
||||
reporte.c.fecha.label("fecha_reporte"), reporte.c.resultado,
|
||||
vph.c.vph, vph.c.genotipo_16_18, vph.c.genotipo_16, vph.c.genotipo_18,
|
||||
).select_from(
|
||||
toma.outerjoin(reporte, hijos_de(toma, reporte)).outerjoin(vph, hijos_de(toma, vph))
|
||||
).subquery("citologias")
|
||||
|
||||
|
||||
def biopsias(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por biopsia reportada, con su grado, su solicitud y la citología que la originó (si se encontró).
|
||||
|
||||
Desde T-22h la biopsia es una orden (`biopsia`, `orden`: la solicitud, con su fecha y su número de orden)
|
||||
y su reporte, una hija de ella: la toma queda dos niveles arriba (toma, orden, reporte).
|
||||
"""
|
||||
reporte = pivote(tablas, "biopsia", "reporte", {"grado": "biopsia.grado"}, nombre="reporte_biopsia")
|
||||
orden = pivote(tablas, "biopsia", "orden", columnas=("orden_numero",), nombre="orden_biopsia")
|
||||
toma = pivote(tablas, "citologia", "toma", nombre="toma_de_la_biopsia")
|
||||
return select(
|
||||
reporte.c.procedimiento_id, reporte.c.fuente_tabla, reporte.c.fuente_id, reporte.c.pac_id,
|
||||
reporte.c.fecha.label("fecha_reporte"), reporte.c.grado, orden.c.fecha.label("fecha_solicitud"), orden.c.orden_numero,
|
||||
toma.c.procedimiento_id.label("toma_id"), toma.c.pac_id.label("toma_pac_id"), toma.c.fecha.label("fecha_toma"),
|
||||
).select_from(
|
||||
reporte.outerjoin(orden, hijos_de(orden, reporte)).outerjoin(toma, hijos_de(toma, orden))
|
||||
).subquery("biopsias")
|
||||
|
||||
|
||||
def notas(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por nota médica: su fecha, su CIE-10 y la especialidad que la escribió (código; nulo si no se reconoció)."""
|
||||
nota = pivote(tablas, "nota_medica", "encuentro", {
|
||||
"cie_codigo": "nota_medica.diagnostico",
|
||||
"especialidad": ("nota_medica.especialidad", "valor_id"),
|
||||
"especialidad_fuente": ("nota_medica.especialidad", "valor_fuente"),
|
||||
}, nombre="nota_medica")
|
||||
return select(
|
||||
nota.c.procedimiento_id, nota.c.fuente_tabla, nota.c.fuente_id, nota.c.pac_id, nota.c.fecha,
|
||||
nota.c.cie_codigo, nota.c.especialidad, nota.c.especialidad_fuente,
|
||||
).subquery("notas")
|
||||
|
||||
|
||||
def notas_con_textos(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Las notas con su motivo de consulta y su diagnóstico en texto (tal como llegan) y su identificador del hospital.
|
||||
|
||||
Aparte de `notas` para no mover la huella de las definiciones que ya la leen (T-24b, T-24c).
|
||||
"""
|
||||
nota = pivote(tablas, "nota_medica", "encuentro", {
|
||||
"cie_codigo": "nota_medica.diagnostico",
|
||||
"especialidad": ("nota_medica.especialidad", "valor_id"),
|
||||
"motivo": "nota_medica.motivo",
|
||||
"diagnostico_texto": "nota_medica.diagnostico_texto",
|
||||
}, columnas=("id_hospital",), nombre="nota_con_textos")
|
||||
return select(
|
||||
nota.c.procedimiento_id, nota.c.pac_id, nota.c.fecha, nota.c.cie_codigo, nota.c.especialidad,
|
||||
nota.c.motivo, nota.c.diagnostico_texto, nota.c.id_hospital,
|
||||
).subquery("notas_con_textos")
|
||||
|
||||
|
||||
def ordenes_de_biopsia(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por biopsia solicitada (la orden, con o sin reporte; T-22h): de quién y la fecha de la solicitud."""
|
||||
orden = pivote(tablas, "biopsia", "orden", nombre="orden_de_biopsia")
|
||||
return select(orden.c.procedimiento_id, orden.c.pac_id, orden.c.fecha).subquery("ordenes_de_biopsia")
|
||||
|
||||
|
||||
def tomas_con_especialidad(tablas: TablasKit = TABLAS) -> Subquery:
|
||||
"""Una fila por citología tomada, con la especialidad de la orden de la que cuelga (nula si no tiene o no se reconoce)."""
|
||||
toma = pivote(tablas, "citologia", "toma", nombre="toma_con_especialidad")
|
||||
orden = pivote(tablas, "citologia", "orden", {"especialidad": ("orden.especialidad", "valor_id")},
|
||||
nombre="orden_de_la_toma")
|
||||
return select(toma.c.procedimiento_id, toma.c.pac_id, toma.c.fecha, orden.c.especialidad).select_from(
|
||||
toma.outerjoin(orden, hijos_de(orden, toma))
|
||||
).subquery("tomas_con_especialidad")
|
||||
@@ -1,281 +0,0 @@
|
||||
"""El estatus de seguimiento ASCCP de cada paciente a una fecha (T-24c; plan de seguimiento, §5.2).
|
||||
|
||||
`estatus_al(referencia, reglas)` es la única regla: una CTE `(pac_id, estatus)` con un renglón
|
||||
por persona. La usan el estrato `estatus_seguimiento` (`estrato`, a la referencia de cada
|
||||
reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las cohortes (a su
|
||||
fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo
|
||||
pasado no cambia cuando la paciente avanza.
|
||||
|
||||
POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia
|
||||
POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si
|
||||
es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de
|
||||
valoración (la nota que resuelve una toma, como en CACU_DIAS_TOMA_DIAGNOSTICO); una
|
||||
orden o una biopsia, por regla, si es del mismo día que una nota de colposcopia (la
|
||||
colposcopia es la madre de la biopsia)
|
||||
INFO_INSUFICIENTE la historia no alcanza (`cacu.seguimiento.insuficiente.regla`); también el resto
|
||||
PRE_COLPOSCOPIA ninguna de las anteriores y, si se conoce la especialidad de sus citologías,
|
||||
alguna es de vigilancia
|
||||
|
||||
Ninguna regla está escrita aquí: todas son de `parametros.toml` (`cacu.seguimiento.*`, §2bis); qué
|
||||
parámetro de la consulta es qué clave lo declara `estratos.toml` (`[cacu.estatus_seguimiento.parametros]`),
|
||||
y llegan como `reglas`. Las listas (CIE-10, especialidades, evidencias) van ligadas como
|
||||
parámetros (S-K76); los textos del motivo y del diagnóstico se comparan por contención, en
|
||||
mayúsculas y sin acentos; la precedencia, la referencia y la regla de insuficiente arman la
|
||||
consulta. Una opción que el código no sabe aplicar falla con `ReglaDesconocida`.
|
||||
"""
|
||||
|
||||
import unicodedata
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import (
|
||||
CTE, ColumnElement, and_, bindparam, case, exists, func, literal, literal_column, or_, select, union_all,
|
||||
)
|
||||
|
||||
from webapi.follow_up.silver import biopsias, notas_con_textos, ordenes_de_biopsia, tomas_con_especialidad
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.functions import dias_entre
|
||||
from webapi.follow_up.view import P, vista
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
|
||||
RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3)
|
||||
MARCOS = ("estatus", "ronda")
|
||||
REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte
|
||||
EVIDENCIAS = ("motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia")
|
||||
FUENTES_DE_TRATAMIENTO = ("nota_posterior_a_colposcopia",)
|
||||
REGLAS_DE_INSUFICIENTE = ("inicio_datos_posterior_a_alta", "sin_alta_registrada", "ambos", "nunca")
|
||||
REQUISITOS_DE_COLPOSCOPIA = ("valoracion_previa", "ninguno")
|
||||
REQUISITOS_DE_BIOPSIA = ("mismo_dia_que_colposcopia", "ninguno")
|
||||
|
||||
V_PERSONA = vista("v_persona", "pac_id")
|
||||
SIN_ACENTO = {"Á": "A", "É": "E", "Í": "I", "Ó": "O", "Ú": "U", "Ü": "U", "á": "a", "é": "e", "í": "i", "ó": "o",
|
||||
"ú": "u", "ü": "u"} # fmt: skip
|
||||
|
||||
|
||||
class ReglaDesconocida(ValueError):
|
||||
"""Una regla de `cacu.seguimiento.*` con una opción que el código no sabe aplicar."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reglas:
|
||||
"""Las reglas que dan forma a la consulta, ya validadas. Las listas no van aquí: se ligan al ejecutar."""
|
||||
|
||||
referencia: str # el parámetro del reporte: `periodo_inicio` o `fecha_corte`
|
||||
precedencia: tuple[str, ...]
|
||||
motivos: tuple[str, ...] # normalizados
|
||||
diagnosticos: tuple[str, ...] # normalizados
|
||||
insuficiente: str
|
||||
valoracion_previa: bool # una nota de colposcopia cuenta solo después de una cita de valoración
|
||||
biopsia_mismo_dia: bool # la orden y la biopsia cuentan solo el día de una nota de colposcopia
|
||||
|
||||
|
||||
def reglas_de(valores: Mapping) -> Reglas:
|
||||
"""Valida las reglas (`{parámetro de la consulta: valor}`, los de `estratos.toml`) contra las opciones admitidas."""
|
||||
exigir_opciones("cacu.seguimiento.marco", valores["seguimiento_marco"], MARCOS)
|
||||
if "estatus" not in valores["seguimiento_marco"]:
|
||||
raise ReglaDesconocida("cacu.seguimiento.marco no incluye «estatus»: el estrato no se publica.")
|
||||
if "ronda" in valores["seguimiento_marco"]:
|
||||
raise ReglaDesconocida("cacu.seguimiento.marco: «ronda» (UE) todavía no se sabe aplicar.")
|
||||
exigir_opcion("cacu.seguimiento.referencia", valores["seguimiento_referencia"], tuple(REFERENCIAS))
|
||||
precedencia = tuple(valores["seguimiento_precedencia"])
|
||||
if sorted(precedencia) != sorted(ESTATUS):
|
||||
raise ReglaDesconocida(
|
||||
f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; "
|
||||
f"llegó {precedencia}."
|
||||
)
|
||||
exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS)
|
||||
exigir_opciones(
|
||||
"cacu.seguimiento.tratamiento.fuentes", valores["seguimiento_fuentes_tratamiento"], FUENTES_DE_TRATAMIENTO
|
||||
)
|
||||
exigir_opcion("cacu.seguimiento.insuficiente.regla", valores["seguimiento_insuficiente"], REGLAS_DE_INSUFICIENTE)
|
||||
exigir_opcion("cacu.seguimiento.colposcopia.requisito", valores["seguimiento_requisito"], REQUISITOS_DE_COLPOSCOPIA)
|
||||
exigir_opcion(
|
||||
"cacu.seguimiento.colposcopia.biopsia_requisito",
|
||||
valores["seguimiento_biopsia_requisito"],
|
||||
REQUISITOS_DE_BIOPSIA,
|
||||
)
|
||||
return Reglas(
|
||||
referencia=REFERENCIAS[valores["seguimiento_referencia"]],
|
||||
precedencia=precedencia,
|
||||
motivos=tuple(normalizado(m) for m in valores["seguimiento_motivos"]),
|
||||
diagnosticos=tuple(normalizado(d) for d in valores["seguimiento_diagnosticos"]),
|
||||
insuficiente=valores["seguimiento_insuficiente"],
|
||||
valoracion_previa=valores["seguimiento_requisito"] == "valoracion_previa",
|
||||
biopsia_mismo_dia=valores["seguimiento_biopsia_requisito"] == "mismo_dia_que_colposcopia",
|
||||
)
|
||||
|
||||
|
||||
def estrato(valores: Mapping) -> CTE:
|
||||
"""El estrato `estatus_seguimiento` (`estratos.toml`): `(unidad_id, estrato)`, a la referencia del reporte."""
|
||||
reglas = reglas_de(valores)
|
||||
estatus = estatus_al(P(reglas.referencia), reglas, incluye_referencia=reglas.referencia == "fecha_corte")
|
||||
return select(estatus.c.pac_id.label("unidad_id"), estatus.c.estatus.label("estrato")).cte(
|
||||
"estrato_estatus_seguimiento"
|
||||
)
|
||||
|
||||
|
||||
def estatus_al(
|
||||
referencia: ColumnElement, reglas: Reglas, *, incluye_referencia: bool = False, tablas: TablasKit = TABLAS
|
||||
) -> CTE:
|
||||
"""La CTE `(pac_id, estatus)`: un renglón por persona, con lo ocurrido antes de `referencia`.
|
||||
|
||||
`referencia` es una fecha de SQL (un parámetro: `P("periodo_inicio")`, `P("corte")`). Con
|
||||
`incluye_referencia`, cuenta también lo de ese día (un corte); sin él, solo lo anterior (el inicio
|
||||
de un periodo). Los parámetros `seguimiento_*` de las listas se ligan al ejecutar.
|
||||
"""
|
||||
|
||||
def antes(fecha) -> ColumnElement:
|
||||
return fecha <= referencia if incluye_referencia else fecha < referencia
|
||||
|
||||
nota, orden, reporte, toma = (
|
||||
notas_con_textos(tablas), ordenes_de_biopsia(tablas), biopsias(tablas), tomas_con_especialidad(tablas)
|
||||
)
|
||||
# La cita de valoración: la nota que resuelve una toma, con las reglas de CACU_DIAS_TOMA_DIAGNOSTICO.
|
||||
valoracion = (
|
||||
select(nota.c.pac_id, func.min(nota.c.fecha).label("primera"))
|
||||
.select_from(nota.join(toma, toma.c.pac_id == nota.c.pac_id))
|
||||
.where(
|
||||
antes(nota.c.fecha),
|
||||
nota.c.fecha > toma.c.fecha,
|
||||
dias_entre(toma.c.fecha, nota.c.fecha) < P("seguimiento_horizonte_valoracion"),
|
||||
nota.c.cie_codigo.in_(P("seguimiento_cie_valoracion", lista=True)),
|
||||
nota.c.especialidad.in_(P("seguimiento_especialidades_valoracion", lista=True)),
|
||||
)
|
||||
.group_by(nota.c.pac_id)
|
||||
.cte("seguimiento_valoracion")
|
||||
)
|
||||
# Una nota de colposcopia: de su especialidad y, por regla, posterior a la primera valoración.
|
||||
de_colposcopia = and_(
|
||||
antes(nota.c.fecha),
|
||||
nota.c.especialidad.in_(P("seguimiento_especialidades_colposcopia", lista=True)),
|
||||
nota.c.fecha > valoracion.c.primera if reglas.valoracion_previa else _siempre(),
|
||||
)
|
||||
con_valoracion = nota.outerjoin(valoracion, valoracion.c.pac_id == nota.c.pac_id)
|
||||
# Los días con una nota de colposcopia válida: la orden de biopsia se expide ese día (su madre).
|
||||
visitas = select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(de_colposcopia).cte(
|
||||
"seguimiento_visitas_de_colposcopia"
|
||||
)
|
||||
|
||||
def de_una_visita(pac_id, fecha) -> ColumnElement:
|
||||
if not reglas.biopsia_mismo_dia:
|
||||
return _siempre()
|
||||
return exists().where(visitas.c.pac_id == pac_id, visitas.c.fecha == fecha)
|
||||
|
||||
evidencias = union_all(
|
||||
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
|
||||
_habilitada("motivo"), de_colposcopia, _contiene(nota.c.motivo, reglas.motivos, "motivo")
|
||||
),
|
||||
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
|
||||
_habilitada("cie"), de_colposcopia, nota.c.cie_codigo.in_(P("seguimiento_cie_colposcopia", lista=True)),
|
||||
),
|
||||
select(nota.c.pac_id, nota.c.fecha).select_from(con_valoracion).where(
|
||||
_habilitada("diagnostico_texto"), de_colposcopia,
|
||||
_contiene(nota.c.diagnostico_texto, reglas.diagnosticos, "diagnostico"),
|
||||
),
|
||||
select(orden.c.pac_id, orden.c.fecha).where(
|
||||
_habilitada("orden_biopsia"), antes(orden.c.fecha), de_una_visita(orden.c.pac_id, orden.c.fecha)
|
||||
),
|
||||
select(reporte.c.pac_id, reporte.c.fecha_reporte.label("fecha")).where(
|
||||
_habilitada("biopsia"), antes(reporte.c.fecha_reporte),
|
||||
de_una_visita(reporte.c.pac_id, reporte.c.fecha_solicitud),
|
||||
),
|
||||
).subquery("evidencias_de_colposcopia")
|
||||
colposcopia = (
|
||||
select(evidencias.c.pac_id, func.min(evidencias.c.fecha).label("primera"))
|
||||
.group_by(evidencias.c.pac_id)
|
||||
.cte("seguimiento_colposcopia")
|
||||
)
|
||||
tratamiento = (
|
||||
select(nota.c.pac_id)
|
||||
.distinct()
|
||||
.select_from(nota.join(colposcopia, colposcopia.c.pac_id == nota.c.pac_id))
|
||||
.where(
|
||||
antes(nota.c.fecha),
|
||||
nota.c.fecha > colposcopia.c.primera,
|
||||
nota.c.cie_codigo.in_(P("seguimiento_cie_tratamiento", lista=True)),
|
||||
)
|
||||
.cte("seguimiento_tratamiento")
|
||||
)
|
||||
# Fuera de vigilancia: todas sus citologías tienen especialidad conocida y ninguna es de vigilancia.
|
||||
de_vigilancia = or_(
|
||||
toma.c.especialidad.is_(None), toma.c.especialidad.in_(P("seguimiento_especialidades_vigilancia", lista=True))
|
||||
)
|
||||
fuera_de_vigilancia = (
|
||||
select(toma.c.pac_id)
|
||||
.where(antes(toma.c.fecha))
|
||||
.group_by(toma.c.pac_id)
|
||||
.having(func.sum(case((de_vigilancia, 1), else_=0)) == 0)
|
||||
.cte("seguimiento_fuera_de_vigilancia")
|
||||
)
|
||||
persona = V_PERSONA
|
||||
cumple = {
|
||||
"POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None),
|
||||
"POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None),
|
||||
"INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente),
|
||||
"PRE_COLPOSCOPIA": fuera_de_vigilancia.c.pac_id.is_(None),
|
||||
}
|
||||
estatus = case(*((cumple[e], literal(e)) for e in reglas.precedencia), else_=literal(RESTO))
|
||||
return (
|
||||
select(persona.c.pac_id, estatus.label("estatus"))
|
||||
.select_from(
|
||||
persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id)
|
||||
)
|
||||
.cte("seguimiento_estatus")
|
||||
)
|
||||
|
||||
|
||||
def normalizado(texto: str) -> str:
|
||||
"""Un texto para comparar: sin espacios al borde, sin acentos y en mayúsculas (la Ñ se queda)."""
|
||||
return "".join(SIN_ACENTO.get(c, c) for c in unicodedata.normalize("NFC", texto.strip())).upper()
|
||||
|
||||
|
||||
def _normalizado_sql(columna: ColumnElement) -> ColumnElement:
|
||||
"""`normalizado` en SQL: sin acentos (antes de `upper`, que en SQLite solo sabe ASCII) y en mayúsculas."""
|
||||
for con, sin in SIN_ACENTO.items():
|
||||
columna = func.replace(columna, con, sin)
|
||||
return func.upper(columna)
|
||||
|
||||
|
||||
def _contiene(columna: ColumnElement, textos: tuple[str, ...], nombre: str) -> ColumnElement:
|
||||
"""La columna, normalizada, contiene alguno de los textos (ya normalizados). Sin textos, nunca."""
|
||||
if not textos:
|
||||
return _nunca()
|
||||
normal = _normalizado_sql(columna)
|
||||
return or_(*(normal.contains(bindparam(f"seguimiento_{nombre}_{i}", t)) for i, t in enumerate(textos)))
|
||||
|
||||
|
||||
def _habilitada(evidencia: str) -> ColumnElement:
|
||||
"""La evidencia está en `cacu.seguimiento.colposcopia.evidencias` (ligada al ejecutar)."""
|
||||
return literal(evidencia).in_(P("seguimiento_evidencias", lista=True))
|
||||
|
||||
|
||||
def _insuficiente(regla: str) -> ColumnElement:
|
||||
"""La regla de historia insuficiente. Hoy no hay fecha de alta (usuario, 2026-10-22): se asume posterior al
|
||||
inicio de los datos, así que `inicio_datos_posterior_a_alta` no marca a nadie y `sin_alta_registrada`, a todas."""
|
||||
return _siempre() if regla in ("sin_alta_registrada", "ambos") else _nunca()
|
||||
|
||||
|
||||
def _siempre() -> ColumnElement:
|
||||
"""Una condición verdadera. No `true()`: SQL Server la escribe como `1`, que no es condición."""
|
||||
return literal_column("1") == literal_column("1")
|
||||
|
||||
|
||||
def _nunca() -> ColumnElement:
|
||||
"""Una condición falsa (ver `_siempre`)."""
|
||||
return literal_column("1") == literal_column("0")
|
||||
|
||||
|
||||
def exigir_opcion(clave: str, valor, admitidas: tuple) -> None:
|
||||
"""La regla `clave` vale una de las opciones que el código sabe aplicar; si no, `ReglaDesconocida`."""
|
||||
if valor not in admitidas:
|
||||
raise ReglaDesconocida(f"{clave} = {valor!r}: el código sabe aplicar {list(admitidas)}.")
|
||||
|
||||
|
||||
def exigir_opciones(clave: str, valores, admitidas: tuple) -> None:
|
||||
"""Cada valor de la regla `clave` es una opción que el código sabe aplicar; si no, `ReglaDesconocida`."""
|
||||
desconocidas = [v for v in valores if v not in admitidas]
|
||||
if desconocidas:
|
||||
raise ReglaDesconocida(f"{clave}: {desconocidas} no se saben aplicar; el código sabe {list(admitidas)}.")
|
||||
@@ -1,26 +0,0 @@
|
||||
"""De dónde lee una definición: una vista o una tabla por su nombre, y sus parámetros.
|
||||
|
||||
Una definición de indicador lee la plata genérica por su vocabulario
|
||||
(`<proyecto>/consultas/plata.py`) y las tablas de apoyo (`dim_fecha`,
|
||||
`dim_grupo_edad`, `v_persona`) por `vista`. Desde F6 (ADR-MD-009) no hay
|
||||
tablas de hechos por tipo ni sus vistas `v_<tabla>_actual`.
|
||||
|
||||
Las consultas son objetos de SQLAlchemy: el SQL lo escribe SQLAlchemy
|
||||
para el motor de la sesión.
|
||||
"""
|
||||
|
||||
from sqlalchemy import BindParameter, FromClause, bindparam, column, table
|
||||
|
||||
|
||||
def vista(nombre: str, *columnas: str) -> FromClause:
|
||||
"""Una vista o una tabla por su nombre y sus columnas, para las que no salen de un modelo."""
|
||||
return table(nombre, *(column(nombre_columna) for nombre_columna in columnas))
|
||||
|
||||
|
||||
def P(nombre: str, *, lista: bool = False) -> BindParameter:
|
||||
"""Un parámetro de una definición. `lista`: su valor es una lista y va en un `IN`.
|
||||
|
||||
El valor no entra al SQL: se liga al ejecutar, así que la definición
|
||||
no cambia cuando cambia una regla del TOML (S-K76).
|
||||
"""
|
||||
return bindparam(nombre, expanding=lista)
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Aggregate log of every import attempt (validations and commits).
|
||||
|
||||
Each attempt becomes one JSON line in `import_log.jsonl` under
|
||||
Each attempt becomes one JSON line in `importaciones.jsonl` under
|
||||
`WEBAPI_REPORT_DIR`. A record only carries counts, field names, source
|
||||
column names and value *shapes* ("9999-99-99" for a date in an unexpected
|
||||
format): never a row, a file name, a connection string or an identifier.
|
||||
|
||||
@@ -12,6 +12,7 @@ from extraction.segmentation import SEGMENTERS
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
@@ -48,16 +49,49 @@ class _ResultCache:
|
||||
_CACHE = _ResultCache()
|
||||
|
||||
|
||||
def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
|
||||
"""One `(name, bytes)` per row of a SQL source (connected the same way
|
||||
`SqlConnector` is): `column` is the field bundle (a `varbinary(max)`
|
||||
PDF, or already a plain string — `read_document` reads either), and
|
||||
`key_column` names the row (a patient or study id) for tracing. Any
|
||||
column type `SqlConnector` can read works; it's not limited to PDFs."""
|
||||
column = sql.get("column")
|
||||
if not column:
|
||||
raise ConnectorError("falta column")
|
||||
if not sql.get("query") and not sql.get("table"):
|
||||
raise ConnectorError("falta table o query")
|
||||
key_column = sql.get("key_column") or column
|
||||
if key_column == column:
|
||||
raise ConnectorError("key_column debe ser distinta de column")
|
||||
connector = SqlConnector.connect(sql)
|
||||
connector = (
|
||||
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
|
||||
)
|
||||
files = []
|
||||
for row in connector.read_rows({column: "contenido", key_column: "clave"}):
|
||||
raw = row.get("contenido")
|
||||
if raw is None:
|
||||
continue
|
||||
name = str(row.get("clave", len(files) + 1))
|
||||
files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8")))
|
||||
return files
|
||||
|
||||
|
||||
@register_connector
|
||||
class DocumentConnector(DataFrameConnector):
|
||||
"""Clinical documents that are not tables: one report per patient,
|
||||
several pages per patient, many patients per file, scans, free text.
|
||||
several pages per patient, many patients per file, scans, free text —
|
||||
uploaded directly, or read one row at a time from a SQL source whose
|
||||
`payload` carries `sql` (a connection plus `table`/`query`, `column`
|
||||
and `key_column`) instead of `files`; either way, every row's content
|
||||
reaches the same extraction, PDF, image or plain text alike.
|
||||
|
||||
Every file is read page by page (text layer or OCR), split into
|
||||
per-patient records, and the target entity's fields are extracted from
|
||||
labels and narrative text. Records of the same patient found in other
|
||||
pages or files are merged. Each row also carries the record's pages as
|
||||
a PDF (`documento`), mappable to the entity's file column.
|
||||
Every file is read page by page (text layer or OCR; plain text as its
|
||||
own lines), split into per-patient records, and the target entity's
|
||||
fields are extracted from labels and narrative text. Records of the
|
||||
same patient found in other pages or files — or rows — are merged.
|
||||
Each row also carries the record's pages as a PDF (`documento`),
|
||||
mappable to the entity's file column, when the source produced one.
|
||||
|
||||
Corrections made while reviewing travel in `overrides`
|
||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||
@@ -65,7 +99,7 @@ class DocumentConnector(DataFrameConnector):
|
||||
|
||||
kind = "document"
|
||||
label = "Documentos clínicos"
|
||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
||||
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
|
||||
category = "document"
|
||||
icon = "document_scanner"
|
||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||
@@ -103,7 +137,12 @@ class DocumentConnector(DataFrameConnector):
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
if payload.get("sql"):
|
||||
files = _files_from_sql(payload["sql"])
|
||||
else:
|
||||
files = [
|
||||
(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)
|
||||
]
|
||||
return cls(
|
||||
files,
|
||||
target=payload["target"],
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Matching OCR-discovered captions against a project's catalog, and
|
||||
minting new catalog entries when nothing matches well enough.
|
||||
|
||||
`discover_captions` (Extraction) finds `caption: value` lines no known
|
||||
`FieldSpec` already explains. For each one, this module decides whether an
|
||||
existing `resultado_id` means the same thing closely enough to reuse
|
||||
(`rapidfuzz`, tolerant of how a hospital's own report wording differs from
|
||||
the catalog's own), or whether it's a field the catalog doesn't have yet —
|
||||
in which case it's added (`add_resultado`), never silently dropped.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
from rapidfuzz import fuzz, process
|
||||
|
||||
from extraction.nlp import DiscoveredField
|
||||
from extraction.nlp.text import find_date, fold
|
||||
from indicadores_kit.plata.procedimiento import valor_de_observacion
|
||||
from indicadores_kit.registry.catalogos import Catalogo, add_resultado
|
||||
|
||||
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
|
||||
# two short, unrelated captions that merely share common words ("de", "del")
|
||||
# too high for this use (two genuinely different captions can clear 80).
|
||||
# Lower than `extraction.nlp.extractors.FUZZY_LABEL_THRESHOLD` (0-100 scale
|
||||
# here, that one 0-1): a caption is free text, not a single known label
|
||||
# tolerating only OCR noise, so it varies more from the catalog's wording.
|
||||
CAPTION_MATCH_THRESHOLD = 80.0
|
||||
CAPTION_SCORER = fuzz.token_sort_ratio
|
||||
FALLBACK_ESTUDIO_ID = "documento_externo"
|
||||
FALLBACK_ESTUDIO_ETIQUETA = "Documento externo"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchedField:
|
||||
"""One discovered caption, resolved to a `resultado_id` (existing or
|
||||
just minted) with its value already shaped for `observacion`."""
|
||||
|
||||
resultado_id: str
|
||||
is_new: bool
|
||||
observacion: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _NewResultado:
|
||||
resultado_id: str
|
||||
tipo_valor: str
|
||||
|
||||
|
||||
def match_or_mint(
|
||||
discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None
|
||||
) -> list[MatchedField]:
|
||||
"""One `MatchedField` per discovered caption, in order.
|
||||
|
||||
`estudio_id`, when the caller already knows it (the row's own
|
||||
study-type column, resolved through `codigos_hospital`), scopes which
|
||||
resultados are tried first and which estudio a minted field joins;
|
||||
without it, every resultado in the catalog is a candidate and a new
|
||||
field's estudio is guessed the same way, or falls back to
|
||||
`documento_externo`.
|
||||
"""
|
||||
labels = _resultado_labels(catalogo, estudio_id)
|
||||
valid_codes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
by_resultado_id = {r.resultado_id: r for r in catalogo.resultados}
|
||||
resolved = []
|
||||
for field in discovered:
|
||||
found = _best_match(field.caption, labels)
|
||||
if found is not None:
|
||||
resultado, is_new = by_resultado_id[found], False
|
||||
else:
|
||||
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
|
||||
is_new = True
|
||||
value = _coerce_value(field.value, resultado.tipo_valor)
|
||||
observacion = valor_de_observacion(
|
||||
value,
|
||||
field.value,
|
||||
tipo_valor=resultado.tipo_valor,
|
||||
en_catalogo=lambda v, r=resultado.resultado_id: (r, v) in valid_codes,
|
||||
)
|
||||
resolved.append(MatchedField(resultado.resultado_id, is_new, observacion))
|
||||
return resolved
|
||||
|
||||
|
||||
def _resultado_labels(catalogo: Catalogo, estudio_id: str | None) -> dict[str, str]:
|
||||
resultados = catalogo.resultados
|
||||
if estudio_id is not None:
|
||||
of_estudio = [r for r in resultados if r.estudio_id == estudio_id]
|
||||
if of_estudio:
|
||||
resultados = of_estudio
|
||||
return {r.resultado_id: fold(r.etiqueta) for r in resultados}
|
||||
|
||||
|
||||
def _best_match(caption: str, labels: dict[str, str]) -> str | None:
|
||||
if not labels:
|
||||
return None
|
||||
found = process.extractOne(fold(caption), labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||
return found[2] if found is not None else None
|
||||
|
||||
|
||||
def _mint(field: DiscoveredField, *, proyecto: str, estudio_id: str | None, catalogo: Catalogo) -> _NewResultado:
|
||||
estudio = estudio_id
|
||||
estudio_etiqueta = None
|
||||
if estudio is None:
|
||||
estudio_labels = {e.estudio_id: fold(e.etiqueta) for e in catalogo.estudios}
|
||||
found = process.extractOne(fold(field.caption), estudio_labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||
estudio = found[2] if found is not None else None
|
||||
if estudio is None:
|
||||
estudio, estudio_etiqueta = FALLBACK_ESTUDIO_ID, FALLBACK_ESTUDIO_ETIQUETA
|
||||
tipo_valor = _infer_tipo_valor(field.value)
|
||||
resultado_id = add_resultado(
|
||||
proyecto,
|
||||
estudio_id=estudio,
|
||||
nombre=_slug(field.caption),
|
||||
etiqueta=field.caption.strip(),
|
||||
tipo_valor=tipo_valor,
|
||||
estudio_etiqueta=estudio_etiqueta,
|
||||
)
|
||||
return _NewResultado(resultado_id, tipo_valor)
|
||||
|
||||
|
||||
def _slug(text: str) -> str:
|
||||
without_accents = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
|
||||
return re.sub(r"[^a-z0-9]+", "_", without_accents.lower()).strip("_") or "campo"
|
||||
|
||||
|
||||
def _infer_tipo_valor(value: str) -> str:
|
||||
if find_date(value) is not None:
|
||||
return "fecha"
|
||||
if _is_number(value):
|
||||
return "numero"
|
||||
return "texto"
|
||||
|
||||
|
||||
def _is_number(value: str) -> bool:
|
||||
try:
|
||||
float(value.strip().replace(",", "."))
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _coerce_value(value: str, tipo_valor: str):
|
||||
if tipo_valor == "fecha":
|
||||
found = find_date(value)
|
||||
return found[0] if found else None
|
||||
if tipo_valor in ("numero", "booleano"):
|
||||
try:
|
||||
return float(value.strip().replace(",", "."))
|
||||
except ValueError:
|
||||
return None
|
||||
return value
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Writes the catalog-fallback fields a document source's records carry
|
||||
(captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`)
|
||||
into the silver layer directly: one synthetic `procedimiento` per record
|
||||
per estudio its resolved fields touch, with their `observacion`s matched
|
||||
or minted against the project's catalog (`catalog_matching`).
|
||||
|
||||
There is no staging row for these — the whole point is a field outside
|
||||
today's structured schemas — so this bypasses `DESDE_STAGING` and writes
|
||||
straight through the domain's existing `carga_repository`, the same one
|
||||
`webapi.orquestacion`'s `cargar` step uses for staging-derived batches.
|
||||
|
||||
Marked clearly apart from every staging-derived procedimiento:
|
||||
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
|
||||
staging table name. `fuente_id` is the record's own natural key (not a SQL
|
||||
row's surrogate id), so reprocessing the same record later — read again
|
||||
from the SQL source, re-uploaded as a file, or corrected by hand — updates
|
||||
the same rows in place instead of duplicating them; the structured fields
|
||||
a source also carries keep going through the unmodified staging/import
|
||||
path (`commit_sources`), independently of this.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from indicadores_kit.plata.procedimiento import LotePlata
|
||||
from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
|
||||
|
||||
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CatalogCommitResult:
|
||||
proyecto: str
|
||||
records_written: int = 0
|
||||
records_without_patient: int = 0
|
||||
fields_matched: int = 0
|
||||
fields_minted: int = 0
|
||||
|
||||
|
||||
def commit_discovered_fields(
|
||||
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None
|
||||
) -> CatalogCommitResult:
|
||||
"""A patient without a row in `persona` is counted and skipped: this
|
||||
path only fills in fields for a patient already known, it doesn't
|
||||
create one."""
|
||||
dominio = import_module(f"persistance.{proyecto}")
|
||||
tablas = tablas_de(proyecto)
|
||||
ruta = ruta_de_catalogo(proyecto)
|
||||
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
|
||||
|
||||
result = CatalogCommitResult(proyecto=proyecto)
|
||||
procedures, observations = [], []
|
||||
for record in records:
|
||||
if not record.discovered or record.key is None:
|
||||
continue
|
||||
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
|
||||
if not patients:
|
||||
result.records_without_patient += 1
|
||||
continue
|
||||
pac_id = patients[0].pac_id
|
||||
|
||||
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id)
|
||||
if any(field.is_new for field in matched):
|
||||
catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too
|
||||
matched = _fold_duplicates(matched)
|
||||
|
||||
by_estudio: dict[str, list] = defaultdict(list)
|
||||
for field in matched:
|
||||
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
|
||||
result.fields_minted += int(field.is_new)
|
||||
result.fields_matched += int(not field.is_new)
|
||||
for estudio, fields in by_estudio.items():
|
||||
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
|
||||
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
|
||||
observations += [
|
||||
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
|
||||
for field in fields
|
||||
]
|
||||
result.records_written += 1
|
||||
|
||||
if procedures:
|
||||
_sync_catalog(dominio, proyecto, tablas)
|
||||
dominio.carga_repository.guardar_carga(
|
||||
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
|
||||
"""A record's discovered captions can repeat the same resultado_id (a
|
||||
static label such as "FECHA" printed on several pages): `observacion`
|
||||
has one row per `(procedimiento, resultado_id)`, so only the first
|
||||
occurrence survives. `discover_captions` keeps every repeat on purpose
|
||||
and leaves folding to the caller (see its docstring)."""
|
||||
seen: set[str] = set()
|
||||
folded = []
|
||||
for field in matched:
|
||||
if field.resultado_id in seen:
|
||||
continue
|
||||
seen.add(field.resultado_id)
|
||||
folded.append(field)
|
||||
return folded
|
||||
|
||||
|
||||
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
|
||||
"""A field minted by `match_or_mint` only exists in the TOML until this
|
||||
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
|
||||
the matching `cat_estudio`/`cat_resultado` row to already be there."""
|
||||
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
|
||||
dominio.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
@@ -0,0 +1,231 @@
|
||||
"""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
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Recomputes a domain's indicators after its staging tables change.
|
||||
|
||||
A successful import asks for a recomputation (`RecomputationQueue.solicitar`),
|
||||
A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`),
|
||||
which only drops a marker file. A separate process (`python -m
|
||||
webapi.recomputation`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs ->
|
||||
webapi.indicadores_vivos`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's cycle (`webapi.orquestacion.correr`): catalogs ->
|
||||
staging to facts -> views -> registry -> definitions -> reports.
|
||||
Requests that arrive while a domain is running are folded into one more run.
|
||||
|
||||
@@ -26,7 +26,7 @@ from typing import Any
|
||||
|
||||
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
|
||||
|
||||
DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes
|
||||
DOMINIOS = ("cacu", "cama", "tea")
|
||||
_SUMMARY_MAX = 400
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -41,7 +41,7 @@ def _short(value: Any) -> str:
|
||||
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
||||
|
||||
|
||||
class RecomputationQueue:
|
||||
class ColaDeRecalculo:
|
||||
"""Marker-file queue and status of the indicator recomputations."""
|
||||
|
||||
def __init__(self, base: Path | None = None):
|
||||
@@ -55,18 +55,18 @@ class RecomputationQueue:
|
||||
def _status_path(self) -> Path:
|
||||
return self.base / "estado.json"
|
||||
|
||||
def request_run(self, dominio: str) -> None:
|
||||
if dominio not in DOMAINS:
|
||||
def solicitar(self, dominio: str) -> None:
|
||||
if dominio not in DOMINIOS:
|
||||
raise ValueError(f"dominio desconocido: {dominio!r}")
|
||||
self._pending.mkdir(parents=True, exist_ok=True)
|
||||
(self._pending / dominio).write_text(_now(), encoding="utf-8")
|
||||
|
||||
def pending(self) -> list[str]:
|
||||
def pendientes(self) -> list[str]:
|
||||
if not self._pending.exists():
|
||||
return []
|
||||
return sorted(p.name for p in self._pending.iterdir() if p.name in DOMAINS)
|
||||
return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS)
|
||||
|
||||
def take(self, dominio: str) -> bool:
|
||||
def tomar(self, dominio: str) -> bool:
|
||||
"""Consumes the marker; a request made from now on queues one more run."""
|
||||
try:
|
||||
(self._pending / dominio).unlink()
|
||||
@@ -74,15 +74,15 @@ class RecomputationQueue:
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
def status(self) -> dict[str, Any]:
|
||||
def estado(self) -> dict[str, Any]:
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
pending = set(self.pending())
|
||||
return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMAINS}
|
||||
pending = set(self.pendientes())
|
||||
return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS}
|
||||
|
||||
def _save_status(self, dominio: str, entrada: dict[str, Any]) -> None:
|
||||
def _guardar_estado(self, dominio: str, entrada: dict[str, Any]) -> None:
|
||||
self.base.mkdir(parents=True, exist_ok=True)
|
||||
lock = self.base / ".estado.lock"
|
||||
with open(lock, "w") as handle:
|
||||
@@ -96,58 +96,58 @@ class RecomputationQueue:
|
||||
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
tmp.replace(self._status_path)
|
||||
|
||||
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
|
||||
from webapi.orchestration import Context, run, steps_of
|
||||
def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrar`: the API migrates on startup)."""
|
||||
from webapi.orquestacion import Contexto, correr, pasos_de
|
||||
|
||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
|
||||
inicio = _now()
|
||||
started = time.monotonic()
|
||||
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||
self._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Context(dominio, desde, hasta, allow_undecided=True)
|
||||
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
||||
ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True)
|
||||
pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"])
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos],
|
||||
pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
)
|
||||
except Exception as exc: # the worker must survive a failing domain
|
||||
log.exception("recálculo de %s falló", dominio)
|
||||
entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))})
|
||||
entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2))
|
||||
self._save_status(dominio, entrada)
|
||||
self._guardar_estado(dominio, entrada)
|
||||
try:
|
||||
JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada})
|
||||
except OSError:
|
||||
pass
|
||||
return entrada
|
||||
|
||||
def serve(self) -> list[str]:
|
||||
def atender(self) -> list[str]:
|
||||
"""Runs every pending domain once; returns the ones it ran."""
|
||||
ran = []
|
||||
for dominio in self.pending():
|
||||
if self.take(dominio):
|
||||
self.run(dominio)
|
||||
for dominio in self.pendientes():
|
||||
if self.tomar(dominio):
|
||||
self.correr(dominio)
|
||||
ran.append(dominio)
|
||||
return ran
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
cola = RecomputationQueue()
|
||||
cola = ColaDeRecalculo()
|
||||
interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
|
||||
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
|
||||
for dominio in DOMAINS:
|
||||
cola.request_run(dominio)
|
||||
for dominio in DOMINIOS:
|
||||
cola.solicitar(dominio)
|
||||
stop = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
|
||||
while True:
|
||||
for dominio in cola.serve():
|
||||
log.info("%s: %s", dominio, cola.status()[dominio].get("estado"))
|
||||
for dominio in cola.atender():
|
||||
log.info("%s: %s", dominio, cola.estado()[dominio].get("estado"))
|
||||
if stop.wait(interval):
|
||||
break
|
||||
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
"""`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
|
||||
@@ -1,502 +0,0 @@
|
||||
"""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
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Each domain's cycle (CaCu, CaMa): from the staging the import leaves to the silver tables, the reference tables, the
|
||||
publication catalog and the views dbt compiled, which the measures are answered over. [Hamilton](https://hamilton.apache.org/)
|
||||
runs it.
|
||||
|
||||
Each step is a function of `cycle.py`. It takes the `Context` and, as parameters, the steps that must run before it;
|
||||
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
|
||||
Persistance's repositories (`ctx.repos`), so each one can run on its own.
|
||||
|
||||
migrate -> catalogs, registry, definitions
|
||||
catalogs -> load, check_silver
|
||||
load -> views, event_models, observe, check_silver
|
||||
registry -> observe
|
||||
event_models -> cohorts (only where there are cohorts: CaCu)
|
||||
cohorts -> estimate
|
||||
|
||||
uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026
|
||||
uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models
|
||||
uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica"
|
||||
|
||||
The `indicadores` service (`webapi.recomputation`) runs the same cycle, without `migrate`, each time an import writes
|
||||
data.
|
||||
|
||||
Module | What it does
|
||||
------------------|-------------
|
||||
`cycle.py` | The steps
|
||||
`runner.py` | `run(ctx, only=...)`: builds Hamilton's driver and runs the steps asked, in order
|
||||
`context.py` | The `Context`: project, years, cut-off, rules file and repositories
|
||||
`repositories.py` | `repositories_of(project)`: Persistance's repositories, by layer
|
||||
`project.py` | A project's period types and cohort definitions
|
||||
`connection.py` | Points Persistance at another database in the same process (tests)
|
||||
`semantic_layer.py` | dbt's views a project's measures read, and the publication catalog
|
||||
"""
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.runner import Step, run, steps_of
|
||||
|
||||
__all__ = ["Context", "Step", "run", "steps_of"]
|
||||
@@ -1,63 +0,0 @@
|
||||
"""La línea de comandos de la orquestación.
|
||||
|
||||
uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026 [--cutoff 2026-01-01] [--allow-undecided]
|
||||
uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models
|
||||
uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica" [--void]
|
||||
|
||||
La base es la de `<PROYECTO>_DATABASE_URL`, como en Persistance.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.runner import run
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
lector = argparse.ArgumentParser(prog="orchestration", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ordenes = lector.add_subparsers(dest="orden", required=True)
|
||||
c = ordenes.add_parser("cycle", help="corre los pasos del proyecto en orden")
|
||||
c.add_argument("project", choices=PROJECTS)
|
||||
c.add_argument("--from", dest="year_from", type=int, required=True, help="primer año de periodos")
|
||||
c.add_argument("--to", dest="year_to", type=int, required=True, help="último año de periodos")
|
||||
c.add_argument("--cutoff", type=date.fromisoformat, default=None)
|
||||
c.add_argument("--allow-undecided", action="store_true")
|
||||
c.add_argument("--parameters", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)")
|
||||
c.add_argument("--only", nargs="+", default=None, help="solo estos pasos")
|
||||
r = ordenes.add_parser("confirm-risks", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)")
|
||||
r.add_argument("project", choices=PROJECTS)
|
||||
r.add_argument("lote_id", type=int)
|
||||
r.add_argument("--reason", required=True, help="por qué se confirma o se anula; queda en cada evaluación")
|
||||
r.add_argument("--void", action="store_true", help="anular (entered-in-error) en vez de confirmar")
|
||||
args = lector.parse_args(argv)
|
||||
|
||||
if args.orden == "confirm-risks":
|
||||
cambiadas = confirm_risks(args.project, args.lote_id, args.reason, void=args.void)
|
||||
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}")
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters)
|
||||
for paso in run(ctx, only=args.only):
|
||||
print(f"{paso.name:20} {paso.seconds:6.1f} s")
|
||||
|
||||
|
||||
def confirm_risks(project: str, lote_id: int, reason: str, *, void: bool = False) -> int:
|
||||
"""Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva.
|
||||
|
||||
No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008).
|
||||
"""
|
||||
from persistance.edges.gold import ERROR, FINAL
|
||||
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
return repositories_of(project).gold.cohorts.change_state(lote_id, ERROR if void else FINAL, reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,229 +0,0 @@
|
||||
"""Los pasos del ciclo de un proyecto, como funciones de Hamilton.
|
||||
|
||||
Cada paso recibe el `Context` y, como parámetros, los pasos que tienen que
|
||||
correr antes; de esos nombres sale el grafo. Los pasos no se pasan datos entre
|
||||
sí: todo va por la base, a través de `ctx.repos`, así que cada uno se puede
|
||||
correr solo (`ejecutor.correr(ctx, solo=[...])`).
|
||||
|
||||
El kit calcula (funciones puras, o funciones de una sesión) y los repositorios
|
||||
de `persistance.edges` escriben, cada operación en una sesión (ADR-MD-005).
|
||||
Bronce lo escribe la ingesta, fuera del ciclo.
|
||||
"""
|
||||
|
||||
import logging
|
||||
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 webapi.orchestration.silver.quality import verificar_plata as calidad_de_la_plata
|
||||
from webapi.orchestration.silver.loads import carga_desde_staging, tablas_de_staging
|
||||
from webapi.orchestration.silver.observation_periods import periodos_de_observacion
|
||||
from webapi.orchestration.silver.views import ddl_de_vistas as ddl_de_v_persona
|
||||
from webapi.orchestration.reference.support import (
|
||||
CLAVE_DIM_FECHA_DESDE,
|
||||
filas_de_dim_fecha,
|
||||
grupos_de_edad_de,
|
||||
)
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.reference.rules import (
|
||||
RUTA_PARAMETROS,
|
||||
leer_parametros,
|
||||
valores_del_archivo,
|
||||
)
|
||||
from webapi.orchestration.reference.periods import periodos_de_tipos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from persistance.edges.silver import save_load_in
|
||||
from sqlmodel import SQLModel, func, select
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.semantic_layer import catalog_layers, event_views
|
||||
from models.cohorts.build import build_of, latest_build, read_frame
|
||||
from models.cohorts.definition import read_definition
|
||||
from webapi.orchestration.project import cohort_definitions, period_types
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def migrate(ctx: Context) -> str:
|
||||
"""`alembic upgrade head` del dominio, con el `alembic.ini` de Persistance."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
ini = Path(persistance.__file__).parent / ctx.project / "alembic.ini"
|
||||
raiz = logging.getLogger()
|
||||
manejadores, nivel = raiz.handlers[:], raiz.level
|
||||
estado = [(r, r.disabled) for r in logging.root.manager.loggerDict.values() if isinstance(r, logging.Logger)]
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
# `env.py` llama a `fileConfig`, que apaga los registradores ya creados y cambia los de la raíz.
|
||||
for registrador, apagado in estado:
|
||||
registrador.disabled = apagado
|
||||
raiz.handlers[:], raiz.level = manejadores, nivel
|
||||
return "head"
|
||||
|
||||
|
||||
def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project))
|
||||
return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
|
||||
|
||||
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
|
||||
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
|
||||
|
||||
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
|
||||
"""
|
||||
tablas, staging = tablas_de(ctx.project), tablas_de_staging(ctx.project)
|
||||
|
||||
def leer(sesion):
|
||||
filas = {modelo.__tablename__: list(sesion.exec(select(modelo))) for modelo in staging}
|
||||
return carga_desde_staging(filas, proyecto=ctx.project)
|
||||
|
||||
def escribir(sesion, datos):
|
||||
return save_load_in(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento,
|
||||
observacion=tablas.Observacion, fuente=datos.fuente, personas=datos.personas,
|
||||
plata=datos.plata)
|
||||
|
||||
return ctx.repos.materializer.materialize(leer, escribir)
|
||||
|
||||
|
||||
def views(load: SQLModel, ctx: Context) -> int:
|
||||
"""`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base."""
|
||||
return len(ctx.repos.silver.views.build_all(ddl_de_v_persona(tablas_de(ctx.project).Persona)))
|
||||
|
||||
|
||||
def registry(migrate: str, ctx: Context) -> list[str]:
|
||||
"""`parametros.toml` (o `ctx.parameters`) -> `def_parametro` (se reemplaza), los periodos que falten en
|
||||
`dim_periodo` y las tablas de apoyo `dim_fecha` y `dim_grupo_edad` (se reemplazan; I-MD27).
|
||||
|
||||
El archivo se lee y valida antes de escribir. Los periodos no se reemplazan:
|
||||
los reportes guardados apuntan a ellos. `dim_fecha` va de `comun.dim_fecha.desde` al fin
|
||||
de `ctx.year_to` 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.project), period_types(ctx.project, _manifest(ctx))
|
||||
ruta = ctx.parameters or RUTA_PARAMETROS
|
||||
parametros = leer_parametros(ruta, tablas=tablas)
|
||||
periodos = periodos_de_tipos(tipos, ctx.year_from, ctx.year_to, tablas=tablas)
|
||||
valores = valores_del_archivo(ruta)
|
||||
# Hasta el fin del último año del ciclo o del año del corte (por omisión, la última carga: hoy), el que sea mayor.
|
||||
hasta = date(max(ctx.year_to, (ctx.cutoff or date.today()).year), 12, 31)
|
||||
desde = date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE])
|
||||
grupos = grupos_de_edad_de(ctx.project, valores, tablas=tablas)
|
||||
gold = ctx.repos.gold
|
||||
gold.parameters.replace_all(parametros)
|
||||
gold.periods.add_missing(periodos)
|
||||
if gold.dates is not None and not _covers(gold.dates, desde, hasta):
|
||||
gold.dates.replace_in_bulk(filas_de_dim_fecha(valores, hasta, proyecto=ctx.project))
|
||||
if gold.age_groups is not None and grupos is not None:
|
||||
gold.age_groups.replace_all(grupos)
|
||||
return tipos
|
||||
|
||||
|
||||
def _covers(fechas, desde: date, hasta: date) -> bool:
|
||||
"""`dim_fecha` ya es exactamente de `desde` a `hasta`: tiene los dos extremos y un día por fecha."""
|
||||
return (fechas.get(desde) is not None and fechas.get(hasta) is not None
|
||||
and fechas.count() == (hasta - desde).days + 1)
|
||||
|
||||
|
||||
def definitions(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
"""The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest.
|
||||
|
||||
It's synchronized: what a report's unit uses isn't deleted.
|
||||
"""
|
||||
capas = catalog_layers(ctx.project, _manifest(ctx))
|
||||
return {"definitions": len(capas[0]), **ctx.repos.gold.publication.sync(capas)}
|
||||
|
||||
|
||||
def event_models(load: SQLModel, ctx: Context) -> int:
|
||||
"""The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base."""
|
||||
return len(ctx.repos.silver.views.build_all(event_views(_manifest(ctx), ctx.project)))
|
||||
|
||||
|
||||
def _manifest(ctx: Context) -> Path:
|
||||
if ctx.dbt_manifest is None:
|
||||
raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there")
|
||||
return ctx.dbt_manifest
|
||||
|
||||
|
||||
def observe(load: SQLModel, registry: list[str], ctx: Context) -> int:
|
||||
"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente."""
|
||||
return ctx.repos.silver.observation.observar(partial(
|
||||
periodos_de_observacion, proyecto=ctx.project, corte=ctx.cutoff,
|
||||
permitir_sin_definir=ctx.allow_undecided,
|
||||
))
|
||||
|
||||
|
||||
def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict[str, int]:
|
||||
"""Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro."""
|
||||
conteos = ctx.repos.silver.links.check(partial(calidad_de_la_plata, tablas=tablas_de(ctx.project)))
|
||||
for nombre, n in conteos.items():
|
||||
if n:
|
||||
log.warning("%s, plata de dos tablas: %d %s.", ctx.project, n, nombre.replace("_", " "))
|
||||
return conteos
|
||||
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
|
||||
|
||||
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
|
||||
"""
|
||||
tablas = tablas_de(ctx.project)
|
||||
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
||||
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
|
||||
|
||||
def armado(definicion, sesion):
|
||||
corte = ctx.cutoff or _last_load_date(sesion, tablas)
|
||||
return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
|
||||
linea=ctx.repos.silver.timeline.query)
|
||||
|
||||
armados = {}
|
||||
for ruta in cohort_definitions(ctx.project):
|
||||
definicion = read_definition(ruta)
|
||||
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
|
||||
return armados
|
||||
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
|
||||
|
||||
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador
|
||||
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
|
||||
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
|
||||
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
|
||||
`confirm-risks`, no este paso.
|
||||
"""
|
||||
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
||||
lotes = {}
|
||||
for ruta in cohort_definitions(ctx.project):
|
||||
definicion = read_definition(ruta)
|
||||
estimador = ctx.estimators.get(definicion.url)
|
||||
if estimador is None:
|
||||
continue
|
||||
|
||||
def frame(sesion, definicion=definicion):
|
||||
armado_id = latest_build(sesion, definicion.url, cohortes=tablas_cohorte)
|
||||
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, definicion,
|
||||
cohortes=tablas_cohorte)
|
||||
|
||||
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
|
||||
if armado_id is None:
|
||||
continue
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
return lotes
|
||||
|
||||
|
||||
def _last_load_date(sesion, tablas) -> date | None:
|
||||
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
|
||||
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
|
||||
if ultima is None or isinstance(ultima, date):
|
||||
return ultima.date() if isinstance(ultima, datetime) else ultima
|
||||
return date.fromisoformat(str(ultima)[:10])
|
||||
@@ -1,19 +0,0 @@
|
||||
"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from models.cohorts.definition import ROOT
|
||||
|
||||
|
||||
def period_types(proyecto: str, manifest: Path) -> list[str]:
|
||||
"""The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest."""
|
||||
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
||||
return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", [])
|
||||
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
|
||||
|
||||
|
||||
def cohort_definitions(proyecto: str) -> list[Path]:
|
||||
"""The cohort TOMLs the cycle builds (`models/cohorts/<project>/*.toml`): today only CaCu's surveillance cohort.
|
||||
Those in `<project>/proposals/` aren't built."""
|
||||
return sorted((ROOT / proyecto).glob("*.toml"))
|
||||
@@ -1,61 +0,0 @@
|
||||
"""`dim_grupo_edad`: los grupos de edad como datos, para etiquetar sin funciones del motor.
|
||||
|
||||
Una fila por grupo, con sus dos límites incluidos. El SQL calcula la edad
|
||||
cumplida con las partes de la fecha de `dim_fecha` y cruza con esta
|
||||
tabla. Los cortes de cada proyecto son la regla `<proyecto>.grupos_edad`
|
||||
del TOML de parámetros (una lista de pares mínimo y máximo): cambiar los
|
||||
grupos es editar el TOML, no un SQL.
|
||||
"""
|
||||
|
||||
from core.indicadores.registro import DimGrupoEdadBase
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
|
||||
EDAD_MAXIMA = 150 # tope del grupo abierto de arriba; una edad mayor es un error de captura
|
||||
|
||||
|
||||
def grupos_de_cortes(cortes: list[list[int]], *, tablas: TablasKit) -> list[DimGrupoEdadBase]:
|
||||
"""De los pares `[edad_min, edad_max]` del TOML a los grupos, más dos abiertos.
|
||||
|
||||
[[25, 34], [35, 44]] -> "<25", "25-34", "35-44", "45+". Los grupos
|
||||
abiertos (S-M3, usuario, 2026-10-08) hacen que toda edad conocida
|
||||
caiga en un grupo: `sin_dato` queda solo para quien no tiene fecha de
|
||||
nacimiento (o una edad imposible). Por lo mismo, los cortes no pueden
|
||||
encimarse ni dejar huecos.
|
||||
"""
|
||||
grupos = []
|
||||
for corte in cortes:
|
||||
if len(corte) != 2 or not all(type(edad) is int for edad in corte):
|
||||
raise ValueError(f"Un corte de edad son dos enteros, mínimo y máximo; llegó {corte!r}.")
|
||||
minimo, maximo = corte
|
||||
grupos.append(
|
||||
tablas.DimGrupoEdad(etiqueta=f"{minimo}-{maximo}", edad_min=minimo, edad_max=maximo)
|
||||
)
|
||||
_exigir_contiguos(grupos)
|
||||
menor = min(grupo.edad_min for grupo in grupos)
|
||||
mayor = max(grupo.edad_max for grupo in grupos)
|
||||
if menor > 0:
|
||||
grupos.insert(0, tablas.DimGrupoEdad(etiqueta=f"<{menor}", edad_min=0, edad_max=menor - 1))
|
||||
if mayor < EDAD_MAXIMA:
|
||||
grupos.append(
|
||||
tablas.DimGrupoEdad(etiqueta=f"{mayor + 1}+", edad_min=mayor + 1, edad_max=EDAD_MAXIMA)
|
||||
)
|
||||
return grupos
|
||||
|
||||
|
||||
def _exigir_contiguos(grupos: list[DimGrupoEdadBase]) -> None:
|
||||
if not grupos:
|
||||
raise ValueError("Hace falta al menos un corte de edad.")
|
||||
anterior = None
|
||||
for grupo in sorted(grupos, key=lambda g: g.edad_min):
|
||||
if grupo.edad_min > grupo.edad_max:
|
||||
raise ValueError(f"El grupo {grupo.etiqueta!r} tiene los límites al revés.")
|
||||
if anterior is not None and grupo.edad_min <= anterior.edad_max:
|
||||
raise ValueError(f"Los grupos {anterior.etiqueta!r} y {grupo.etiqueta!r} se enciman.")
|
||||
if anterior is not None and grupo.edad_min > anterior.edad_max + 1:
|
||||
raise ValueError(
|
||||
f"Entre {anterior.etiqueta!r} y {grupo.etiqueta!r} hay edades sin grupo."
|
||||
)
|
||||
anterior = grupo
|
||||
@@ -1,136 +0,0 @@
|
||||
"""Catálogos de la plata (F1): `core/catalogos/<proyecto>.toml` leído y validado.
|
||||
|
||||
Un catálogo es estudio -> resultado -> valor (`core/catalogos/LEEME.md`).
|
||||
Aquí solo se lee el archivo y se devuelven las filas de `cat_estudio`,
|
||||
`cat_resultado` y `cat_valor` del proyecto; las escribe Persistance por la
|
||||
arista `catalogos` de webapi.orchestration (T-17c).
|
||||
|
||||
`codigos_hospital` de cada estudio no va a ninguna tabla: es cómo nombra el
|
||||
hospital al estudio (tipo de estudio de la orden, instrumento), y lo usa la
|
||||
carga de F5.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import core
|
||||
from core.indicadores.catalogos import TIPOS_DE_VALOR
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
# Los catálogos viven en Core, junto a los modelos de sus tablas.
|
||||
RAIZ_CATALOGOS = Path(core.__file__).parent / "catalogos"
|
||||
|
||||
|
||||
class CatalogoInvalido(ValueError):
|
||||
"""El archivo de catálogo no cumple sus reglas."""
|
||||
|
||||
|
||||
class Catalogo(NamedTuple):
|
||||
"""Las filas de las tres tablas de catálogo de un proyecto, en el orden del archivo."""
|
||||
|
||||
estudios: list[SQLModel]
|
||||
resultados: list[SQLModel]
|
||||
valores: list[SQLModel]
|
||||
|
||||
|
||||
def ruta_de_catalogo(proyecto: str) -> Path:
|
||||
"""El archivo de catálogo del proyecto: `core/catalogos/<proyecto>.toml`."""
|
||||
return RAIZ_CATALOGOS / f"{proyecto}.toml"
|
||||
|
||||
|
||||
def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
|
||||
"""Lee el archivo, lo valida y devuelve las filas con las clases de `tablas`.
|
||||
|
||||
`resultado_id` es `"<estudio>.<resultado>"`; el `orden` de un valor es su
|
||||
posición en la lista, desde 1, y todos llegan `vigente` (retirar uno es
|
||||
cosa de quien sincroniza la tabla).
|
||||
"""
|
||||
estudios, resultados, valores = [], [], []
|
||||
for estudio_id, estudio in _leer(ruta).items():
|
||||
estudios.append(tablas.CatEstudio(estudio_id=estudio_id, etiqueta=_etiqueta(estudio, estudio_id)))
|
||||
for nombre, resultado in estudio.get("resultados", {}).items():
|
||||
resultado_id = f"{estudio_id}.{nombre}"
|
||||
tipo_valor = _tipo_de_valor(resultado, resultado_id)
|
||||
resultados.append(
|
||||
tablas.CatResultado(
|
||||
resultado_id=resultado_id,
|
||||
estudio_id=estudio_id,
|
||||
etiqueta=_etiqueta(resultado, resultado_id),
|
||||
tipo_valor=tipo_valor,
|
||||
unidad=resultado.get("unidad"),
|
||||
sistema=resultado.get("sistema"),
|
||||
)
|
||||
)
|
||||
valores += [
|
||||
tablas.CatValor(
|
||||
resultado_id=resultado_id,
|
||||
valor_id=valor_id,
|
||||
etiqueta=etiqueta,
|
||||
orden=orden,
|
||||
estado="vigente",
|
||||
)
|
||||
for orden, (valor_id, etiqueta) in enumerate(_valores(resultado, resultado_id, tipo_valor), start=1)
|
||||
]
|
||||
return Catalogo(estudios, resultados, valores)
|
||||
|
||||
|
||||
def codigos_hospital(proyecto: str) -> dict[str, str]:
|
||||
"""Código del hospital -> `estudio_id`, del catálogo del proyecto.
|
||||
|
||||
Un código que aparece en dos estudios es un error: no se sabría a cuál va.
|
||||
"""
|
||||
codigos: dict[str, str] = {}
|
||||
for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items():
|
||||
for codigo in estudio.get("codigos_hospital", []):
|
||||
if codigo in codigos:
|
||||
raise CatalogoInvalido(
|
||||
f"El código del hospital {codigo!r} está en dos estudios: {codigos[codigo]!r} y {estudio_id!r}."
|
||||
)
|
||||
codigos[codigo] = estudio_id
|
||||
return codigos
|
||||
|
||||
|
||||
def _leer(ruta: Path) -> dict:
|
||||
return tomllib.loads(Path(ruta).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _etiqueta(seccion: dict, nombre: str) -> str:
|
||||
if "etiqueta" not in seccion:
|
||||
raise CatalogoInvalido(f"{nombre}: falta la etiqueta.")
|
||||
return seccion["etiqueta"]
|
||||
|
||||
|
||||
def _tipo_de_valor(resultado: dict, resultado_id: str) -> str:
|
||||
"""El `tipo_valor` del resultado, y las llaves que ese tipo admite."""
|
||||
tipo_valor = resultado.get("tipo_valor")
|
||||
if tipo_valor not in TIPOS_DE_VALOR:
|
||||
raise CatalogoInvalido(
|
||||
f"{resultado_id}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}."
|
||||
)
|
||||
if tipo_valor == "codigo" and not resultado.get("valores"):
|
||||
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.")
|
||||
if tipo_valor != "codigo" and "valores" in resultado:
|
||||
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.")
|
||||
if tipo_valor != "externo" and "sistema" in resultado:
|
||||
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.")
|
||||
if tipo_valor != "numero" and "unidad" in resultado:
|
||||
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.")
|
||||
return tipo_valor
|
||||
|
||||
|
||||
def _valores(resultado: dict, resultado_id: str, tipo_valor: str) -> list[tuple[str, str]]:
|
||||
"""(valor, etiqueta) de cada valor del resultado, en el orden del archivo; sin repetidos."""
|
||||
if tipo_valor != "codigo":
|
||||
return []
|
||||
vistos: set[str] = set()
|
||||
valores = []
|
||||
for entrada in resultado["valores"]:
|
||||
valor = entrada["valor"]
|
||||
if valor in vistos:
|
||||
raise CatalogoInvalido(f"{resultado_id}: el valor {valor!r} está repetido.")
|
||||
vistos.add(valor)
|
||||
valores.append((valor, _etiqueta(entrada, f"{resultado_id}: {valor!r}")))
|
||||
return valores
|
||||
@@ -1,35 +0,0 @@
|
||||
"""`dim_fecha`: una fila por día, para hacer aritmética de fechas sin funciones del motor.
|
||||
|
||||
Sumar días o medir un intervalo es una resta de `dia_num` con un cruce.
|
||||
`dia_habil_num` cuenta solo de lunes a viernes; los días festivos no
|
||||
están (haría falta un calendario, S-K27). `anio`, `mes` y `dia` son las
|
||||
partes de la fecha: sirven para la edad cumplida, que no es una resta de
|
||||
días. Se reemplaza entera por `RegistroRepository.reemplazar`.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.indicadores.registro import DimFechaBase
|
||||
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
|
||||
def dias(desde: date, hasta: date, *, tablas: TablasKit) -> list[DimFechaBase]:
|
||||
"""Los días de `desde` a `hasta`, los dos incluidos."""
|
||||
if hasta < desde:
|
||||
raise ValueError(f"El rango de dim_fecha va al revés: {desde} a {hasta}.")
|
||||
filas, habiles = [], 0
|
||||
for numero in range((hasta - desde).days + 1):
|
||||
dia = desde + timedelta(days=numero)
|
||||
habiles += dia.weekday() < 5
|
||||
filas.append(
|
||||
tablas.DimFecha(
|
||||
fecha=dia,
|
||||
dia_num=numero,
|
||||
dia_habil_num=habiles,
|
||||
anio=dia.year,
|
||||
mes=dia.month,
|
||||
dia=dia.day,
|
||||
)
|
||||
)
|
||||
return filas
|
||||
@@ -1,701 +0,0 @@
|
||||
# Parámetros de indicadores_kit, para todos los proyectos.
|
||||
#
|
||||
# Cada parámetro lleva:
|
||||
# valor lo que usa el cálculo
|
||||
# estado "sin_definir" nadie lo ha decidido; el valor solo permite correr
|
||||
# "provisional" hay una propuesta documentada, falta confirmarla
|
||||
# "confirmado" decisión cerrada
|
||||
# fuente dónde está documentada la decisión o la pendiente
|
||||
#
|
||||
# Se carga en la tabla def_parametro de cada base con
|
||||
# registry.parametros.cargar_parametros. La clave es "seccion.nombre".
|
||||
|
||||
[comun.dim_fecha.desde]
|
||||
# El primer día de `dim_fecha`, la tabla de fechas que cruzan las consultas portables (la edad del estrato
|
||||
# `grupo_edad`). Fijo, porque `dia_num` y `dia_habil_num` se cuentan desde él; el último día es el fin del
|
||||
# último año del ciclo. Tiene que ser anterior al nacimiento más antiguo: si no, la guarda de cobertura
|
||||
# (`calidad/cobertura.exigir_cobertura`) detiene el cálculo y lo dice (T-24f, I-MD27).
|
||||
valor = "1920-01-01"
|
||||
estado = "provisional"
|
||||
fuente = "Usuario, 2026-10-22: dim_fecha y dim_grupo_edad se llenan de los TOML (T-24f, I-MD27); 1920 cubre edades hasta los 106 años"
|
||||
|
||||
[comun.umbral_supresion]
|
||||
# Se suprime un resultado cuyo denominador es menor que este valor.
|
||||
valor = 5
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta confirmarla (usuario, 2026-10-12). Los catálogos dicen < 5 y dejan la pregunta abierta (conventions.suppression.min_cell)"
|
||||
|
||||
# Bandas del resumen de riesgos (`mart/riesgos.py`, T-21d). Provisionales: la compuerta
|
||||
# pide que todo indicador calcule sin `sin_definir`; son candidatos documentados, falta que clínica decida (MD-Q5).
|
||||
[comun.riesgos.corte_intermedio]
|
||||
# Probabilidad desde la que la banda es INTERMEDIO (de 0 a 1).
|
||||
valor = 0.04
|
||||
estado = "provisional"
|
||||
fuente = "Candidato del prototipo: umbral de acción de ASCCP 2019 para colposcopia (4 %, riesgo inmediato de CIN3+). Decide clínica (MD-Q5)"
|
||||
|
||||
[comun.riesgos.corte_alto]
|
||||
# Probabilidad desde la que la banda es ALTO (de 0 a 1).
|
||||
valor = 0.25
|
||||
estado = "provisional"
|
||||
fuente = "Candidato del prototipo: umbral de ASCCP 2019 para tratamiento (25 %). En TEA no hay candidato propio. Decide clínica (MD-Q5)"
|
||||
|
||||
[cacu.riesgos.horizonte_banda]
|
||||
# Años desde la fecha índice de la evaluación que se clasifica; 0 = riesgo prevalente (inmediato).
|
||||
valor = 0
|
||||
estado = "provisional"
|
||||
fuente = "Prototipo: horizonte 0, el que miden los umbrales de ASCCP. Decide clínica con modelos (MD-Q5)"
|
||||
|
||||
[cama.riesgos.horizonte_banda]
|
||||
# Años desde el BI-RADS índice: el horizonte del desenlace de la cohorte de tamizaje (365 días, T-21g).
|
||||
valor = 1
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)"
|
||||
|
||||
[tea.riesgos.horizonte_banda]
|
||||
# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses).
|
||||
valor = 4
|
||||
estado = "provisional"
|
||||
fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)"
|
||||
|
||||
[comun.catalogos.banda_riesgo]
|
||||
# Las bandas del resumen de riesgos, de menor a mayor.
|
||||
valor = [
|
||||
{ clave = "BAJO", etiqueta = "Riesgo bajo", color = "#9DBFE3" },
|
||||
{ clave = "INTERMEDIO", etiqueta = "Riesgo intermedio", color = "#E8C28E" },
|
||||
{ clave = "ALTO", etiqueta = "Riesgo alto", color = "#D98E4A" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta T-21d: tres bandas fijas con dos cortes (comun.riesgos.*); los nombres siguen a MD-Q5"
|
||||
|
||||
[cacu.calidad_insatisfactoria]
|
||||
valor = "INSATISFACTORIO"
|
||||
estado = "provisional"
|
||||
fuente = "kpi_catalog_cacu_eu.yaml CACU_EU8; Core admite también \"0\" (CITO_CALIDAD_ESPECIMEN_ALIAS); valores reales sin confirmar"
|
||||
|
||||
[cama.calidad_satisfactoria]
|
||||
valor = "SATISFACTORIO"
|
||||
estado = "provisional"
|
||||
fuente = "kpi_catalog_cama_eu.yaml CAMA_EU8; mast_calidad_imagen es texto libre, valores reales sin confirmar"
|
||||
|
||||
[cacu.grupos_edad]
|
||||
# Grupos de edad del estrato `grupo_edad`: pares [mínimo, máximo] en años cumplidos, incluidos,
|
||||
# contiguos. Se agrega un grupo abierto en cada extremo ("<25", "65+").
|
||||
valor = [[25, 34], [35, 44], [45, 54], [55, 64]]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar"
|
||||
|
||||
[cama.grupos_edad]
|
||||
valor = [[40, 49], [50, 59], [60, 69]]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar"
|
||||
|
||||
# ===========================================================================
|
||||
# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8)
|
||||
#
|
||||
# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la
|
||||
# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses".
|
||||
# Las listas y tablas se guardan en def_parametro como JSON.
|
||||
# El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga.
|
||||
# Documentos citados (repositorio analisis-tea, carpeta docs/):
|
||||
# lista = lista_indicadores_TEA_v2.md · contexto = contexto_reporte_pipeline_TEA.md
|
||||
# estandares = estandares_indicadores_TEA.md · modif = modificaciones.md
|
||||
# ===========================================================================
|
||||
|
||||
[tea.cohorte.edad_min_meses]
|
||||
valor = 16
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)"
|
||||
|
||||
[tea.cohorte.edad_max_meses]
|
||||
valor = 36
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1 (director)"
|
||||
|
||||
[tea.cohorte.dias_por_mes]
|
||||
# Mes medio para pasar días a meses (edad con un decimal).
|
||||
valor = 30.4375
|
||||
estado = "confirmado"
|
||||
fuente = "analisis-tea/tea/comun.py, edad_meses"
|
||||
|
||||
[tea.cohorte.plazo_ados2_eeg_dias]
|
||||
# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo.
|
||||
valor = 30
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)"
|
||||
|
||||
[tea.cohorte.ventanas]
|
||||
# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos.
|
||||
valor = [
|
||||
{ clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" },
|
||||
{ clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" },
|
||||
{ clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" },
|
||||
]
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)"
|
||||
|
||||
[tea.instrumentos.informantes_ramos]
|
||||
# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre.
|
||||
valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"]
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1 (equipo); psicología no registra al cuidador principal"
|
||||
|
||||
[tea.instrumentos.informantes_otros]
|
||||
valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"]
|
||||
estado = "confirmado"
|
||||
fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21"
|
||||
|
||||
[tea.ramos.areas]
|
||||
# «TOTAL» no cuenta como área.
|
||||
valor = [
|
||||
{ clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
|
||||
{ clave = "LINGUISTICO", etiqueta = "Lingüístico" },
|
||||
{ clave = "FISICO", etiqueta = "Físico" },
|
||||
{ clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
|
||||
{ clave = "ADAPTATIVO", etiqueta = "Adaptativo" },
|
||||
]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de ins_area; contexto §1"
|
||||
|
||||
[tea.poblacion.css_min_tea]
|
||||
# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor.
|
||||
valor = 3
|
||||
estado = "confirmado"
|
||||
fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo"
|
||||
|
||||
[tea.diagnostico.cie_tea]
|
||||
# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840).
|
||||
valor = ["F840"]
|
||||
estado = "confirmado"
|
||||
fuente = "usuario (2026-10-15): solo F84.0 (autismo)"
|
||||
|
||||
[tea.diagnostico.instrumentos_mchat]
|
||||
# M25: valores de psi_instrumento_tamizaje que son un M-CHAT.
|
||||
valor = ["M_CHAT_R", "M_CHAT_RF"]
|
||||
estado = "confirmado"
|
||||
fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)"
|
||||
|
||||
[tea.atencion.plazo_referencia_evaluacion_dias]
|
||||
# K1: inicio de la evaluación a más tardar este número de días después de la referencia.
|
||||
valor = 90
|
||||
estado = "confirmado"
|
||||
fuente = "estandares: NICE QS51, enunciado 1 (3 meses)"
|
||||
|
||||
[tea.parto.apgar_corte]
|
||||
# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10).
|
||||
valor = 7
|
||||
estado = "confirmado"
|
||||
fuente = "lista, M17: menor de 7, 7, y 8 a 10"
|
||||
|
||||
# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar:
|
||||
# un cambio pide volver a cargar.
|
||||
[tea.antecedentes_maternos.no_registrado]
|
||||
valor = "NO_REGISTRADO"
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2: NO_REGISTRADO = sin dato"
|
||||
|
||||
[tea.antecedentes_maternos.hipertension_ninguno]
|
||||
valor = "NINGUNO"
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_hipertension_preeclampsia"
|
||||
|
||||
[tea.antecedentes_maternos.embarazo_no_unico]
|
||||
valor = ["GEMELAR", "TRIPLE_O_MAS"]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_embarazo_multiple"
|
||||
|
||||
[tea.antecedentes_maternos.liquido_anormal]
|
||||
valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_liquido_amniotico"
|
||||
|
||||
[tea.supresion.activa]
|
||||
# Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se
|
||||
# suprime nada, aunque comun.umbral_supresion tenga valor.
|
||||
valor = false
|
||||
estado = "provisional"
|
||||
fuente = "modif: supresión opcional, apagada por omisión (tablero interno); CaCu tiene la suya sin decidir (bloqueos.md D1)"
|
||||
|
||||
[tea.presentacion.fuente]
|
||||
valor = "Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL"
|
||||
estado = "confirmado"
|
||||
fuente = "lista: toda figura lleva la fuente"
|
||||
|
||||
[tea.presentacion.leyenda]
|
||||
valor = "Uso exclusivo de investigación. No usar para decisiones clínicas."
|
||||
estado = "confirmado"
|
||||
fuente = "marco_regulatorio_TEA.md §3"
|
||||
|
||||
# Catálogos de las composiciones (C2): clave (como en la base), etiqueta y color.
|
||||
# Colores: paleta de ejemplo del estándar común, hasta que se fije la hoja de estilo.
|
||||
[tea.catalogos.sin_dato]
|
||||
valor = { etiqueta = "Sin dato", color = "#C9CDD2" }
|
||||
estado = "confirmado"
|
||||
fuente = "lista: «sin dato» siempre se muestra como categoría propia"
|
||||
|
||||
[tea.catalogos.sexo]
|
||||
valor = [
|
||||
{ clave = "F", etiqueta = "Femenino", color = "#E0A030" },
|
||||
{ clave = "M", etiqueta = "Masculino", color = "#2F6DB3" },
|
||||
{ clave = "I", etiqueta = "Indeterminado", color = "#8A9199" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, pac_sexo; colores provisionales"
|
||||
|
||||
[tea.catalogos.resultado_mchat]
|
||||
valor = [
|
||||
{ clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" },
|
||||
{ clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" },
|
||||
{ clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales"
|
||||
|
||||
[tea.catalogos.interpretacion_ramos]
|
||||
valor = [
|
||||
{ clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" },
|
||||
{ clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" },
|
||||
{ clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales"
|
||||
|
||||
[tea.catalogos.grado_hipoacusia]
|
||||
valor = [
|
||||
{ clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" },
|
||||
{ clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" },
|
||||
{ clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" },
|
||||
{ clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" },
|
||||
{ clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" },
|
||||
{ clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, pea_grado_hipoacusia; colores provisionales"
|
||||
|
||||
[tea.catalogos.apgar_5min]
|
||||
valor = [
|
||||
{ clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" },
|
||||
{ clave = "SIETE", etiqueta = "7", color = "#E8C28E" },
|
||||
{ clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "lista, M17; colores provisionales"
|
||||
|
||||
# ===========================================================================
|
||||
# CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml)
|
||||
# ===========================================================================
|
||||
|
||||
[cacu.citologia_anomala]
|
||||
# Resultados de citología (células escamosas) que cuentan como anómalos en IND1.
|
||||
valor = ["ASC-US", "ASC-H", "LIEBG", "LIEAG", "CIS"]
|
||||
estado = "provisional"
|
||||
fuente = "Usuario, 2026-10-24: ASC-US cuenta como anómalo. Antes (2026-10-12) quedaba fuera, como en kpi_catalog.yaml IND1 ('abnormal set is LSIL+, ASC-H, HSIL'); falta que clínica lo confirme y decidir glandulares y carcinoma (I-K61)"
|
||||
|
||||
[cacu.biopsia_cis]
|
||||
valor = ["CIS"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). IND2b (I-K16): arranque con el grado CIS de Core (GradoCIN); falta que clínica lo confirme y ver que llega poblado en bx_cin_grado"
|
||||
|
||||
[cacu.deteccion_grados]
|
||||
# Grados de biopsia que cuentan como lesión detectada en CACU_EU13: el umbral CIN2+.
|
||||
valor = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta del catálogo (kpi_catalog_cacu_eu.yaml CACU_EU13: CIN2+), falta que clínica la confirme. CIN3+ no se puede: `bx_cin_grado` guarda CIN2 y CIN3 juntos como LIEAG (I-K15)"
|
||||
|
||||
[cacu.citologia_alto_grado]
|
||||
# Resultados de citología de alto grado: la población de CACU_CONFIRMACION_CITOLOGIA (la paciente entra si su
|
||||
# última citología válida del periodo es una de estos) y los valores del estrato `citologia_alto_grado`.
|
||||
valor = ["ASC-H", "LIEAG", "CIS"]
|
||||
estado = "provisional"
|
||||
fuente = "Usuario, 2026-10-24: confirmación por biopsia según resultado citológico, las tres peores categorías Bethesda; falta que clínica la confirme"
|
||||
|
||||
# ===========================================================================
|
||||
# CaCu · estatus de seguimiento ASCCP (T-24c): las reglas de `cacu/seguimiento.py`
|
||||
#
|
||||
# El código solo aplica estas reglas; cada una dice en su comentario las opciones que
|
||||
# sabe aplicar. Una opción desconocida falla con un mensaje que lista las admitidas.
|
||||
# Los textos se comparan en mayúsculas y sin acentos, por contención.
|
||||
# ===========================================================================
|
||||
|
||||
[cacu.seguimiento.marco]
|
||||
# Qué estratificación de seguimiento se publica. Opciones: "estatus" (ASCCP), "ronda" (UE, todavía no).
|
||||
valor = ["estatus"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22 (§5.1): ASCCP provisional; las rondas UE, después"
|
||||
|
||||
[cacu.seguimiento.referencia]
|
||||
# A qué fecha se evalúa el estatus en el estrato: "inicio_periodo" (lo que traía al entrar al
|
||||
# periodo, como `grupo_edad`) o "fecha_corte" (al corte del reporte).
|
||||
valor = "inicio_periodo"
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo"
|
||||
|
||||
[cacu.seguimiento.precedencia]
|
||||
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de
|
||||
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir).
|
||||
# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo).
|
||||
valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.colposcopia.evidencias]
|
||||
# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto):
|
||||
# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos`
|
||||
# "cie" una nota de colposcopia con un CIE-10 de `colposcopia.cie`
|
||||
# "diagnostico_texto" una nota de colposcopia cuyo diagnóstico en texto contiene uno de
|
||||
# `colposcopia.diagnosticos` (la nota que llega «S/C»)
|
||||
# "orden_biopsia" una orden de biopsia (la solicitud)
|
||||
# "biopsia" una biopsia reportada
|
||||
# «Nota de colposcopia»: de una de `colposcopia.especialidades` y, con `colposcopia.requisito`, posterior
|
||||
# a la cita de valoración.
|
||||
valor = ["motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: el motivo, el CIE y el diagnóstico en texto, solo en notas de colposcopia"
|
||||
|
||||
[cacu.seguimiento.colposcopia.requisito]
|
||||
# Qué tiene que haber antes de una nota de colposcopia para que cuente. Opciones:
|
||||
# "valoracion_previa" una cita de valoración anterior: la nota que resuelve una toma, con las reglas de
|
||||
# CACU_DIAS_TOMA_DIAGNOSTICO (`cacu.diagnostico.cie`, `cacu.diagnostico.especialidades`
|
||||
# y `cacu.horizontes.toma_diagnostico_dias`); es de donde sale la fecha de diagnóstico
|
||||
# "ninguno" cuenta sola
|
||||
valor = "valoracion_previa"
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «si no hay cita de valoración, que es de la que se toma la fecha de diagnóstico, no puede haber cita de colposcopia»"
|
||||
|
||||
[cacu.seguimiento.colposcopia.biopsia_requisito]
|
||||
# Cuándo cuentan la orden de biopsia y la biopsia reportada. Opciones:
|
||||
# "mismo_dia_que_colposcopia" la orden (o la solicitud de la reportada) es del mismo día que una nota de
|
||||
# colposcopia válida de la paciente: la colposcopia es la madre de la biopsia
|
||||
# "ninguno" cuentan solas
|
||||
valor = "mismo_dia_que_colposcopia"
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «la orden de biopsia debe ser expedida el mismo día que la de colposcopia»; «la colposcopia es padre de la biopsia»"
|
||||
|
||||
[cacu.seguimiento.colposcopia.motivos]
|
||||
# Textos del motivo de consulta de una nota de colposcopia que la indican (lista libre, en mayúsculas y sin acentos).
|
||||
valor = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.colposcopia.especialidades]
|
||||
# Especialidades de una nota de colposcopia (para el motivo, el CIE y el diagnóstico en texto). Opciones:
|
||||
# el enum `Especialidad` de Core (MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA).
|
||||
valor = ["CLINICA_MUJER_COLPOSCOPIA"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: la nota de colposcopia es de «Clínica de la Mujer y Colposcopia», no hay otra"
|
||||
|
||||
[cacu.seguimiento.colposcopia.cie]
|
||||
# CIE-10 de una nota de colposcopia que indican colposcopia, como los deja la carga (sin punto).
|
||||
# Opciones: el enum CIE-10 compartido con dev-data.
|
||||
valor = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme; B97.7 (VPH) agregado por el ejemplo del usuario (2026-10-22)"
|
||||
|
||||
[cacu.seguimiento.colposcopia.diagnosticos]
|
||||
# Textos del diagnóstico de una nota de colposcopia que indican colposcopia aunque el CIE llegue
|
||||
# «S/C» (lista libre, en mayúsculas y sin acentos).
|
||||
valor = ["VIRUS DEL PAPILOMA HUMANO"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «S/C y con Diagnóstico: VIRUS DEL PAPILOMA HUMANO»"
|
||||
|
||||
[cacu.seguimiento.tratamiento.fuentes]
|
||||
# Qué cuenta como tratamiento. Opciones: "nota_posterior_a_colposcopia" (una nota con un CIE-10 de
|
||||
# `tratamiento.cie`, posterior en fecha a la primera evidencia de colposcopia).
|
||||
valor = ["nota_posterior_a_colposcopia"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: el tratamiento está en la nota médica, después de una de colposcopia"
|
||||
|
||||
[cacu.seguimiento.tratamiento.cie]
|
||||
# CIE-10 de la nota de tratamiento, como los deja la carga. Opciones: el enum CIE-10 compartido.
|
||||
valor = ["D06", "D060", "D061", "D067", "D069"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: «un código CIE-10 anómalo, por ejemplo D06»"
|
||||
|
||||
[cacu.seguimiento.insuficiente.regla]
|
||||
# Cuándo la historia no alcanza. Opciones: "inicio_datos_posterior_a_alta", "sin_alta_registrada",
|
||||
# "ambos", "nunca". Hoy no hay fecha de alta (derechohabiencia): con "inicio_datos_posterior_a_alta"
|
||||
# se asume alta posterior al inicio de los datos y nadie cae; con "sin_alta_registrada", todas caerían.
|
||||
valor = "inicio_datos_posterior_a_alta"
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: sin columna de alta, se asume posterior"
|
||||
|
||||
[cacu.seguimiento.vigilancia.especialidades]
|
||||
# Especialidades de las citologías de vigilancia. Opciones: el enum `Especialidad` de Core. Se aplica
|
||||
# solo cuando la especialidad de la citología se conoce (la de su orden): una paciente sale de
|
||||
# vigilancia si todas sus citologías tienen especialidad conocida y ninguna está aquí.
|
||||
valor = ["MEDICINA_FAMILIAR", "CLINICA_MUJER_COLPOSCOPIA"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: solo cuando se conoce"
|
||||
|
||||
# ===========================================================================
|
||||
# CaCu · la lista de seguimiento (T-24d): `GET /cacu/seguimiento`, `serving/seguimiento.py`
|
||||
# ===========================================================================
|
||||
|
||||
[cacu.seguimiento.ventana_meses]
|
||||
# Meses hacia atrás desde el corte en los que un estudio mete a la paciente en la lista. Opciones: 1, 3, 6, 12.
|
||||
valor = 3
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.fecha_estudio]
|
||||
# Desde qué fecha cuenta la ventana. Opciones: "toma" (la de la toma) o "reporte" (la de su resultado).
|
||||
valor = "toma"
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.estudios]
|
||||
# Qué estudios meten a la paciente en la lista. Opciones: cualquier subconjunto de "citologia" y "vph".
|
||||
valor = ["citologia", "vph"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.resultado_mostrado]
|
||||
# Qué citología mostrar si hay varias en la ventana. Opciones: "ultimo" o "mas_grave" (por el orden de
|
||||
# `cacu.catalogos.citologia`, de menos a más grave; empate, la más reciente). El VPH muestra siempre el último.
|
||||
valor = "ultimo"
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
# Catálogo de resultados citológicos de CaCu (C2), de menos a más grave. Las claves son las
|
||||
# de `CelulasEscamosas` en Core (`cit_celulas_escamosas`).
|
||||
[cacu.catalogos.sin_dato]
|
||||
valor = { etiqueta = "Sin dato", color = "#C9CDD2" }
|
||||
estado = "confirmado"
|
||||
fuente = "lista: «sin dato» siempre se muestra como categoría propia"
|
||||
|
||||
[cacu.catalogos.citologia]
|
||||
valor = [
|
||||
{ clave = "NORMAL", etiqueta = "Normal", color = "#9DBFE3" },
|
||||
{ clave = "ASC-US", etiqueta = "ASC-US", color = "#2F6DB3" },
|
||||
{ clave = "LIEBG", etiqueta = "LIEBG", color = "#E8C28E" },
|
||||
{ clave = "ASC-H", etiqueta = "ASC-H", color = "#D98E4A" },
|
||||
{ clave = "LIEAG", etiqueta = "LIEAG", color = "#B55A1F" },
|
||||
{ clave = "CIS", etiqueta = "Carcinoma in situ", color = "#7A2E0E" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme. Las seis categorías de CelulasEscamosas (Core); falta decidir si se agrupan (indicadores.md pide cinco como máximo en la figura) y si entran glandulares y carcinoma invasor (I-K61); colores provisionales"
|
||||
|
||||
[cacu.catalogos.resultado_anormal]
|
||||
valor = [
|
||||
{ clave = "NO_ANORMAL", etiqueta = "Sin anomalía", color = "#9DBFE3" },
|
||||
{ clave = "ANORMAL", etiqueta = "Anormal", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme. Anormal es la lista `cacu.citologia_anomala` (la de IND1); colores provisionales"
|
||||
|
||||
# Catálogo de BI-RADS de CaMa (C2). Las claves son las del staging (`mast_birads`).
|
||||
[cama.catalogos.sin_dato]
|
||||
valor = { etiqueta = "Sin dato", color = "#C9CDD2" }
|
||||
estado = "confirmado"
|
||||
fuente = "lista: «sin dato» siempre se muestra como categoría propia"
|
||||
|
||||
[cama.catalogos.birads]
|
||||
valor = [
|
||||
{ clave = "B0", etiqueta = "BI-RADS 0", color = "#8A9199" },
|
||||
{ clave = "B1", etiqueta = "BI-RADS 1", color = "#9DBFE3" },
|
||||
{ clave = "B2", etiqueta = "BI-RADS 2", color = "#2F6DB3" },
|
||||
{ clave = "B3", etiqueta = "BI-RADS 3", color = "#E8C28E" },
|
||||
{ clave = "B4A", etiqueta = "BI-RADS 4A", color = "#E0A060" },
|
||||
{ clave = "B4B", etiqueta = "BI-RADS 4B", color = "#CF7D3C" },
|
||||
{ clave = "B4C", etiqueta = "BI-RADS 4C", color = "#C26A2B" },
|
||||
{ clave = "B5", etiqueta = "BI-RADS 5", color = "#B55A1F" },
|
||||
{ clave = "B6", etiqueta = "BI-RADS 6", color = "#7A2E0E" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). fixture de CaMa (B0, B1, B2, B4). Subcategorías 4A, 4B y 4C: el hospital las reporta y llegan normalizadas (usuario, 2026-10-16). Un 4 sin subcategoría ya no tiene barra fija en 0: si llega alguno, se reporta tal cual después de «Sin dato», como todo valor fuera del catálogo, y sigue contando como sospecha y en BI-RADS 4 a 6 (cama.birads_sospecha, cama.birads_4_a_6). Colores provisionales"
|
||||
|
||||
[cacu.catalogos.biopsia]
|
||||
# Grados histológicos de la biopsia cervical (C2), de menos a más grave. Las claves son las
|
||||
# de `GradoCIN` en Core (`bx_cin_grado`).
|
||||
valor = [
|
||||
{ clave = "NORMAL", etiqueta = "Normal", color = "#9DBFE3" },
|
||||
{ clave = "LIEBG", etiqueta = "LIEBG (CIN 1)", color = "#E8C28E" },
|
||||
{ clave = "LIEAG", etiqueta = "LIEAG (CIN 2 y 3)", color = "#D98E4A" },
|
||||
{ clave = "CIS", etiqueta = "Carcinoma in situ", color = "#B55A1F" },
|
||||
{ clave = "CARCINOMA", etiqueta = "Carcinoma invasor", color = "#7A2E0E" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme. Los grados de GradoCIN (Core) menos DESCONOCIDO, que se reporta tal cual; colores provisionales"
|
||||
|
||||
[cama.catalogos.biopsia]
|
||||
# Grados histológicos de la biopsia de mama (C2), de menos a más grave. Las claves son las de
|
||||
# `GradoHistologicoMama` en Core (`bx_grado_histologico`).
|
||||
valor = [
|
||||
{ clave = "BENIGNO", etiqueta = "Benigno", color = "#9DBFE3" },
|
||||
{ clave = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ", color = "#D98E4A" },
|
||||
{ clave = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor", color = "#7A2E0E" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme. Los grados de GradoHistologicoMama (Core) menos DESCONOCIDO, que se reporta tal cual; colores provisionales"
|
||||
|
||||
[cama.biopsia_cancer]
|
||||
# Grados de la biopsia de mama que cuentan como cáncer: el grupo «anómalo» de CAMA_BIOPSIAS.
|
||||
valor = ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder agrupar, falta que clínica la confirme (usuario, 2026-10-13: par de gráficas de biopsias)"
|
||||
|
||||
[cama.birads_gravedad]
|
||||
# Las categorías de BI-RADS de menos a más grave, para ordenar su presentación. Es el mismo
|
||||
# orden con que CAMA_BIRADS elige la categoría de cada paciente (`GRAVEDAD`, S-M54).
|
||||
valor = ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
|
||||
estado = "provisional"
|
||||
fuente = "S-M54: un BI-RADS 0 (incompleto) pide más estudios y pesa más que uno benigno; falta que clínica lo confirme. Un 4 sin subcategoría pesa menos que 4A (usuario, 2026-10-16)"
|
||||
|
||||
[cama.birads_sospecha]
|
||||
# BI-RADS que piden biopsia: el denominador de CAMA_CONFIRMACION_BIRADS45.
|
||||
valor = ["B4", "B4A", "B4B", "B4C", "B5"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme (usuario, 2026-10-13: «confirmación histopatológica BI-RADS 4/5»). Con las subcategorías 4A, 4B y 4C (usuario, 2026-10-16)"
|
||||
|
||||
[cama.birads_4_a_6]
|
||||
# BI-RADS que cuentan CAMA_BIRADS456_PACIENTE y CAMA_BIRADS456_MASTOGRAFIA: los de sospecha
|
||||
# (4, 5) y la malignidad confirmada (6). No es `birads_sospecha`: ese es el denominador de la
|
||||
# confirmación histopatológica, y un B6 ya está confirmado.
|
||||
valor = ["B4", "B4A", "B4B", "B4C", "B5", "B6"]
|
||||
estado = "provisional"
|
||||
fuente = "Usuario, 2026-10-16: conteos de BI-RADS 4, 5 y 6 por paciente y por mastografía; falta que clínica lo confirme"
|
||||
|
||||
[cama.catalogos.birads_4_a_6]
|
||||
valor = [
|
||||
{ clave = "B4A", etiqueta = "BI-RADS 4A", color = "#E0A060" },
|
||||
{ clave = "B4B", etiqueta = "BI-RADS 4B", color = "#CF7D3C" },
|
||||
{ clave = "B4C", etiqueta = "BI-RADS 4C", color = "#C26A2B" },
|
||||
{ clave = "B5", etiqueta = "BI-RADS 5", color = "#B55A1F" },
|
||||
{ clave = "B6", etiqueta = "BI-RADS 6", color = "#7A2E0E" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Subconjunto de cama.catalogos.birads, con los mismos colores. Sin B4: un 4 sin subcategoría se reporta tal cual después de «Sin dato» (usuario, 2026-10-16)"
|
||||
|
||||
# ===========================================================================
|
||||
# Periodo de observación: desde cuándo hay datos de cada proyecto
|
||||
# ===========================================================================
|
||||
|
||||
[cacu.observacion.inicio_datos]
|
||||
# Primer día del que hay datos cargados. Antes de esa fecha no se sabe qué le pasó a la
|
||||
# paciente: quien se tamizó antes parece nueva. Lo usa el paso `observar`.
|
||||
valor = "2023-01-01"
|
||||
estado = "sin_definir"
|
||||
fuente = "indicadores_kit_0, issues del catálogo de CaCu (I-12): «con historia desde 2023»; falta que quien administra la fuente confirme la fecha de la primera extracción"
|
||||
|
||||
[cama.observacion.inicio_datos]
|
||||
valor = "2023-01-01"
|
||||
estado = "sin_definir"
|
||||
fuente = "Sin fuente propia: se copia el de CaCu para poder correr; falta la fecha de la primera extracción de CaMa"
|
||||
|
||||
[tea.observacion.inicio_datos]
|
||||
valor = "2025-01-01"
|
||||
estado = "confirmado"
|
||||
fuente = "responsable de TEA, 2026-10-21"
|
||||
|
||||
# ===========================================================================
|
||||
# Vínculos entre un resultado y su toma (paso `verificar_vinculos`)
|
||||
# ===========================================================================
|
||||
|
||||
[comun.vinculos.minimo_validos]
|
||||
# Proporción mínima de filas con vínculo válido, de 0 a 1. Solo se exige si la arista se
|
||||
# llama con `exigir=True` (`vinculos_del_proyecto` de webapi.orchestration): por debajo, falla en vez de dejar calcular con vínculos rotos.
|
||||
valor = 0.95
|
||||
estado = "sin_definir"
|
||||
fuente = "Sin decisión: 0.95 es un punto de partida para poder correr; falta medirlo con datos reales"
|
||||
|
||||
# ===========================================================================
|
||||
# Horizontes: una clave por par de eventos (MV-4). Días desde el primer evento en los que
|
||||
# todavía se espera el segundo; el día en que se cumplen ya no se espera.
|
||||
# ===========================================================================
|
||||
|
||||
[cacu.horizontes.toma_reporte_dias]
|
||||
# Días desde la toma en los que todavía se espera el resultado: pasado ese plazo sin
|
||||
# resultado, el estudio ya no está «en observación» y cuenta como excluido de C3r.
|
||||
valor = 60
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme: no hay ventana de monitoreo fijada (usuario, 2026-10-13). S-K85 (indicadores_mvp.md): 60 es el de las pruebas de campo"
|
||||
|
||||
[cama.horizontes.toma_reporte_dias]
|
||||
valor = 60
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta para poder calcular, falta que clínica la confirme: no hay ventana de monitoreo fijada (usuario, 2026-10-13). S-K85 (indicadores_mvp.md): 60 es el de las pruebas de campo"
|
||||
|
||||
[cacu.horizontes.toma_diagnostico_dias]
|
||||
# Días desde la toma en los que una nota de diagnóstico todavía se le atribuye: la primera
|
||||
# nota con un CIE-10 de `cacu.diagnostico.cie` antes de que se cumpla el plazo es su
|
||||
# diagnóstico. Pasado el plazo sin nota, la toma cuenta como excluida de C3r (S-TD4).
|
||||
valor = 180
|
||||
estado = "provisional"
|
||||
fuente = "Arbitrario para poder calcular (usuario, 2026-10-16: «las ventanas de tiempo, dejarlas parametrizadas»); falta que clínica lo fije"
|
||||
|
||||
[cama.horizontes.toma_diagnostico_dias]
|
||||
valor = 180
|
||||
estado = "provisional"
|
||||
fuente = "Arbitrario para poder calcular (usuario, 2026-10-16: «las ventanas de tiempo, dejarlas parametrizadas»); falta que clínica lo fije"
|
||||
|
||||
# ===========================================================================
|
||||
# Diagnóstico: las notas médicas que resuelven una toma y las que son antecedente (S-TD3)
|
||||
# ===========================================================================
|
||||
# Los CIE-10 van sin punto (C53.9 -> C539) y se comparan exactos: cada lista trae el código
|
||||
# de tres caracteres y sus subcategorías. Se cambian aquí sin tocar el código.
|
||||
|
||||
[cacu.diagnostico.cie]
|
||||
# CACU_DIAS_TOMA_DIAGNOSTICO: CIE-10 de la nota que resuelven la toma, sea cual sea el
|
||||
# resultado (usuario, 2026-10-16: «el diagnóstico no necesariamente tiene que ser maligno»):
|
||||
# normal: Z01.4 (examen ginecológico) y Z12.4 (pesquisa de tumor del cuello uterino);
|
||||
# VPH: B97.7 (papilomavirus); citología anormal: R87.6;
|
||||
# lesión escamosa: N87.0, N87.1, N87.2 y N87.9 (displasia cervical leve, moderada, grave
|
||||
# y sin especificar);
|
||||
# cáncer: D06 (carcinoma in situ) y C53 (tumor maligno del cuello del útero).
|
||||
valor = [
|
||||
"Z014", "Z124",
|
||||
"B977", "R876",
|
||||
"N87", "N870", "N871", "N872", "N879",
|
||||
"D06", "D060", "D061", "D067", "D069",
|
||||
"C53", "C530", "C531", "C538", "C539",
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles"
|
||||
|
||||
[cacu.diagnostico.cie_antecedente]
|
||||
# Una nota con uno de estos CIE-10 anterior a la toma deja fuera la toma: la paciente ya es
|
||||
# un caso (S-TD2). Solo la incidencia, D06 y C53: con la lista amplia, cualquier consulta
|
||||
# previa sacaría a la paciente del tamizaje.
|
||||
valor = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles"
|
||||
|
||||
[cacu.diagnostico.especialidades]
|
||||
# Las especialidades (código de `Core`, `nota_medica.enums.Especialidad`) cuyas notas
|
||||
# resuelven la toma: las que dan el diagnóstico, no medicina familiar.
|
||||
valor = ["CLINICA_MUJER_COLPOSCOPIA", "CIRUGIA_ONCOLOGICA"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles"
|
||||
|
||||
[cama.diagnostico.cie]
|
||||
# CAMA_DIAS_TOMA_DIAGNOSTICO: CIE-10 de la nota que resuelven la toma, sea cual sea el resultado:
|
||||
# normal: Z12.3 (pesquisa de tumor de la mama);
|
||||
# benignos: N60 (displasia mamaria benigna), N61 a N64 (otros trastornos de la mama) y
|
||||
# D24 (tumor benigno de la mama);
|
||||
# imagen anormal: R92;
|
||||
# cáncer: D05 (carcinoma in situ) y C50 (tumor maligno de la mama).
|
||||
valor = [
|
||||
"Z123",
|
||||
"N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609",
|
||||
"N61", "N62", "N63",
|
||||
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649",
|
||||
"D24", "R92",
|
||||
"D05", "D050", "D051", "D057", "D059",
|
||||
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles"
|
||||
|
||||
[cama.diagnostico.cie_antecedente]
|
||||
# Como en CaCu: solo la incidencia, D05 y C50.
|
||||
valor = [
|
||||
"D05", "D050", "D051", "D057", "D059",
|
||||
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles"
|
||||
|
||||
[cama.diagnostico.especialidades]
|
||||
# El catálogo de `Core` no tiene una clínica de mama: queda cirugía oncológica.
|
||||
valor = ["CIRUGIA_ONCOLOGICA"]
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta provisional del asistente, aceptada por el usuario (2026-10-16: «usa tus códigos provisionales, de modo tal que después sean intercambiables»); falta que clínica la confirme. dev-data compartirá un enum con los códigos disponibles"
|
||||
@@ -1,154 +0,0 @@
|
||||
"""`dim_periodo`: una sola definición de a qué periodo pertenece una fecha.
|
||||
|
||||
Se genera, no se escribe a mano ni se calcula con `strftime` en cada SQL
|
||||
(ADR-003 §9, regla 4). Cada periodo es el intervalo `[inicio, fin)`.
|
||||
|
||||
Hay un tipo por granularidad (S-M4, T-1 de v0.4.0); el `periodo_id` dice
|
||||
el tipo y ordena bien como texto:
|
||||
|
||||
dia 2025-03-05 un día
|
||||
semana_epidemiologica 2025-SE10 domingo a domingo
|
||||
semana_habil 2025-SH10 lunes a sábado: los cinco días hábiles
|
||||
semana_iso 2025-W10 lunes a lunes, ISO 8601
|
||||
mes 2025-03
|
||||
bimestre 2025-B2 enero-febrero = B1
|
||||
trimestre 2025-T1 enero-marzo = T1
|
||||
semestre 2025-S1 enero-junio = S1
|
||||
|
||||
`anio` es el año del periodo; en las semanas, el año de la semana, que
|
||||
puede empezar en diciembre del anterior. `semestre` es el semestre que
|
||||
contiene el inicio del periodo.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.indicadores.registro import DimPeriodoBase
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
Generador = Callable[[type[DimPeriodoBase], int], list[DimPeriodoBase]]
|
||||
|
||||
|
||||
class TipoDePeriodoDesconocido(ValueError):
|
||||
"""Se pidió un tipo de periodo que el kit no sabe generar."""
|
||||
|
||||
|
||||
def semestres(anio_inicio: int, anio_fin: int, *, tablas: TablasKit) -> list[DimPeriodoBase]:
|
||||
"""Los semestres de `anio_inicio` a `anio_fin`, los dos incluidos."""
|
||||
return periodos("semestre", anio_inicio, anio_fin, tablas=tablas)
|
||||
|
||||
|
||||
def periodos(
|
||||
tipo: str, anio_inicio: int, anio_fin: int, *, tablas: TablasKit
|
||||
) -> list[DimPeriodoBase]:
|
||||
"""Los periodos de un tipo cuyo año va de `anio_inicio` a `anio_fin`, los dos incluidos."""
|
||||
if tipo not in _GENERADORES:
|
||||
raise TipoDePeriodoDesconocido(
|
||||
f"No hay periodos de tipo {tipo!r}; los tipos son {', '.join(TIPOS_PERIODO)}."
|
||||
)
|
||||
generar = _GENERADORES[tipo]
|
||||
return [
|
||||
fila for anio in range(anio_inicio, anio_fin + 1) for fila in generar(tablas.DimPeriodo, anio)
|
||||
]
|
||||
|
||||
|
||||
def periodos_de_tipos(
|
||||
tipos: Iterable[str], anio_inicio: int, anio_fin: int, *, tablas: TablasKit
|
||||
) -> list[DimPeriodoBase]:
|
||||
"""Los periodos de varios tipos, uno tras otro. Los `periodo_id` no chocan entre tipos."""
|
||||
return [fila for tipo in tipos for fila in periodos(tipo, anio_inicio, anio_fin, tablas=tablas)]
|
||||
|
||||
|
||||
def inicio_semana_epidemiologica(anio: int) -> date:
|
||||
"""El domingo en que empieza la semana epidemiológica 1 de `anio`.
|
||||
|
||||
La semana 1 es la primera que tiene al menos cuatro días en el año
|
||||
(regla de la Secretaría de Salud y del CDC): la que contiene el 4 de
|
||||
enero. Puede empezar entre el 29 de diciembre y el 4 de enero.
|
||||
"""
|
||||
cuatro_de_enero = date(anio, 1, 4)
|
||||
return cuatro_de_enero - timedelta(days=(cuatro_de_enero.weekday() + 1) % 7)
|
||||
|
||||
|
||||
def _fila(
|
||||
modelo: type[DimPeriodoBase], periodo_id: str, tipo: str, inicio: date, fin: date, anio: int
|
||||
) -> DimPeriodoBase:
|
||||
return modelo(
|
||||
periodo_id=periodo_id,
|
||||
tipo=tipo,
|
||||
inicio=inicio,
|
||||
fin=fin,
|
||||
anio=anio,
|
||||
semestre=1 if inicio.month <= 6 else 2,
|
||||
)
|
||||
|
||||
|
||||
def _dias(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]:
|
||||
primero, siguiente = date(anio, 1, 1), date(anio + 1, 1, 1)
|
||||
return [
|
||||
_fila(modelo, dia.isoformat(), "dia", dia, dia + timedelta(days=1), anio)
|
||||
for dia in (primero + timedelta(days=n) for n in range((siguiente - primero).days))
|
||||
]
|
||||
|
||||
|
||||
def _por_meses(meses: int, tipo: str, prefijo: str) -> Generador:
|
||||
"""Los periodos de `meses` meses que parten el año desde enero."""
|
||||
|
||||
def generar(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]:
|
||||
filas = []
|
||||
for numero in range(1, 12 // meses + 1):
|
||||
mes = (numero - 1) * meses + 1
|
||||
inicio = date(anio, mes, 1)
|
||||
fin = date(anio + 1, 1, 1) if mes + meses > 12 else date(anio, mes + meses, 1)
|
||||
periodo_id = f"{anio}-{numero:02d}" if not prefijo else f"{anio}-{prefijo}{numero}"
|
||||
filas.append(_fila(modelo, periodo_id, tipo, inicio, fin, anio))
|
||||
return filas
|
||||
|
||||
return generar
|
||||
|
||||
|
||||
def _semanas(
|
||||
tipo: str, prefijo: str, inicio_del_anio: Callable[[int], date], dias_desde_el_inicio: tuple[int, int]
|
||||
) -> Generador:
|
||||
"""Las semanas de un año: de `inicio_del_anio(anio)` al de `anio + 1`, de siete en siete.
|
||||
|
||||
`dias_desde_el_inicio` recorta cada semana: (0, 7) es la semana entera;
|
||||
(1, 6), de lunes a sábado en una semana que empieza en domingo.
|
||||
"""
|
||||
desde, hasta = dias_desde_el_inicio
|
||||
|
||||
def generar(modelo: type[DimPeriodoBase], anio: int) -> list[DimPeriodoBase]:
|
||||
primera, siguiente = inicio_del_anio(anio), inicio_del_anio(anio + 1)
|
||||
return [
|
||||
_fila(
|
||||
modelo,
|
||||
f"{anio}-{prefijo}{numero:02d}",
|
||||
tipo,
|
||||
semana + timedelta(days=desde),
|
||||
semana + timedelta(days=hasta),
|
||||
anio,
|
||||
)
|
||||
for numero, semana in enumerate(
|
||||
(primera + timedelta(weeks=n) for n in range((siguiente - primera).days // 7)),
|
||||
start=1,
|
||||
)
|
||||
]
|
||||
|
||||
return generar
|
||||
|
||||
|
||||
_GENERADORES: dict[str, Generador] = {
|
||||
"dia": _dias,
|
||||
"semana_epidemiologica": _semanas("semana_epidemiologica", "SE", inicio_semana_epidemiologica, (0, 7)),
|
||||
# La semana hábil lleva el número y el año de la epidemiológica que la contiene (S-M7).
|
||||
"semana_habil": _semanas("semana_habil", "SH", inicio_semana_epidemiologica, (1, 6)),
|
||||
"semana_iso": _semanas("semana_iso", "W", lambda anio: date.fromisocalendar(anio, 1, 1), (0, 7)),
|
||||
"mes": _por_meses(1, "mes", ""),
|
||||
"bimestre": _por_meses(2, "bimestre", "B"),
|
||||
"trimestre": _por_meses(3, "trimestre", "T"),
|
||||
"semestre": _por_meses(6, "semestre", "S"),
|
||||
}
|
||||
|
||||
TIPOS_PERIODO = tuple(_GENERADORES)
|
||||
@@ -1,101 +0,0 @@
|
||||
"""Registro L2 de parámetros: `parametros.toml` cargado en `def_parametro`.
|
||||
|
||||
El archivo en git es la única fuente de verdad. La tabla se reconstruye
|
||||
entera en cada carga; nadie la edita a mano (ADR-003 §9).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from core.indicadores.registro import DefParametroBase
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
# Un solo archivo para todos los proyectos, dentro del paquete.
|
||||
RUTA_PARAMETROS = Path(__file__).resolve().parent / "parametros.toml"
|
||||
ESTADOS_PARAMETRO = ("sin_definir", "provisional", "confirmado")
|
||||
|
||||
|
||||
class ParametroSinDefinir(LookupError):
|
||||
"""Se pidió un parámetro que nadie ha decidido todavía."""
|
||||
|
||||
|
||||
def leer_parametros(ruta: Path, *, tablas: TablasKit) -> list[DefParametroBase]:
|
||||
"""Lee el archivo y devuelve una fila por parámetro, ya validada.
|
||||
|
||||
Un parámetro es una tabla con algún valor que no es tabla; su clave es
|
||||
la ruta de secciones con puntos: `[tea.cohorte.edad_min_meses]` da
|
||||
`"tea.cohorte.edad_min_meses"`. Una tabla sin esas llaves es una
|
||||
sección más.
|
||||
"""
|
||||
contenido = Path(ruta).read_bytes()
|
||||
toml_sha = hashlib.sha256(contenido).hexdigest()
|
||||
secciones = tomllib.loads(contenido.decode("utf-8"))
|
||||
return [
|
||||
_a_fila(tablas.DefParametro, clave, parametro, toml_sha)
|
||||
for clave, parametro in _parametros_de(secciones)
|
||||
]
|
||||
|
||||
|
||||
def valores_del_archivo(ruta: Path = RUTA_PARAMETROS) -> dict:
|
||||
"""Clave -> valor de cada parámetro del archivo, sin estado ni base.
|
||||
|
||||
Para quien necesita una regla antes de que exista `def_parametro`
|
||||
(los antecedentes de TEA, al cargar). No comprueba el estado.
|
||||
"""
|
||||
secciones = tomllib.loads(Path(ruta).read_text(encoding="utf-8"))
|
||||
return {clave: parametro.get("valor") for clave, parametro in _parametros_de(secciones)}
|
||||
|
||||
|
||||
def valor_de(
|
||||
sesion: Session, clave: str, *, tablas: TablasKit, permitir_sin_definir: bool = False
|
||||
):
|
||||
"""El valor de un parámetro.
|
||||
|
||||
Un parámetro `sin_definir` trae un valor que solo permite correr: hay que pedirlo a propósito con `permitir_sin_definir=True`.
|
||||
"""
|
||||
fila = sesion.get(tablas.DefParametro, clave)
|
||||
if fila is None:
|
||||
raise KeyError(f"No existe el parámetro {clave!r}.")
|
||||
if fila.estado == "sin_definir" and not permitir_sin_definir:
|
||||
raise ParametroSinDefinir(
|
||||
f"El parámetro {clave!r} está sin definir ({fila.fuente})."
|
||||
)
|
||||
return json.loads(fila.valor)
|
||||
|
||||
|
||||
def _parametros_de(seccion: dict, ruta: tuple[str, ...] = ()):
|
||||
"""(clave, tabla) de cada parámetro, en el orden del archivo."""
|
||||
for nombre, contenido in seccion.items():
|
||||
if not isinstance(contenido, dict):
|
||||
raise ValueError(f"{'.'.join(ruta) or 'El archivo'}: {nombre!r} no es una sección.")
|
||||
# Una sección solo tiene tablas; un parámetro tiene al menos un valor suelto
|
||||
# (`estado`, `fuente`). Así una sección se puede llamar `fuente`.
|
||||
if not all(isinstance(valor, dict) for valor in contenido.values()):
|
||||
yield ".".join((*ruta, nombre)), contenido
|
||||
else:
|
||||
yield from _parametros_de(contenido, (*ruta, nombre))
|
||||
|
||||
|
||||
def _a_fila(
|
||||
modelo: type[DefParametroBase], clave: str, parametro: dict, toml_sha: str
|
||||
) -> DefParametroBase:
|
||||
# Solo un parámetro sin definir puede no tener valor todavía.
|
||||
obligatorias = {"estado", "fuente"} | (
|
||||
set() if parametro.get("estado") == "sin_definir" else {"valor"}
|
||||
)
|
||||
faltan = obligatorias - set(parametro)
|
||||
if faltan:
|
||||
raise ValueError(f"Al parámetro {clave!r} le falta {sorted(faltan)}.")
|
||||
if parametro["estado"] not in ESTADOS_PARAMETRO:
|
||||
raise ValueError(f"Parámetro {clave!r}: estado desconocido {parametro['estado']!r}.")
|
||||
return modelo(
|
||||
clave=clave,
|
||||
valor=json.dumps(parametro.get("valor"), ensure_ascii=False),
|
||||
estado=parametro["estado"],
|
||||
fuente=parametro["fuente"],
|
||||
toml_sha=toml_sha,
|
||||
)
|
||||
@@ -1,38 +0,0 @@
|
||||
"""Las tablas de apoyo que salen de los TOML (I-MD27, T-24f): `dim_fecha` y `dim_grupo_edad`.
|
||||
|
||||
Las usan los estratos que cruzan fechas (`grupo_edad`: la edad cumplida, portable entre
|
||||
SQLite y Postgres). Las escribe la arista `registro` de webapi.orchestration; aquí solo se arman:
|
||||
|
||||
filas_de_dim_fecha de `comun.dim_fecha.desde` a `hasta`, como diccionarios para un
|
||||
INSERT en bloque (se arman una vez por proceso: son decenas de miles)
|
||||
grupos_de_edad_de los grupos de `<proyecto>.grupos_edad`, o `None` si el proyecto no
|
||||
tiene cortes (TEA)
|
||||
|
||||
`comun.dim_fecha.desde` es fijo porque `dia_num` y `dia_habil_num` se cuentan desde él.
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import date
|
||||
from functools import lru_cache
|
||||
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.dates import dias
|
||||
from webapi.orchestration.tables import TablasKit, tablas_de
|
||||
|
||||
CLAVE_DIM_FECHA_DESDE = "comun.dim_fecha.desde"
|
||||
|
||||
|
||||
def filas_de_dim_fecha(valores: Mapping, hasta: date, *, proyecto: str) -> list[dict]:
|
||||
"""Los días de `comun.dim_fecha.desde` a `hasta`, como diccionarios de `dim_fecha`."""
|
||||
return list(_dias(date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE]), hasta, proyecto))
|
||||
|
||||
|
||||
def grupos_de_edad_de(proyecto: str, valores: Mapping, *, tablas: TablasKit) -> list | None:
|
||||
"""Los grupos de edad de `<proyecto>.grupos_edad` (más los dos abiertos), o `None` si no tiene cortes."""
|
||||
cortes = valores.get(f"{proyecto}.grupos_edad")
|
||||
return None if cortes is None else grupos_de_cortes(cortes, tablas=tablas)
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def _dias(desde: date, hasta: date, proyecto: str) -> tuple[dict, ...]:
|
||||
return tuple(fila.model_dump() for fila in dias(desde, hasta, tablas=tablas_de(proyecto)))
|
||||
@@ -1,95 +0,0 @@
|
||||
"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro.
|
||||
|
||||
Las subclases viven en `persistance/edges/<capa>/` y se
|
||||
instancian en `persistance/<proyecto>/__init__.py` con la fábrica de sesión del
|
||||
dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
PublicationRepository,
|
||||
ReferenceRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
TimelineRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.materializer import Materializer
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bronze:
|
||||
"""Lo que deja la ingesta. Solo se lee."""
|
||||
|
||||
staging: StagingRepository
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Silver:
|
||||
"""Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata."""
|
||||
|
||||
catalogs: CatalogRepository
|
||||
loads: LoadRepository
|
||||
views: ViewsRepository
|
||||
observation: ObservationRepository
|
||||
links: LinksRepository
|
||||
timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Gold:
|
||||
"""El registro (parámetros, periodos, definiciones), los reportes y las cohortes."""
|
||||
|
||||
parameters: ReferenceRepository
|
||||
periods: ReferenceRepository
|
||||
calculation: CalculationRepository
|
||||
publication: PublicationRepository # el catálogo de publicación de §6f (T-19b)
|
||||
cohorts: CohortRepository | None # donde hay tablas de cohortes (los tres desde MD-12)
|
||||
dates: ReferenceRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27)
|
||||
age_groups: ReferenceRepository | None = None # `dim_grupo_edad`, de `<proyecto>.grupos_edad` (I-MD27)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Repositories:
|
||||
"""Todo lo que un paso usa para tocar la base de su proyecto, por capa."""
|
||||
|
||||
bronze: Bronze
|
||||
silver: Silver
|
||||
gold: Gold
|
||||
# Una sesión para leer y escribir en el mismo paso (`load`).
|
||||
materializer: Materializer | None = None
|
||||
|
||||
|
||||
def repositories_of(proyecto: str) -> Repositories:
|
||||
dominio = import_module(f"persistance.{proyecto}")
|
||||
return Repositories(
|
||||
bronze=Bronze(staging=dominio.staging_repository),
|
||||
silver=Silver(
|
||||
catalogs=dominio.catalog_repository,
|
||||
loads=dominio.carga_repository,
|
||||
views=dominio.views_repository,
|
||||
observation=dominio.observation_period_repository,
|
||||
links=dominio.links_repository,
|
||||
timeline=dominio.timeline_repository,
|
||||
),
|
||||
materializer=dominio.materializer,
|
||||
gold=Gold(
|
||||
parameters=dominio.def_parametro_repository,
|
||||
periods=dominio.dim_periodo_repository,
|
||||
calculation=dominio.calculation_repository,
|
||||
publication=dominio.publication_repository,
|
||||
cohorts=getattr(dominio, "cohort_repository", None),
|
||||
dates=getattr(dominio, "dim_fecha_repository", None),
|
||||
age_groups=getattr(dominio, "dim_grupo_edad_repository", None),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
"""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]
|
||||
@@ -1,10 +0,0 @@
|
||||
"""La plata de dos tablas (F5, ADR-MD-007): de staging a `persona`, `procedimiento` y `observacion_clinica`.
|
||||
|
||||
procedimiento.py `DeStaging`, `plata_desde_staging` y el orden de escritura por padres
|
||||
carga.py `carga_desde_staging`: de las filas de staging a las personas y la plata
|
||||
valores.py las normalizaciones de un valor de staging
|
||||
personas.py de una fila de pacientes a `persona`
|
||||
ordenes_y_notas.py la orden de estudio y la nota médica de CaCu y CaMa
|
||||
periodo_observacion.py desde y hasta cuándo hay datos de cada paciente
|
||||
vistas.py la DDL de `v_persona`
|
||||
"""
|
||||
@@ -1,69 +0,0 @@
|
||||
"""CaCu en la plata de dos tablas (ADR-MD-007), por staging directo (T-20c, ADR-MD-009).
|
||||
|
||||
`DESDE_STAGING`: qué procedimientos salen de cada fila de staging, con la normalización como columnas
|
||||
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
|
||||
"""
|
||||
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente
|
||||
from core.cacu.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
|
||||
|
||||
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
|
||||
|
||||
PACIENTES = Paciente # de donde salen las personas
|
||||
ESPECIALIDADES = {e.value for e in Especialidad}
|
||||
LA_TOMA_DE_SU_FILA = Padre(estudio_id="citologia", clase="toma", fuente_id="cit_id", tabla=CitologiaCervical.__tablename__)
|
||||
LA_ORDEN_DEL_ESTUDIO = Padre(por_numero_de_orden="ord_numero_hospital")
|
||||
|
||||
|
||||
def _genotipo_16_18(fila):
|
||||
genotipos = (fila.cit_vph_genotipo_16, fila.cit_vph_genotipo_18)
|
||||
return None if genotipos == (None, None) else int(any(genotipos))
|
||||
|
||||
|
||||
# La biopsia (T-22h, I-MD23): solicitada, es una `orden` del estudio `biopsia` que cuelga de la toma que la
|
||||
# originó; su reporte llega después como hija `reporte`, sin reescribir la orden. Pasa de staging solo lo
|
||||
# realizado: la que trae fecha de solicitud o de reporte. Con reporte y sin solicitud, la orden queda sin fecha.
|
||||
def _biopsia_que_pasa(fila) -> bool:
|
||||
return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None
|
||||
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
CitologiaCervical, "cit_id", "toma", estudio_id="citologia", fecha="cit_fecha_toma",
|
||||
padres=(LA_ORDEN_DEL_ESTUDIO,), columnas={"orden_numero": "ord_numero_hospital"},
|
||||
resultados={"cit_calidad_especimen": "citologia.calidad_muestra"},
|
||||
),
|
||||
# Un resultado sin fecha de reporte todavía no es un resultado: la fila no da reporte.
|
||||
DeStaging(
|
||||
CitologiaCervical, "cit_id", "reporte", estudio_id="citologia", fecha="cit_fecha_reporte",
|
||||
solo_si=lambda f: f.cit_fecha_reporte is not None, padres=(LA_TOMA_DE_SU_FILA,),
|
||||
resultados={
|
||||
"cit_celulas_escamosas": "citologia.bethesda",
|
||||
"cit_celulas_glandulares": "citologia.celulas_glandulares",
|
||||
"cit_carcinoma_invasor": "citologia.carcinoma_invasor",
|
||||
"cit_dx_lesion": "citologia.dx_lesion",
|
||||
},
|
||||
),
|
||||
# El VPH de la misma muestra, si se hizo; con la fecha del reporte de la citología (S-K38).
|
||||
DeStaging(
|
||||
CitologiaCervical, "cit_id", "reporte", estudio_id="vph", fecha="cit_fecha_reporte",
|
||||
solo_si=lambda f: f.cit_fecha_reporte is not None and f.cit_vph_resultado is not None,
|
||||
padres=(LA_TOMA_DE_SU_FILA,), derivadas={"genotipo_16_18": _genotipo_16_18},
|
||||
resultados={
|
||||
"cit_vph_resultado": "vph.resultado",
|
||||
"genotipo_16_18": "vph.genotipo_16_18",
|
||||
"cit_vph_genotipo_16": "vph.genotipo_16",
|
||||
"cit_vph_genotipo_18": "vph.genotipo_18",
|
||||
},
|
||||
),
|
||||
DeStaging(
|
||||
BiopsiaCervical, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
|
||||
solo_si=_biopsia_que_pasa, padres=(LA_TOMA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
|
||||
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
|
||||
resultados={"bx_cin_grado": "biopsia.grado"}),),
|
||||
),
|
||||
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
|
||||
# El motivo de consulta y el diagnóstico en texto: de ahí sale la colposcopia del estatus de seguimiento (T-24b, T-24c).
|
||||
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, con_textos=True),
|
||||
)
|
||||
@@ -1,46 +0,0 @@
|
||||
"""CaMa en la plata de dos tablas (ADR-MD-007), por staging directo (T-20c, ADR-MD-009).
|
||||
|
||||
`DESDE_STAGING`: qué procedimientos salen de cada fila de staging, con la normalización como columnas
|
||||
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
|
||||
"""
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
|
||||
|
||||
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
|
||||
|
||||
PACIENTES = Paciente # de donde salen las personas
|
||||
ESPECIALIDADES = {e.value for e in Especialidad}
|
||||
# La toma de un resultado: la mastografía de su fila (BI-RADS) o la que la originó (`mast_id` de la biopsia).
|
||||
LA_MASTOGRAFIA_DE_SU_FILA = Padre(estudio_id="mastografia", clase="toma", fuente_id="mast_id", tabla=Mastografia.__tablename__)
|
||||
LA_ORDEN_DEL_ESTUDIO = Padre(por_numero_de_orden="ord_numero_hospital")
|
||||
|
||||
# La biopsia (T-22h, I-MD23): solicitada, es una `orden` del estudio `biopsia` que cuelga de la toma que la
|
||||
# originó; su reporte llega después como hija `reporte`, sin reescribir la orden. Pasa de staging solo lo
|
||||
# realizado: la que trae fecha de solicitud o de reporte. Con reporte y sin solicitud, la orden queda sin fecha.
|
||||
def _biopsia_que_pasa(fila) -> bool:
|
||||
return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None
|
||||
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
|
||||
padres=(LA_ORDEN_DEL_ESTUDIO,), columnas={"orden_numero": "ord_numero_hospital"},
|
||||
resultados={"mast_calidad_imagen": "mastografia.calidad_imagen"},
|
||||
),
|
||||
# Un resultado sin fecha de reporte todavía no es un resultado.
|
||||
DeStaging(
|
||||
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
|
||||
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
|
||||
resultados={"mast_birads": "mastografia.birads"},
|
||||
),
|
||||
DeStaging(
|
||||
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
|
||||
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
|
||||
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
|
||||
resultados={"bx_grado_histologico": "biopsia.grado"}),),
|
||||
),
|
||||
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
|
||||
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
|
||||
)
|
||||
@@ -1,47 +0,0 @@
|
||||
"""La carga del staging directo (T-20c): de las filas de staging a las personas y la plata. Pura.
|
||||
|
||||
En un paso: las personas salen de la tabla de pacientes del proyecto (`<p>/plata.PACIENTES`)
|
||||
y los procedimientos y observaciones, de `<p>/plata.DESDE_STAGING`. Lo escribe Persistance
|
||||
(`guardar_carga_en`) por el modelo `carga` de webapi.orchestration.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable, Mapping
|
||||
from importlib import import_module
|
||||
from typing import NamedTuple
|
||||
|
||||
from webapi.orchestration.silver.persons import a_persona
|
||||
from webapi.orchestration.silver.procedures import LotePlata, plata_desde_staging
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, codigos_hospital, ruta_de_catalogo
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
|
||||
class CargaDesdeStaging(NamedTuple):
|
||||
fuente: str # las tablas de staging que dan procedimientos, en el orden de `DESDE_STAGING`
|
||||
personas: list
|
||||
plata: LotePlata
|
||||
|
||||
|
||||
def _plata(proyecto: str):
|
||||
return import_module(f"webapi.orchestration.silver.{proyecto}")
|
||||
|
||||
|
||||
|
||||
def tablas_de_staging(proyecto: str) -> tuple[type, ...]:
|
||||
"""Las tablas de staging que lee la carga: la de pacientes y las de `DESDE_STAGING`, sin repetir."""
|
||||
plata = _plata(proyecto)
|
||||
return (plata.PACIENTES, *dict.fromkeys(c.staging for c in plata.DESDE_STAGING))
|
||||
|
||||
|
||||
def carga_desde_staging(filas: Mapping[str, Iterable], *, proyecto: str) -> CargaDesdeStaging:
|
||||
"""Las personas y la plata de un proyecto, desde sus filas de staging (tabla -> filas)."""
|
||||
plata = _plata(proyecto)
|
||||
tablas = tablas_de(proyecto)
|
||||
lote = plata_desde_staging(
|
||||
filas, correspondencias=plata.DESDE_STAGING,
|
||||
catalogo=catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas),
|
||||
codigos_hospital=codigos_hospital(proyecto),
|
||||
pacientes=(p.pac_id for p in filas.get(plata.PACIENTES.__tablename__, ())),
|
||||
)
|
||||
personas = [a_persona(paciente, tablas=tablas) for paciente in filas.get(plata.PACIENTES.__tablename__, ())]
|
||||
fuente = ", ".join(dict.fromkeys(c.staging.__tablename__ for c in plata.DESDE_STAGING))
|
||||
return CargaDesdeStaging(fuente, personas, lote)
|
||||
@@ -1,97 +0,0 @@
|
||||
"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente.
|
||||
|
||||
Un indicador que mira hacia atrás (¿es su primera citología?) o hacia
|
||||
adelante (¿llegó la biopsia?) necesita saber cuánto se pudo observar a la
|
||||
paciente. Sin eso, quien se tamizó antes de que empezaran los datos
|
||||
parece nueva, y a quien se tamizó ayer parece que no le llegó nada.
|
||||
|
||||
El periodo es el de la extracción: empieza el día que dice la regla
|
||||
`<proyecto>.observacion.inicio_datos` y termina en la fecha de corte (la
|
||||
de la última carga, si no se da otra). Es el mismo para todas las
|
||||
pacientes; la tabla es por paciente para cuando haya una fuente mejor
|
||||
(alta y baja de la derechohabiencia). Aquí se calculan las filas; las escribe
|
||||
`ObservacionRepository` de Persistance (plata), en la arista `observar`.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from webapi.orchestration.reference.rules import ParametroSinDefinir
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
TIPO_EXTRACCION = "extraccion"
|
||||
|
||||
|
||||
class ObservacionSinCorte(ValueError):
|
||||
"""No se dio fecha de corte y no hay ninguna carga de donde tomarla."""
|
||||
|
||||
|
||||
def clave_de_inicio(proyecto: str) -> str:
|
||||
"""La regla que dice desde cuándo hay datos del proyecto."""
|
||||
return f"{proyecto}.observacion.inicio_datos"
|
||||
|
||||
|
||||
def periodos_de_observacion(
|
||||
sesion: Session, proyecto: str, *, corte: date | None = None, permitir_sin_definir: bool = False
|
||||
) -> list:
|
||||
"""Las filas de `periodo_observacion`: un periodo de extracción por persona. Solo lee.
|
||||
|
||||
Necesita las personas (la carga) y la regla en `def_parametro` (el registro).
|
||||
`corte` es el último día observado; sin él, el de la última carga. Una regla
|
||||
sin definir hay que pedirla a propósito, como en el cálculo.
|
||||
|
||||
Raises:
|
||||
KeyError: la regla no está en `def_parametro`.
|
||||
ParametroSinDefinir: la regla está sin definir y no se pidió permitirla.
|
||||
ObservacionSinCorte: no hay corte ni cargas.
|
||||
ValueError: el corte es anterior al inicio de los datos.
|
||||
"""
|
||||
tablas = tablas_de(proyecto)
|
||||
clave = clave_de_inicio(proyecto)
|
||||
inicio = _inicio(clave, sesion.get(tablas.DefParametro, clave), permitir_sin_definir)
|
||||
corte = _corte(fecha_de_ultima_carga(sesion, tablas) if corte is None else corte, inicio)
|
||||
personas = sesion.exec(select(tablas.Persona).order_by(tablas.Persona.pac_id)).all()
|
||||
return _periodos(tablas, inicio, corte, personas)
|
||||
|
||||
|
||||
def _inicio(clave: str, regla, permitir_sin_definir: bool) -> date:
|
||||
if regla is None:
|
||||
raise KeyError(f"No existe el parámetro {clave!r}: corra la arista `registro`.")
|
||||
if regla.estado == "sin_definir" and not permitir_sin_definir:
|
||||
raise ParametroSinDefinir(f"El parámetro {clave!r} está sin definir ({regla.fuente}).")
|
||||
return date.fromisoformat(json.loads(regla.valor))
|
||||
|
||||
|
||||
def _corte(corte, inicio: date) -> date:
|
||||
if corte is None:
|
||||
raise ObservacionSinCorte("No se dio corte y no hay ninguna carga de donde tomarlo.")
|
||||
corte = a_fecha(corte)
|
||||
if corte < inicio:
|
||||
raise ValueError(f"El corte ({corte}) es anterior al inicio de los datos ({inicio}).")
|
||||
return corte
|
||||
|
||||
|
||||
def _periodos(tablas, inicio: date, corte: date, personas) -> list:
|
||||
return [
|
||||
tablas.PeriodoObservacion(
|
||||
pac_id=persona.pac_id, fecha_inicio=inicio, fecha_fin=corte, tipo_periodo=TIPO_EXTRACCION
|
||||
)
|
||||
for persona in personas
|
||||
]
|
||||
|
||||
|
||||
def fecha_de_ultima_carga(sesion: Session, tablas) -> date | None:
|
||||
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
|
||||
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
|
||||
return None if ultima is None else a_fecha(ultima)
|
||||
|
||||
|
||||
def a_fecha(valor) -> date:
|
||||
"""A date however the engine returns it: text, date or date-time."""
|
||||
if isinstance(valor, datetime):
|
||||
return valor.date()
|
||||
if isinstance(valor, date):
|
||||
return valor
|
||||
return date.fromisoformat(str(valor)[:10])
|
||||
@@ -1,73 +0,0 @@
|
||||
"""La orden de estudio y la nota médica de CaCu y CaMa en el staging directo (T-20c).
|
||||
|
||||
El staging de los dos proyectos trae las mismas columnas (`ordenesestudio`, `notamedica`); cada uno
|
||||
da sus tablas y su catálogo de especialidades. Es la normalización que hacían `cdm/ordenes.py` y
|
||||
`cdm/notas.py`, como columnas derivadas:
|
||||
- una orden es lo que se pidió, se haya hecho o no; sin ninguna fecha no es una orden, y su fecha es
|
||||
la de emisión o, si falta, la de solicitud;
|
||||
- la especialidad se guarda en el código de Core (nula si no se reconoce) y, como `valor_fuente`, tal
|
||||
como llegó;
|
||||
- el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`;
|
||||
- el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b),
|
||||
sin normalizarlos (I-K61).
|
||||
"""
|
||||
|
||||
from collections.abc import Collection, Mapping
|
||||
|
||||
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
|
||||
from webapi.orchestration.silver.procedures import DeStaging
|
||||
|
||||
|
||||
def especialidad(columna: str, alias: Mapping[str, str], codigos: Collection[str]) -> dict:
|
||||
"""Las derivadas de una especialidad: su código en Core y el texto tal como llegó."""
|
||||
return {
|
||||
"especialidad": lambda f: codigo_de_especialidad(getattr(f, columna), alias, codigos),
|
||||
"especialidad_fuente": lambda f: texto_limpio(getattr(f, columna)),
|
||||
}
|
||||
|
||||
|
||||
def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collection[str]) -> DeStaging:
|
||||
return DeStaging(
|
||||
staging, "ord_id", "orden", estudio_de="tipo_estudio", fecha="fecha_orden",
|
||||
solo_si=lambda f: (f.ord_fecha or f.ord_fecha_solicitud) is not None,
|
||||
derivadas={
|
||||
"tipo_estudio": lambda f: texto_limpio(f.ord_tipo_estudio),
|
||||
"fecha_orden": lambda f: f.ord_fecha or f.ord_fecha_solicitud,
|
||||
"intencion": lambda f: INTENCION,
|
||||
"estatus": lambda f: texto_limpio(f.ord_estatus),
|
||||
"diagnostico": lambda f: texto_limpio(f.ord_diagnostico),
|
||||
**especialidad("ord_especialidad", alias, codigos),
|
||||
},
|
||||
columnas={"numero_hospital": "ord_numero_hospital", "codigo_fuente": "ord_tipo_estudio"},
|
||||
resultados={
|
||||
"intencion": "orden.intencion",
|
||||
"ord_fecha_solicitud": "orden.fecha_solicitud",
|
||||
"ord_fecha_resultado": "orden.fecha_resultado",
|
||||
"estatus": "orden.estatus",
|
||||
"especialidad": "orden.especialidad",
|
||||
"diagnostico": "orden.diagnostico",
|
||||
},
|
||||
fuentes={"especialidad": "especialidad_fuente"},
|
||||
)
|
||||
|
||||
|
||||
def nota_medica(
|
||||
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False
|
||||
) -> DeStaging:
|
||||
textos = {
|
||||
"motivo": lambda f: texto_limpio(f.nm_motivo_consulta),
|
||||
"diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto),
|
||||
} if con_textos else {}
|
||||
return DeStaging(
|
||||
staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha",
|
||||
columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional)
|
||||
derivadas={
|
||||
"cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos,
|
||||
},
|
||||
resultados={
|
||||
"cie_codigo": "nota_medica.diagnostico",
|
||||
"especialidad": "nota_medica.especialidad",
|
||||
**({f: f"nota_medica.{f}" for f in textos}),
|
||||
},
|
||||
fuentes={"especialidad": "especialidad_fuente"},
|
||||
)
|
||||
@@ -1,30 +0,0 @@
|
||||
"""De una fila de pacientes de staging a `persona` (T-20c)."""
|
||||
|
||||
from core.indicadores.comunes import PersonaBase
|
||||
|
||||
from webapi.orchestration.silver.values import codigo, texto_limpio
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
|
||||
def a_persona(paciente, *, tablas: TablasKit, **propias) -> PersonaBase:
|
||||
"""La persona de una fila de pacientes; las columnas propias del proyecto salen de `tablas.persona_propias`."""
|
||||
return tablas.Persona(
|
||||
pac_id=paciente.pac_id,
|
||||
pac_id_hospital=paciente.pac_id_hospital,
|
||||
fecha_nacimiento=paciente.pac_fecha_nacimiento,
|
||||
**{**tablas.persona_propias(paciente), **propias},
|
||||
)
|
||||
|
||||
|
||||
def de_derechohabiente(paciente) -> dict:
|
||||
"""Lo que la persona de CaCu y CaMa agrega a las comunes: lo que el hospital sabe de la derechohabiente."""
|
||||
return {
|
||||
"dependencia": texto_limpio(paciente.pac_dependencia),
|
||||
"parentesco": texto_limpio(paciente.pac_parentesco),
|
||||
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
|
||||
}
|
||||
|
||||
|
||||
def con_sexo(paciente) -> dict:
|
||||
"""Lo que la persona de TEA agrega: el sexo, como código."""
|
||||
return {"sexo": codigo(paciente.pac_sexo)}
|
||||
@@ -1,257 +0,0 @@
|
||||
"""De staging a `procedimiento` y `observacion` (F5, ADR-MD-007; staging directo, T-20c y ADR-MD-009).
|
||||
|
||||
Cada proyecto declara en `<proyecto>/plata.py`, `DESDE_STAGING`, qué procedimientos salen de cada
|
||||
fila de cada tabla de staging (`DeStaging`): su clase, su estudio, su fecha, su padre, sus columnas
|
||||
y sus resultados, nombrando columnas de staging o **derivadas** (funciones de la fila: la
|
||||
normalización). `plata_desde_staging` reparte cada fila en un procedimiento (el acto) y sus
|
||||
observaciones (un valor por resultado del catálogo). La carga doble y su `Correspondencia` por
|
||||
tabla por tipo se retiraron en T-20c2.
|
||||
|
||||
Solo se calcula: lo escribe Persistance (`guardar_carga_en`), en una transacción. Las filas salen como diccionarios, con la
|
||||
llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`,
|
||||
`clase`) y la de su padre, porque los `procedimiento_id` solo los conoce la base.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import NamedTuple
|
||||
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
|
||||
# A igual profundidad, el orden en que se escriben las clases (`en_orden_de_padres`).
|
||||
ORDEN_DE_CLASES = ("orden", "encuentro", "toma", "reporte", "parte")
|
||||
# Las columnas de `procedimiento` que puede llenar una correspondencia, además de pac_id y fecha.
|
||||
COLUMNAS_DE_PROCEDIMIENTO = ("numero_hospital", "orden_numero", "codigo_fuente", "id_hospital")
|
||||
|
||||
Llave = tuple[str, str, str, str] # (fuente_tabla, fuente_id, estudio_id, clase)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Padre:
|
||||
"""Cómo encuentra un procedimiento a su padre.
|
||||
|
||||
Por la llave de otra fila de staging: `fuente_id` (y, si la trae, `fuente_tabla`) son
|
||||
columnas de la fila; `tabla` es la tabla de staging del padre cuando la fila no la
|
||||
trae. O por el número de orden del hospital (`por_numero_de_orden`): el padre es la
|
||||
orden con ese `numero_hospital`.
|
||||
"""
|
||||
|
||||
estudio_id: str | None = None
|
||||
clase: str | None = None
|
||||
fuente_id: str | None = None
|
||||
fuente_tabla: str | None = None
|
||||
tabla: str | None = None
|
||||
por_numero_de_orden: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Hija:
|
||||
"""Un procedimiento que sale de la misma fila que otro y cuelga de él (el ADOS-2 de una evaluación).
|
||||
|
||||
Solo se crea si alguna de las columnas `solo_si` de la fila trae valor. Su llave tiene la
|
||||
misma fila de staging, con su propio estudio y clase.
|
||||
"""
|
||||
|
||||
estudio_id: str
|
||||
clase: str
|
||||
solo_si: tuple[str, ...]
|
||||
fecha: str | None = None
|
||||
resultados: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeStaging:
|
||||
"""Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c).
|
||||
|
||||
El contenido de la fila son sus columnas de staging más las `derivadas` (nombre -> función de
|
||||
la fila). `paciente` es la columna con el `pac_id`; nula si el procedimiento lo toma de su padre
|
||||
(un instrumento, un segmento). `columnas`: columna de `procedimiento` -> columna del contenido.
|
||||
`estudio_id`, `estudio_de`, `fecha`, `padres`, `resultados`, `fuentes` e `hijas` nombran
|
||||
columnas del contenido.
|
||||
- `solo_si`: si da falso, la fila no produce este procedimiento (un reporte sin fecha todavía
|
||||
no es un reporte); no es un descarte.
|
||||
- `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en
|
||||
`descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging.
|
||||
|
||||
Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada.
|
||||
Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17).
|
||||
"""
|
||||
|
||||
staging: type
|
||||
llave: str
|
||||
clase: str
|
||||
estudio_id: str | None = None
|
||||
estudio_de: str | None = None
|
||||
fecha: str | None = None
|
||||
padres: tuple[Padre, ...] = ()
|
||||
columnas: Mapping[str, str] = field(default_factory=dict)
|
||||
resultados: Mapping[str, str] = field(default_factory=dict)
|
||||
fuentes: Mapping[str, str] = field(default_factory=dict)
|
||||
hijas: tuple[Hija, ...] = ()
|
||||
derivadas: Mapping[str, Callable] = field(default_factory=dict)
|
||||
paciente: str | None = "pac_id"
|
||||
solo_si: Callable | None = None
|
||||
descartar: Callable | None = None
|
||||
|
||||
|
||||
class LotePlata(NamedTuple):
|
||||
"""Lo que recibe `guardar_plata_en`: procedimientos en orden de clase, sus observaciones y los descartes."""
|
||||
|
||||
procedimientos: list[dict]
|
||||
observaciones: list[dict]
|
||||
descartes: dict[str, int]
|
||||
|
||||
|
||||
def plata_desde_staging(
|
||||
filas: Mapping[str, Iterable],
|
||||
*,
|
||||
correspondencias: Iterable[DeStaging],
|
||||
catalogo: Catalogo,
|
||||
codigos_hospital: Mapping[str, str],
|
||||
pacientes: Iterable[int] = (),
|
||||
) -> LotePlata:
|
||||
"""De las filas de staging (tabla -> filas) a procedimientos y observaciones. Pura (staging directo, T-20c).
|
||||
|
||||
Cada `DeStaging` arma el contenido de cada fila de su tabla (columnas más derivadas) y lo
|
||||
reparte en un procedimiento (y sus hijas) con sus observaciones. Cada procedimiento sale como
|
||||
`{"llave": Llave, "padres": [Llave | ("orden", numero)], "pac_id", "fecha", ...}` y cada
|
||||
observación como `{"procedimiento": Llave, "pac_id", "resultado_id", "valor_id",
|
||||
"valor_numerico", "valor_fecha", "valor_texto", "valor_fuente"}`. Una fila cuyo estudio no se
|
||||
encuentra en `codigos_hospital` no entra y se cuenta en `descartes`, como una fila a la
|
||||
que `descartar` le da motivo se cuenta en `descartes` y no entra. `pacientes`: los `pac_id`
|
||||
conocidos, para `descartar`.
|
||||
"""
|
||||
pacientes = set(pacientes)
|
||||
tipos, vigentes = _tipos_y_vigentes(catalogo)
|
||||
procedimientos, observaciones, descartes = [], [], {}
|
||||
for c in correspondencias:
|
||||
tabla = c.staging.__tablename__
|
||||
for fila in filas.get(tabla, ()):
|
||||
fuente_id = getattr(fila, c.llave)
|
||||
if c.descartar is not None and (motivo := c.descartar(fila, pacientes)) is not None:
|
||||
descartes[motivo] = descartes.get(motivo, 0) + 1
|
||||
continue
|
||||
if c.solo_si is not None and not c.solo_si(fila):
|
||||
continue
|
||||
contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente)
|
||||
contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()})
|
||||
_repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital,
|
||||
tipos, vigentes, procedimientos, observaciones, descartes)
|
||||
return LotePlata(en_orden_de_padres(procedimientos), observaciones, descartes)
|
||||
|
||||
|
||||
class CicloDePadres(ValueError):
|
||||
"""Un procedimiento del lote que es, por sus padres, ancestro de sí mismo."""
|
||||
|
||||
|
||||
def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]:
|
||||
"""Los procedimientos en el orden en que se escriben: cada uno después de sus padres del mismo lote (T-22h).
|
||||
|
||||
`guardar_plata_en` resuelve el padre con lo que ya escribió, así que un padre del lote va antes que
|
||||
sus hijos aunque su clase vaya después (la orden de una biopsia cuelga de su toma). A igual
|
||||
profundidad, por `ORDEN_DE_CLASES` y, dentro de la clase, como llegaron. Un padre fuera del lote (ya
|
||||
escrito, o la orden del hospital por su número) no cuenta. Un ciclo de padres falla con `CicloDePadres`.
|
||||
"""
|
||||
por_llave = {p["llave"]: p for p in procedimientos}
|
||||
profundidad: dict = {}
|
||||
|
||||
def de(llave, camino=()):
|
||||
if llave in profundidad:
|
||||
return profundidad[llave]
|
||||
if llave in camino:
|
||||
raise CicloDePadres(f"Ciclo de padres en el lote: {' -> '.join(map(str, (*camino, llave)))}.")
|
||||
padres = [padre for padre in por_llave[llave]["padres"] if padre in por_llave]
|
||||
profundidad[llave] = 1 + max((de(padre, (*camino, llave)) for padre in padres), default=-1)
|
||||
return profundidad[llave]
|
||||
|
||||
return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3])))
|
||||
|
||||
|
||||
def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]:
|
||||
tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados}
|
||||
vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
return tipos, vigentes
|
||||
|
||||
|
||||
def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, columnas: tuple[str, ...],
|
||||
codigos_hospital: Mapping[str, str], tipos: dict, vigentes: set,
|
||||
procedimientos: list, observaciones: list, descartes: dict) -> None:
|
||||
"""Un procedimiento (y sus hijas) con sus observaciones, desde el contenido de una fila: el motor común."""
|
||||
estudio_id = c.estudio_id or codigos_hospital.get(contenido.get(c.estudio_de))
|
||||
if estudio_id is None:
|
||||
motivo = f"{nombre}: {c.estudio_de} fuera de catálogo"
|
||||
descartes[motivo] = descartes.get(motivo, 0) + 1
|
||||
return
|
||||
llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase)
|
||||
procedimientos.append({
|
||||
"llave": llave,
|
||||
"padres": [p for p in (_parent(padre, contenido) for padre in c.padres) if p is not None],
|
||||
"pac_id": contenido.get("pac_id"),
|
||||
"fecha": contenido.get(c.fecha) if c.fecha else None,
|
||||
# Sin columna de fecha (instrumentos, segmentos), la fecha es la del padre; con ella, puede quedar nula.
|
||||
"fecha_del_padre": c.fecha is None,
|
||||
**{columna: contenido.get(columna) for columna in columnas},
|
||||
})
|
||||
observaciones += _observaciones(llave, contenido, c.resultados, c.fuentes, tipos, vigentes)
|
||||
for hija in c.hijas:
|
||||
if all(contenido.get(columna) is None for columna in hija.solo_si):
|
||||
continue
|
||||
llave_hija = (fuente_tabla, str(fuente_id), hija.estudio_id, hija.clase)
|
||||
procedimientos.append({
|
||||
"llave": llave_hija, "padres": [llave], "pac_id": contenido.get("pac_id"),
|
||||
"fecha": contenido.get(hija.fecha) if hija.fecha else None, "fecha_del_padre": hija.fecha is None,
|
||||
})
|
||||
observaciones += _observaciones(llave_hija, contenido, hija.resultados, c.fuentes, tipos, vigentes)
|
||||
|
||||
|
||||
def valor_de_observacion(valor, fuente, *, tipo_valor: str, en_catalogo: Callable[[str], bool]) -> dict:
|
||||
"""El valor en su columna según `tipo_valor` (ADR-MD-007). Un valor nulo da la observación con valor nulo."""
|
||||
fila = {"valor_id": None, "valor_numerico": None, "valor_fecha": None, "valor_texto": None, "valor_fuente": None}
|
||||
if tipo_valor == "codigo":
|
||||
texto = None if valor is None else str(valor)
|
||||
fila["valor_id"] = texto if texto is not None and en_catalogo(texto) else None
|
||||
fila["valor_fuente"] = None if fuente is None else str(fuente)
|
||||
elif tipo_valor in ("booleano", "numero"):
|
||||
fila["valor_numerico"] = None if valor is None else float(valor)
|
||||
elif tipo_valor == "fecha":
|
||||
fila["valor_fecha"] = valor
|
||||
else: # texto, externo
|
||||
fila["valor_texto"] = None if valor is None else str(valor)
|
||||
return fila
|
||||
|
||||
|
||||
def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str], fuentes: Mapping[str, str],
|
||||
tipos: dict, vigentes: set) -> list[dict]:
|
||||
filas = []
|
||||
for columna, plantilla in resultados.items():
|
||||
resultado_id = plantilla.format(estudio=llave[2])
|
||||
filas.append({
|
||||
"procedimiento": llave,
|
||||
"pac_id": contenido.get("pac_id"),
|
||||
"resultado_id": resultado_id,
|
||||
**valor_de_observacion(
|
||||
contenido.get(columna), _fuente(contenido, columna, fuentes),
|
||||
tipo_valor=tipos[resultado_id], en_catalogo=lambda v, r=resultado_id: (r, v) in vigentes,
|
||||
),
|
||||
})
|
||||
return filas
|
||||
|
||||
|
||||
def _fuente(contenido: dict, columna: str, fuentes: Mapping[str, str]):
|
||||
"""El valor tal como llegó: el de su columna fuente, o el mismo valor si esa columna viene vacía."""
|
||||
fuente = contenido.get(fuentes.get(columna, columna))
|
||||
return contenido.get(columna) if fuente is None else fuente
|
||||
|
||||
|
||||
def _parent(padre: Padre, contenido: dict):
|
||||
if padre.por_numero_de_orden:
|
||||
numero = contenido.get(padre.por_numero_de_orden)
|
||||
return None if numero is None else ("orden", numero)
|
||||
fuente_id = contenido.get(padre.fuente_id)
|
||||
if fuente_id is None:
|
||||
return None
|
||||
tabla = contenido.get(padre.fuente_tabla) if padre.fuente_tabla else padre.tabla
|
||||
if tabla is None:
|
||||
return None
|
||||
return (tabla, str(fuente_id), padre.estudio_id, padre.clase)
|
||||
@@ -1,43 +0,0 @@
|
||||
"""Calidad de la plata de dos tablas: lo que está mal en `procedimiento` y `observacion`, contado.
|
||||
|
||||
Cuatro conteos, una consulta cada uno (ADR-MD-007):
|
||||
|
||||
reporte_sin_padre un reporte o una parte sin procedimiento padre
|
||||
fuera_de_catalogo una observación codificada cuyo valor no está en `cat_valor` (llegó texto, no código)
|
||||
de_otro_estudio una observación de un resultado de otro estudio que el de su procedimiento
|
||||
(salvo los `orden.*` de una orden, cuyo estudio es el pedido)
|
||||
nulas una observación sin ningún valor
|
||||
|
||||
Solo lee y solo cuenta. Qué hacer con los conteos (avisar) lo decide la arista
|
||||
`verificar_plata` de webapi.orchestration.
|
||||
"""
|
||||
|
||||
from sqlalchemy import and_, func, not_, select
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
CONTEOS = ("reporte_sin_padre", "fuera_de_catalogo", "de_otro_estudio", "nulas")
|
||||
VALORES = ("valor_id", "valor_numerico", "valor_fecha", "valor_texto", "valor_fuente")
|
||||
|
||||
|
||||
def verificar_plata(sesion: Session, *, tablas: TablasKit) -> dict[str, int]:
|
||||
"""Los cuatro conteos de `CONTEOS` sobre el estado actual de las dos tablas."""
|
||||
p, o, r = tablas.Procedimiento, tablas.Observacion, tablas.CatResultado
|
||||
observaciones_con_resultado = select(func.count()).select_from(o).join(r, r.resultado_id == o.resultado_id)
|
||||
consultas = {
|
||||
"reporte_sin_padre": select(func.count()).select_from(p).where(
|
||||
p.clase.in_(("reporte", "parte")), p.padre_id.is_(None)
|
||||
),
|
||||
"fuera_de_catalogo": observaciones_con_resultado.where(
|
||||
r.tipo_valor == "codigo", o.valor_id.is_(None), o.valor_fuente.is_not(None)
|
||||
),
|
||||
"de_otro_estudio": observaciones_con_resultado.join(p, p.procedimiento_id == o.procedimiento_id).where(
|
||||
r.estudio_id != p.estudio_id,
|
||||
not_(and_(r.estudio_id == "orden", p.clase == "orden")),
|
||||
),
|
||||
"nulas": select(func.count()).select_from(o).where(
|
||||
*(getattr(o, columna).is_(None) for columna in VALORES)
|
||||
),
|
||||
}
|
||||
return {nombre: sesion.execute(consulta).scalar_one() for nombre, consulta in consultas.items()}
|
||||
@@ -1,44 +0,0 @@
|
||||
"""Las normalizaciones de un valor de staging que usan las columnas derivadas de `DESDE_STAGING` (T-20c).
|
||||
|
||||
Una sola definición por regla (T-20c3; antes repartidas en `cdm/` y en la normalización de cada proyecto,
|
||||
retirados en T-20c2).
|
||||
"""
|
||||
|
||||
from collections.abc import Collection, Mapping
|
||||
|
||||
INTENCION = "order" # FHIR `ServiceRequest.intent` de una orden; sus valores están sin definir
|
||||
|
||||
|
||||
def texto_limpio(valor) -> str | None:
|
||||
"""Un texto de staging sin espacios alrededor; nulo si viene vacío. No lo normaliza más (I-K61)."""
|
||||
if valor is None:
|
||||
return None
|
||||
return str(valor).strip() or None
|
||||
|
||||
|
||||
def codigo(texto: str | None) -> str | None:
|
||||
"""Un código como lo compara ulises: sin espacios al borde y en mayúsculas; vacío es nulo."""
|
||||
if texto is None:
|
||||
return None
|
||||
return texto.strip().upper() or None
|
||||
|
||||
|
||||
def cie(texto: str | None) -> str | None:
|
||||
"""Un código CIE-10 para compararlo: sin espacios, sin punto y en mayúsculas (C53.9 -> C539); vacío es nulo."""
|
||||
if texto is None:
|
||||
return None
|
||||
return texto.strip().upper().replace(".", "").replace(" ", "") or None
|
||||
|
||||
|
||||
def codigo_de_especialidad(texto, alias: Mapping[str, str], codigos: Collection[str]) -> str | None:
|
||||
"""La especialidad en el código de Core: el propio código o su alias, sin distinguir mayúsculas.
|
||||
|
||||
Nulo si no viene o no se reconoce: quien la use la cuenta como sin dato.
|
||||
"""
|
||||
limpio = texto_limpio(texto)
|
||||
if limpio is None:
|
||||
return None
|
||||
en_mayusculas = limpio.upper()
|
||||
if en_mayusculas in codigos:
|
||||
return en_mayusculas
|
||||
return alias.get(en_mayusculas)
|
||||
@@ -1,72 +0,0 @@
|
||||
"""La vista `v_persona`, la única que queda en la base de un proyecto (F6, ADR-MD-009).
|
||||
|
||||
Es un `select` de SQLAlchemy; `CreateView` y `DropView`, de aquí, la escriben para
|
||||
el motor (T-2 de v0.5.0). La crea la arista `vistas`, no la migración (B21). Aquí
|
||||
solo se arma la DDL; no se ejecuta.
|
||||
|
||||
Antes eran las de `sqlalchemy-utils`, pero importar ese paquete registra para toda
|
||||
sesión de SQLAlchemy un `after_flush` (`sqlalchemy_utils.aggregates`) que recorre
|
||||
todos los objetos de la sesión en cada flush. La carga a plata hace un flush por
|
||||
procedimiento nuevo, así que la carga crecía con el cuadrado de los pacientes
|
||||
(TEA, 1000 pacientes: 25 s con él, 9 s sin él).
|
||||
|
||||
Las vistas por tipo (`v_<tabla>_actual`, las de rol y las de cada proyecto)
|
||||
se borraron con sus tablas en las migraciones de F6.
|
||||
"""
|
||||
|
||||
from sqlalchemy import Select, column, select, table
|
||||
from sqlalchemy.ext.compiler import compiles
|
||||
from sqlalchemy.schema import DDLElement
|
||||
from sqlalchemy.sql.expression import Executable
|
||||
|
||||
from core.indicadores.comunes import PersonaBase
|
||||
|
||||
|
||||
def ddl_de_vistas(persona: type = PersonaBase) -> list[Executable]:
|
||||
"""La DDL que crea o reemplaza `v_persona`, con las columnas de la persona del proyecto. No la ejecuta.
|
||||
|
||||
La ejecuta Persistance (`VistasRepository.construir`) o, en una base de
|
||||
prueba, `pruebas.construir_vistas`.
|
||||
"""
|
||||
# `persona` no tiene versiones: su vista es la tabla, para que un
|
||||
# indicador lea solo vistas (B18, I-K23).
|
||||
return reemplazar_vista("v_persona", select(*_columnas("persona", persona)))
|
||||
|
||||
|
||||
def _columnas(nombre: str, modelo: type) -> list:
|
||||
"""Las columnas de `modelo`, leídas de la tabla o vista `nombre`."""
|
||||
return list(table(nombre, *(column(campo) for campo in modelo.model_fields)).c)
|
||||
|
||||
|
||||
class CreateView(DDLElement):
|
||||
"""`CREATE VIEW nombre AS <consulta>`, con los valores escritos en la consulta."""
|
||||
|
||||
def __init__(self, nombre: str, consulta: Select) -> None:
|
||||
self.nombre, self.consulta = nombre, consulta
|
||||
|
||||
|
||||
class DropView(DDLElement):
|
||||
"""`DROP VIEW IF EXISTS nombre`, sin CASCADE: SQLite no lo acepta (I-K100)."""
|
||||
|
||||
def __init__(self, nombre: str) -> None:
|
||||
self.nombre = nombre
|
||||
|
||||
|
||||
@compiles(CreateView)
|
||||
def _crear(elemento: CreateView, compilador, **_) -> str:
|
||||
nombre = compilador.dialect.identifier_preparer.quote(elemento.nombre)
|
||||
return f"CREATE VIEW {nombre} AS {compilador.sql_compiler.process(elemento.consulta, literal_binds=True)}"
|
||||
|
||||
|
||||
@compiles(DropView)
|
||||
def _borrar(elemento: DropView, compilador, **_) -> str:
|
||||
return f"DROP VIEW IF EXISTS {compilador.dialect.identifier_preparer.quote(elemento.nombre)}"
|
||||
|
||||
|
||||
def borrar_vista(nombre: str) -> DropView:
|
||||
return DropView(nombre)
|
||||
|
||||
|
||||
def reemplazar_vista(nombre: str, consulta: Select) -> list[Executable]:
|
||||
"""La DDL que crea la vista `nombre` con esa consulta; si ya existe, la reemplaza."""
|
||||
return [borrar_vista(nombre), CreateView(nombre, consulta)]
|
||||
@@ -1,87 +0,0 @@
|
||||
"""Las tablas de un proyecto, juntas, para pasarlas al código común.
|
||||
|
||||
El código común (carga, registro, cálculo, contratos) no importa clases
|
||||
de tabla: recibe las del proyecto en un `TablasKit`. Así cada proyecto
|
||||
puede tener sus propias clases, aunque las columnas sean las mismas, y
|
||||
CaCu y CaMa corren en el mismo proceso sin un "proyecto activo".
|
||||
|
||||
Cada proyecto declara la suya en `<proyecto>/tablas.py` como `TABLAS`.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TablasKit:
|
||||
"""Las tablas de un proyecto: el registro, el oro y la plata genérica (una sola plata, ADR-MD-009)."""
|
||||
|
||||
Persona: type[SQLModel]
|
||||
PeriodoObservacion: type[SQLModel]
|
||||
Carga: type[SQLModel]
|
||||
DefParametro: type[SQLModel]
|
||||
DimPeriodo: type[SQLModel]
|
||||
DimFecha: type[SQLModel]
|
||||
DimGrupoEdad: type[SQLModel]
|
||||
MeasureReport: type[SQLModel]
|
||||
# Los catálogos de la plata (F1): estudio -> resultado -> valor, de `core/catalogos/<proyecto>.toml`.
|
||||
CatEstudio: type[SQLModel]
|
||||
CatResultado: type[SQLModel]
|
||||
CatValor: type[SQLModel]
|
||||
# La plata de dos tablas (F5, ADR-MD-007).
|
||||
Procedimiento: type[SQLModel]
|
||||
Observacion: type[SQLModel]
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): opcionales para que un registro de prueba no los necesite.
|
||||
CatMeasure: type[SQLModel] | None = None
|
||||
CatMeasureResultado: type[SQLModel] | None = None
|
||||
CatMeasureValor: type[SQLModel] | None = None
|
||||
CatMeasureGrupo: type[SQLModel] | None = None
|
||||
CatEstrato: type[SQLModel] | None = None
|
||||
CatEstratoValor: type[SQLModel] | None = None
|
||||
CatMeasureEstrato: type[SQLModel] | None = None
|
||||
MeasureReportUnidad: type[SQLModel] | None = None
|
||||
MeasureReportUnidadEstrato: type[SQLModel] | None = None
|
||||
# De una fila de `paciente` de staging, las columnas que este proyecto agrega a su `persona`.
|
||||
persona_propias: Callable[[object], dict] = lambda paciente: {}
|
||||
|
||||
def comunes(self) -> list[type[SQLModel]]:
|
||||
return [
|
||||
self.Persona,
|
||||
self.PeriodoObservacion,
|
||||
self.Carga,
|
||||
self.DefParametro,
|
||||
self.DimPeriodo,
|
||||
self.DimFecha,
|
||||
self.DimGrupoEdad,
|
||||
self.MeasureReport,
|
||||
self.CatEstudio,
|
||||
self.CatResultado,
|
||||
self.CatValor,
|
||||
self.Procedimiento,
|
||||
self.Observacion,
|
||||
]
|
||||
|
||||
def publicacion(self) -> list[type[SQLModel]]:
|
||||
"""Las tablas de §6f (MD-19) que el proyecto declara, en orden de llaves foráneas."""
|
||||
return [m for m in (self.CatMeasure, self.CatMeasureResultado, self.CatMeasureValor, self.CatMeasureGrupo, self.CatEstrato, self.CatEstratoValor, self.CatMeasureEstrato, self.MeasureReportUnidad, self.MeasureReportUnidadEstrato) if m is not None]
|
||||
|
||||
def catalogo_de_publicacion(self) -> list[type[SQLModel]]:
|
||||
"""Las siete tablas `cat_*` de §6f, padres antes que hijos (lo que sincroniza la arista `definiciones`)."""
|
||||
return [m for m in (self.CatEstrato, self.CatEstratoValor, self.CatMeasure, self.CatMeasureResultado,
|
||||
self.CatMeasureValor, self.CatMeasureGrupo, self.CatMeasureEstrato) if m is not None]
|
||||
|
||||
def todas(self) -> list[type[SQLModel]]:
|
||||
"""Todo lo que la base del proyecto lleva del kit (sin staging ni cohortes)."""
|
||||
return [*self.comunes(), *self.publicacion()]
|
||||
|
||||
|
||||
def tablas_de(proyecto: str) -> TablasKit:
|
||||
"""El `TablasKit` del proyecto, de `<proyecto>/tablas.py`."""
|
||||
if proyecto not in PROJECTS:
|
||||
raise KeyError(f"Proyecto desconocido: {proyecto!r}.")
|
||||
return import_module(f"webapi.orchestration.tables.{proyecto}").TABLAS
|
||||
@@ -1,77 +0,0 @@
|
||||
"""Las tablas de CaCu: viven en `Core`, en el registro del dominio (ADR-004).
|
||||
|
||||
`TABLAS` es lo que el código común recibe para trabajar con este proyecto.
|
||||
"""
|
||||
|
||||
from core.cacu.indicadores.models import (
|
||||
CatMeasure,
|
||||
CatMeasureResultado,
|
||||
CatMeasureValor,
|
||||
CatMeasureGrupo,
|
||||
CatEstrato,
|
||||
CatEstratoValor,
|
||||
CatMeasureEstrato,
|
||||
MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato,
|
||||
CatEstudio,
|
||||
CatResultado,
|
||||
CatValor,
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
CohorteMiembro,
|
||||
CohorteVariable,
|
||||
EvaluacionRiesgo,
|
||||
EvaluacionRiesgoLote,
|
||||
Carga,
|
||||
DefParametro,
|
||||
DimFecha,
|
||||
DimGrupoEdad,
|
||||
DimPeriodo,
|
||||
MeasureReport,
|
||||
PeriodoObservacion,
|
||||
Persona,
|
||||
)
|
||||
|
||||
from webapi.orchestration.silver.persons import de_derechohabiente
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
__all__ = ["TABLAS", "COHORTES"]
|
||||
|
||||
TABLAS = TablasKit(
|
||||
Persona=Persona,
|
||||
PeriodoObservacion=PeriodoObservacion,
|
||||
Carga=Carga,
|
||||
DefParametro=DefParametro,
|
||||
DimPeriodo=DimPeriodo,
|
||||
DimFecha=DimFecha,
|
||||
DimGrupoEdad=DimGrupoEdad,
|
||||
MeasureReport=MeasureReport,
|
||||
CatEstudio=CatEstudio,
|
||||
CatResultado=CatResultado,
|
||||
CatValor=CatValor,
|
||||
Procedimiento=Procedimiento,
|
||||
Observacion=Observacion,
|
||||
CatMeasure=CatMeasure,
|
||||
CatMeasureResultado=CatMeasureResultado,
|
||||
CatMeasureValor=CatMeasureValor,
|
||||
CatMeasureGrupo=CatMeasureGrupo,
|
||||
CatEstrato=CatEstrato,
|
||||
CatEstratoValor=CatEstratoValor,
|
||||
CatMeasureEstrato=CatMeasureEstrato,
|
||||
MeasureReportUnidad=MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato=MeasureReportUnidadEstrato,
|
||||
persona_propias=de_derechohabiente,
|
||||
)
|
||||
|
||||
# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003).
|
||||
COHORTES = TablasCohorte(
|
||||
CohorteArmado=CohorteArmado,
|
||||
CohorteMiembro=CohorteMiembro,
|
||||
CohorteExclusion=CohorteExclusion,
|
||||
CohorteVariable=CohorteVariable,
|
||||
EvaluacionRiesgoLote=EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo=EvaluacionRiesgo,
|
||||
)
|
||||
@@ -1,77 +0,0 @@
|
||||
"""Las tablas de CaMa: viven en `Core`, en el registro del dominio (ADR-004).
|
||||
|
||||
`TABLAS` es lo que el código común recibe para trabajar con este proyecto.
|
||||
"""
|
||||
|
||||
from core.cama.indicadores.models import (
|
||||
CatMeasure,
|
||||
CatMeasureResultado,
|
||||
CatMeasureValor,
|
||||
CatMeasureGrupo,
|
||||
CatEstrato,
|
||||
CatEstratoValor,
|
||||
CatMeasureEstrato,
|
||||
MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato,
|
||||
CatEstudio,
|
||||
CatResultado,
|
||||
CatValor,
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
CohorteMiembro,
|
||||
CohorteVariable,
|
||||
EvaluacionRiesgo,
|
||||
EvaluacionRiesgoLote,
|
||||
Carga,
|
||||
DefParametro,
|
||||
DimFecha,
|
||||
DimGrupoEdad,
|
||||
DimPeriodo,
|
||||
MeasureReport,
|
||||
PeriodoObservacion,
|
||||
Persona,
|
||||
)
|
||||
|
||||
from webapi.orchestration.silver.persons import de_derechohabiente
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
__all__ = ["TABLAS", "COHORTES"]
|
||||
|
||||
TABLAS = TablasKit(
|
||||
Persona=Persona,
|
||||
PeriodoObservacion=PeriodoObservacion,
|
||||
Carga=Carga,
|
||||
DefParametro=DefParametro,
|
||||
DimPeriodo=DimPeriodo,
|
||||
DimFecha=DimFecha,
|
||||
DimGrupoEdad=DimGrupoEdad,
|
||||
MeasureReport=MeasureReport,
|
||||
CatEstudio=CatEstudio,
|
||||
CatResultado=CatResultado,
|
||||
CatValor=CatValor,
|
||||
Procedimiento=Procedimiento,
|
||||
Observacion=Observacion,
|
||||
CatMeasure=CatMeasure,
|
||||
CatMeasureResultado=CatMeasureResultado,
|
||||
CatMeasureValor=CatMeasureValor,
|
||||
CatMeasureGrupo=CatMeasureGrupo,
|
||||
CatEstrato=CatEstrato,
|
||||
CatEstratoValor=CatEstratoValor,
|
||||
CatMeasureEstrato=CatMeasureEstrato,
|
||||
MeasureReportUnidad=MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato=MeasureReportUnidadEstrato,
|
||||
persona_propias=de_derechohabiente,
|
||||
)
|
||||
|
||||
# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003; MD-12).
|
||||
COHORTES = TablasCohorte(
|
||||
CohorteArmado=CohorteArmado,
|
||||
CohorteMiembro=CohorteMiembro,
|
||||
CohorteExclusion=CohorteExclusion,
|
||||
CohorteVariable=CohorteVariable,
|
||||
EvaluacionRiesgoLote=EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo=EvaluacionRiesgo,
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""El ciclo de indicadores de cada proyecto (CaCu, CaMa, TEA): del staging que deja
|
||||
la ingesta a los reportes que publica el tablero. Lo corre
|
||||
[Hamilton](https://hamilton.apache.org/).
|
||||
|
||||
Cada paso es una función de `ciclo.py`. Recibe el `Contexto` y, como parámetros,
|
||||
los pasos que deben correr antes; Hamilton arma el grafo con esos nombres. Los
|
||||
pasos no se pasan datos: todo va por la base, a través de los repositorios de
|
||||
Persistance (`ctx.repos`), así que cada uno se puede correr solo. El cálculo es
|
||||
del kit (`indicadores_kit`); aquí solo se decide qué se lee, a qué repositorio
|
||||
se le pasa y en qué orden.
|
||||
|
||||
migrar -> catalogos, registro, definiciones
|
||||
catalogos -> cargar
|
||||
cargar -> vistas, cohortes
|
||||
vistas + registro + definiciones -> calcular
|
||||
calcular -> observar, verificar_plata
|
||||
cohortes -> estimar (solo donde hay cohortes: hoy, CaCu)
|
||||
|
||||
uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026
|
||||
uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular
|
||||
uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica"
|
||||
|
||||
El servicio `indicadores` (`webapi.indicadores_vivos`) corre este mismo ciclo,
|
||||
sin `migrar`, cada vez que una importación escribe datos.
|
||||
|
||||
Módulo | Qué hace
|
||||
---------------|---------
|
||||
`ciclo.py` | Los pasos
|
||||
`ejecutor.py` | `correr(ctx, solo=...)`: arma el driver de Hamilton y corre los pasos pedidos en orden
|
||||
`contexto.py` | El `Contexto`: proyecto, años, corte, parámetros y repositorios
|
||||
`repositorios.py` | `repositorios_de(proyecto)`: los repositorios de Persistance, por capa
|
||||
`proyecto.py` | Tipos de periodo y definiciones de cohorte de un proyecto
|
||||
`conexion.py` | Apunta Persistance a otra base en el mismo proceso (pruebas)
|
||||
"""
|
||||
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.ejecutor import Paso, correr, pasos_de
|
||||
|
||||
__all__ = ["Contexto", "Paso", "correr", "pasos_de"]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""La línea de comandos de la orquestación.
|
||||
|
||||
uv run python -m webapi.orquestacion ciclo cacu --desde 2024 --hasta 2026 [--corte 2026-01-01] [--permitir-sin-definir]
|
||||
uv run python -m webapi.orquestacion ciclo tea --desde 2025 --hasta 2025 --solo calcular
|
||||
uv run python -m webapi.orquestacion confirmar-riesgos cacu 3 --motivo "revisado por clínica" [--anular]
|
||||
|
||||
La base es la de `<PROYECTO>_DATABASE_URL`, como en Persistance.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.ejecutor import correr
|
||||
|
||||
PROYECTOS = ("cacu", "cama", "tea")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
lector = argparse.ArgumentParser(prog="orquestacion", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ordenes = lector.add_subparsers(dest="orden", required=True)
|
||||
c = ordenes.add_parser("ciclo", help="corre los pasos del proyecto en orden")
|
||||
c.add_argument("proyecto", choices=PROYECTOS)
|
||||
c.add_argument("--desde", type=int, required=True, help="primer año de periodos")
|
||||
c.add_argument("--hasta", type=int, required=True, help="último año de periodos")
|
||||
c.add_argument("--corte", type=date.fromisoformat, default=None)
|
||||
c.add_argument("--permitir-sin-definir", action="store_true")
|
||||
c.add_argument("--parametros", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)")
|
||||
c.add_argument("--solo", nargs="+", default=None, help="solo estos pasos")
|
||||
r = ordenes.add_parser("confirmar-riesgos", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)")
|
||||
r.add_argument("proyecto", choices=PROYECTOS)
|
||||
r.add_argument("lote_id", type=int)
|
||||
r.add_argument("--motivo", required=True, help="por qué se confirma o se anula; queda en cada evaluación")
|
||||
r.add_argument("--anular", action="store_true", help="anular (entered-in-error) en vez de confirmar")
|
||||
args = lector.parse_args(argv)
|
||||
|
||||
if args.orden == "confirmar-riesgos":
|
||||
cambiadas = confirmar_riesgos(args.proyecto, args.lote_id, args.motivo, anular=args.anular)
|
||||
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.anular else 'confirmadas'}")
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
ctx = Contexto(args.proyecto, args.desde, args.hasta, args.corte, args.permitir_sin_definir, args.parametros)
|
||||
for paso in correr(ctx, solo=args.solo):
|
||||
print(f"{paso.nombre:20} {paso.segundos:6.1f} s")
|
||||
|
||||
|
||||
def confirmar_riesgos(proyecto: str, lote_id: int, motivo: str, *, anular: bool = False) -> int:
|
||||
"""Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva.
|
||||
|
||||
No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008).
|
||||
"""
|
||||
from persistance.aristas.oro import ERROR, FINAL
|
||||
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
return repositorios_de(proyecto).oro.cohorte.cambiar_estado(lote_id, ERROR if anular else FINAL, motivo)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Los pasos del ciclo de un proyecto, como funciones de Hamilton.
|
||||
|
||||
Cada paso recibe el `Contexto` y, como parámetros, los pasos que tienen que
|
||||
correr antes; de esos nombres sale el grafo. Los pasos no se pasan datos entre
|
||||
sí: todo va por la base, a través de `ctx.repos`, así que cada uno se puede
|
||||
correr solo (`ejecutor.correr(ctx, solo=[...])`).
|
||||
|
||||
El kit calcula (funciones puras, o funciones de una sesión) y los repositorios
|
||||
de `persistance.aristas` escriben, cada operación en una sesión (ADR-MD-005).
|
||||
Bronce lo escribe la ingesta, fuera del ciclo.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
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.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 webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo
|
||||
|
||||
registro_de_eventos = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def migrar(ctx: Contexto) -> str:
|
||||
"""`alembic upgrade head` del dominio, con el `alembic.ini` de Persistance."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
ini = Path(persistance.__file__).parent / ctx.proyecto / "alembic.ini"
|
||||
raiz = logging.getLogger()
|
||||
manejadores, nivel = raiz.handlers[:], raiz.level
|
||||
estado = [(r, r.disabled) for r in logging.root.manager.loggerDict.values() if isinstance(r, logging.Logger)]
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
# `env.py` llama a `fileConfig`, que apaga los registradores ya creados y cambia los de la raíz.
|
||||
for registrador, apagado in estado:
|
||||
registrador.disabled = apagado
|
||||
raiz.handlers[:], raiz.level = manejadores, nivel
|
||||
return "head"
|
||||
|
||||
|
||||
def catalogos(migrar: str, ctx: Contexto) -> dict[str, int]:
|
||||
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.proyecto), tablas=tablas_de(ctx.proyecto))
|
||||
return ctx.repos.plata.catalogos.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
|
||||
|
||||
def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel:
|
||||
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
|
||||
|
||||
Incremental por la llave lógica de cada procedimiento (`guardar_carga_en`): repetir no cambia nada.
|
||||
"""
|
||||
tablas, staging = tablas_de(ctx.proyecto), tablas_de_staging(ctx.proyecto)
|
||||
|
||||
def leer(sesion):
|
||||
filas = {modelo.__tablename__: list(sesion.exec(select(modelo))) for modelo in staging}
|
||||
return carga_desde_staging(filas, proyecto=ctx.proyecto)
|
||||
|
||||
def escribir(sesion, datos):
|
||||
return guardar_carga_en(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento,
|
||||
observacion=tablas.Observacion, fuente=datos.fuente, personas=datos.personas,
|
||||
plata=datos.plata)
|
||||
|
||||
return ctx.repos.materializador.materializar(leer, escribir)
|
||||
|
||||
|
||||
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)))
|
||||
|
||||
|
||||
def registro(migrar: str, ctx: Contexto) -> list[str]:
|
||||
"""`parametros.toml` (o `ctx.parametros`) -> `def_parametro` (se reemplaza), los periodos que falten en
|
||||
`dim_periodo` y las tablas de apoyo `dim_fecha` y `dim_grupo_edad` (se reemplazan; I-MD27).
|
||||
|
||||
El archivo se lee y valida antes de escribir. Los periodos no se reemplazan:
|
||||
los reportes guardados apuntan a ellos. `dim_fecha` va de `comun.dim_fecha.desde` al fin
|
||||
de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `<proyecto>.grupos_edad`, si el
|
||||
proyecto los tiene (TEA no).
|
||||
"""
|
||||
tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto)
|
||||
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)
|
||||
valores = valores_del_archivo(ruta)
|
||||
# Hasta el fin del último año del ciclo o del año del corte (por omisión, la última carga: hoy), el que sea mayor.
|
||||
hasta = date(max(ctx.anio_fin, (ctx.corte or date.today()).year), 12, 31)
|
||||
desde = date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE])
|
||||
grupos = grupos_de_edad_de(ctx.proyecto, valores, tablas=tablas)
|
||||
oro = ctx.repos.oro
|
||||
oro.parametros.reemplazar(parametros)
|
||||
oro.periodos.agregar_faltantes(periodos)
|
||||
if oro.fechas is not None and not _cubre(oro.fechas, desde, hasta):
|
||||
oro.fechas.reemplazar_en_bloque(filas_de_dim_fecha(valores, hasta, proyecto=ctx.proyecto))
|
||||
if oro.grupos_edad is not None and grupos is not None:
|
||||
oro.grupos_edad.reemplazar(grupos)
|
||||
return tipos
|
||||
|
||||
|
||||
def _cubre(fechas, desde: date, hasta: date) -> bool:
|
||||
"""`dim_fecha` ya es exactamente de `desde` a `hasta`: tiene los dos extremos y un día por fecha."""
|
||||
return (fechas.get(desde) is not None and fechas.get(hasta) is not None
|
||||
and fechas.count() == (hasta - desde).days + 1)
|
||||
|
||||
|
||||
def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]:
|
||||
"""Las definiciones del proyecto -> el catálogo de publicación de §6f (`cat_measure*`, `cat_estrato*`).
|
||||
|
||||
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.
|
||||
"""
|
||||
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())}
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# `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:
|
||||
"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente."""
|
||||
return ctx.repos.plata.observacion.observar(partial(
|
||||
periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte,
|
||||
permitir_sin_definir=ctx.permitir_sin_definir,
|
||||
))
|
||||
|
||||
|
||||
def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[str, list[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():
|
||||
if n:
|
||||
registro_de_eventos.warning("%s, plata de dos tablas: %d %s.", ctx.proyecto, n, nombre.replace("_", " "))
|
||||
return conteos
|
||||
|
||||
|
||||
@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)."""
|
||||
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)
|
||||
|
||||
armados = {}
|
||||
for ruta in definiciones_de_cohorte(ctx.proyecto):
|
||||
definicion = leer_definicion(ruta)
|
||||
armados[definicion.url] = ctx.repos.oro.cohorte.armar(partial(armado, definicion))
|
||||
return armados
|
||||
|
||||
|
||||
@config.when(con_cohortes=True)
|
||||
def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, tuple[int, bool]]:
|
||||
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
|
||||
|
||||
Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador
|
||||
(`ctx.estimadores[url]`: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
|
||||
un lote `preliminary` (`CohorteRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
|
||||
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
|
||||
`confirmar-riesgos`, no este paso.
|
||||
"""
|
||||
tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES
|
||||
lotes = {}
|
||||
for ruta in definiciones_de_cohorte(ctx.proyecto):
|
||||
definicion = leer_definicion(ruta)
|
||||
estimador = ctx.estimadores.get(definicion.url)
|
||||
if estimador is None:
|
||||
continue
|
||||
|
||||
def marco(sesion, definicion=definicion):
|
||||
armado_id = ultimo_armado(sesion, definicion.url, cohortes=tablas_cohorte)
|
||||
return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion,
|
||||
cohortes=tablas_cohorte)
|
||||
|
||||
armado_id, ancho = ctx.repos.oro.cohorte.leer(marco)
|
||||
if armado_id is None:
|
||||
continue
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[definicion.url] = ctx.repos.oro.cohorte.guardar_lote(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
return lotes
|
||||
@@ -10,7 +10,7 @@ from persistance.settings import settings
|
||||
from persistance import db
|
||||
|
||||
|
||||
def point_to(proyecto: str, url: str) -> None:
|
||||
def apuntar(proyecto: str, url: str) -> None:
|
||||
motor = getattr(db, f"get_{proyecto}_engine")
|
||||
if motor.cache_info().currsize:
|
||||
motor().dispose()
|
||||
@@ -1,6 +1,5 @@
|
||||
"""Lo que recibe cada paso del ciclo."""
|
||||
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
@@ -8,36 +7,27 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def dbt_manifest_path() -> Path | None:
|
||||
"""The deployment's dbt manifest, from `DBT_MANIFEST`."""
|
||||
ruta = os.environ.get("DBT_MANIFEST")
|
||||
return Path(ruta) if ruta else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Context:
|
||||
class Contexto:
|
||||
"""Lo que recibe un paso: el proyecto y las opciones del ciclo.
|
||||
|
||||
`anio_inicio` y `anio_fin` son los años de los periodos que se registran y
|
||||
calculan. `corte` es la fecha hasta la que llegan los datos; sin ella, cada
|
||||
paso del kit toma la de la última carga. `permitir_sin_definir` deja correr
|
||||
con parámetros que nadie ha decidido: hay que pedirlo a propósito, como en
|
||||
el kit. `parametros` es el archivo de parámetros que carga `registry`; sin
|
||||
el kit. `parametros` es el archivo de parámetros que carga `registro`; sin
|
||||
él, el `parametros.toml` del kit. `repos` es todo lo que el paso usa
|
||||
para tocar la base: nunca abre una sesión por su cuenta (`repositories.py`).
|
||||
para tocar la base: nunca abre una sesión por su cuenta (`repositorios.py`).
|
||||
"""
|
||||
|
||||
project: str
|
||||
year_from: int
|
||||
year_to: int
|
||||
cutoff: date | None = None
|
||||
allow_undecided: bool = False
|
||||
parameters: Path | None = None
|
||||
# The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle
|
||||
# creates their event models (`event_models`) and seeds the publication catalog (`definitions`).
|
||||
dbt_manifest: Path | None = field(default_factory=dbt_manifest_path)
|
||||
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()`
|
||||
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada.
|
||||
estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
|
||||
proyecto: str
|
||||
anio_inicio: int
|
||||
anio_fin: int
|
||||
corte: date | None = None
|
||||
permitir_sin_definir: bool = False
|
||||
parametros: Path | None = None
|
||||
# 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)
|
||||
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
|
||||
repos: Any = field(default=None, compare=False, repr=False)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Corre los pasos de un proyecto (`cycle.py`) con Hamilton.
|
||||
"""Corre los pasos de un proyecto (`ciclo.py`) con Hamilton.
|
||||
|
||||
Si un paso falla, los anteriores quedan hechos (cada operación de un
|
||||
repositorio es su propia transacción) y se puede volver a correr: los pasos no
|
||||
duplican. Si el contexto no trae repositorios, se le ponen los de Persistance
|
||||
para el proyecto (`repositories_of`).
|
||||
para el proyecto (`repositorios_de`).
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -16,28 +16,28 @@ from hamilton import driver
|
||||
from hamilton.execution.graph_functions import topologically_sort_nodes
|
||||
from hamilton.lifecycle import NodeExecutionHook
|
||||
|
||||
from webapi.orchestration import cycle
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.project import cohort_definitions
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
from webapi.orquestacion import ciclo
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.proyecto import definiciones_de_cohorte
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
registro = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Step:
|
||||
class Paso:
|
||||
"""Lo que dejó un paso: su resumen y cuánto tardó."""
|
||||
|
||||
name: str
|
||||
summary: Any
|
||||
seconds: float
|
||||
nombre: str
|
||||
resumen: Any
|
||||
segundos: float
|
||||
|
||||
|
||||
class _Logbook(NodeExecutionHook):
|
||||
class _Bitacora(NodeExecutionHook):
|
||||
"""Anota cada paso que corre, en el orden en que corre."""
|
||||
|
||||
def __init__(self):
|
||||
self.pasos: list[Step] = []
|
||||
self.pasos: list[Paso] = []
|
||||
self._inicio = 0.0
|
||||
|
||||
def run_before_node_execution(self, **_):
|
||||
@@ -45,44 +45,44 @@ class _Logbook(NodeExecutionHook):
|
||||
|
||||
def run_after_node_execution(self, *, node_name: str, result: Any, success: bool, **_):
|
||||
if success:
|
||||
self.pasos.append(Step(node_name, result, time.monotonic() - self._inicio))
|
||||
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
|
||||
self.pasos.append(Paso(node_name, result, time.monotonic() - self._inicio))
|
||||
registro.info("%s: %s en %.1f s", node_name, _corto(result), self.pasos[-1].segundos)
|
||||
|
||||
|
||||
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
|
||||
return (driver.Builder()
|
||||
.with_modules(cycle)
|
||||
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
|
||||
.with_modules(ciclo)
|
||||
.with_config({"con_cohortes": bool(definiciones_de_cohorte(proyecto))})
|
||||
.with_adapters(*adaptadores)
|
||||
.build())
|
||||
|
||||
|
||||
def _in_order(dr: driver.Driver) -> list[str]:
|
||||
def _en_orden(dr: driver.Driver) -> list[str]:
|
||||
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
|
||||
|
||||
|
||||
def steps_of(proyecto: str) -> list[str]:
|
||||
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
|
||||
return _in_order(_driver(proyecto))
|
||||
def pasos_de(proyecto: str) -> list[str]:
|
||||
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, solo donde hay definiciones)."""
|
||||
return _en_orden(_driver(proyecto))
|
||||
|
||||
|
||||
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
|
||||
"""Corre el ciclo del proyecto en el orden de sus dependencias. `only`: los pasos a correr; los demás no corren.
|
||||
def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]:
|
||||
"""Corre el ciclo del proyecto en el orden de sus dependencias. `solo`: los pasos a correr; los demás no corren.
|
||||
|
||||
Los pasos que no corren se le dan a Hamilton ya resueltos. Así entre dos pedidos puede no quedar dependencia
|
||||
(`load` y `compute` sin `views`), por eso se le piden en el orden del grafo completo.
|
||||
(`cargar` y `calcular` sin `vistas`), por eso se le piden en el orden del grafo completo.
|
||||
"""
|
||||
if ctx.repos is None:
|
||||
ctx = replace(ctx, repos=repositories_of(ctx.project))
|
||||
bitacora = _Logbook()
|
||||
dr = _driver(ctx.project, bitacora)
|
||||
todos = _in_order(dr)
|
||||
pedidos = [p for p in todos if only is None or p in only]
|
||||
ctx = replace(ctx, repos=repositorios_de(ctx.proyecto))
|
||||
bitacora = _Bitacora()
|
||||
dr = _driver(ctx.proyecto, bitacora)
|
||||
todos = _en_orden(dr)
|
||||
pedidos = [p for p in todos if solo is None or p in solo]
|
||||
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
|
||||
return bitacora.pasos
|
||||
|
||||
|
||||
def _short(resumen: Any) -> str:
|
||||
def _corto(resumen: Any) -> str:
|
||||
if isinstance(resumen, dict):
|
||||
return f"{len(resumen)} elementos"
|
||||
return str(resumen)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Lo que el ciclo necesita saber de las definiciones del kit para un proyecto."""
|
||||
|
||||
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 definiciones_de_cohorte(proyecto: str) -> list[Path]:
|
||||
"""Los TOML de cohortes que el ciclo arma (`<proyecto>/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h)."""
|
||||
return sorted((RAIZ / proyecto / "cohortes").glob("*.toml"))
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro.
|
||||
|
||||
Las subclases viven en `persistance/aristas/<capa>/` y se
|
||||
instancian en `persistance/<proyecto>/__init__.py` con la fábrica de sesión del
|
||||
dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from 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,
|
||||
CohorteRepository,
|
||||
PublicacionRepository,
|
||||
RegistroRepository,
|
||||
)
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
TimelineQuery,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
)
|
||||
from persistance.materializador import Materializador
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bronce:
|
||||
"""Lo que deja la ingesta. Solo se lee."""
|
||||
|
||||
staging: StagingRepository
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Plata:
|
||||
"""Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata."""
|
||||
|
||||
catalogos: CatalogoRepository
|
||||
carga: CargaRepository
|
||||
vistas: VistasRepository
|
||||
observacion: ObservacionRepository
|
||||
vinculos: VinculosRepository
|
||||
timeline: TimelineRepository | None = None # the patients' timeline, through the kit's query
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Oro:
|
||||
"""El registro (parámetros, periodos, definiciones), los reportes y las cohortes."""
|
||||
|
||||
parametros: RegistroRepository
|
||||
periodos: RegistroRepository
|
||||
calculo: CalculoRepository
|
||||
publicacion: PublicacionRepository # el catálogo de publicación de §6f (T-19b)
|
||||
cohorte: CohorteRepository | None # donde hay tablas de cohortes (los tres desde MD-12)
|
||||
fechas: RegistroRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27)
|
||||
grupos_edad: RegistroRepository | None = None # `dim_grupo_edad`, de `<proyecto>.grupos_edad` (I-MD27)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Repositorios:
|
||||
"""Todo lo que un paso usa para tocar la base de su proyecto, por capa."""
|
||||
|
||||
bronce: Bronce
|
||||
plata: Plata
|
||||
oro: Oro
|
||||
# Una sesión para leer y escribir en el mismo paso (`cargar`).
|
||||
materializador: Materializador | None = None
|
||||
|
||||
|
||||
def repositorios_de(proyecto: str) -> Repositorios:
|
||||
dominio = import_module(f"persistance.{proyecto}")
|
||||
return Repositorios(
|
||||
bronce=Bronce(staging=dominio.staging_repository),
|
||||
plata=Plata(
|
||||
catalogos=dominio.catalogo_repository,
|
||||
carga=dominio.carga_repository,
|
||||
vistas=dominio.vistas_repository,
|
||||
observacion=dominio.observar_repository,
|
||||
vinculos=dominio.vinculos_repository,
|
||||
timeline=dominio.timeline_repository.with_query(timeline_query(proyecto)),
|
||||
),
|
||||
materializador=dominio.materializador,
|
||||
oro=Oro(
|
||||
parametros=dominio.def_parametro_repository,
|
||||
periodos=dominio.dim_periodo_repository,
|
||||
calculo=dominio.calculo_repository,
|
||||
publicacion=dominio.publicacion_repository,
|
||||
cohorte=getattr(dominio, "cohorte_repository", None),
|
||||
fechas=getattr(dominio, "dim_fecha_repository", None),
|
||||
grupos_edad=getattr(dominio, "dim_grupo_edad_repository", None),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
@@ -1,9 +1,9 @@
|
||||
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`, only in DEV.
|
||||
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
|
||||
|
||||
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
|
||||
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
|
||||
evaluation. Patient data: **registered only in DEV** (`DEV_REVISION`), on simulated data, and every response carries
|
||||
`simulado: true`. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
|
||||
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
|
||||
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
|
||||
removed or renamed, only added.
|
||||
"""
|
||||
|
||||
@@ -16,7 +16,7 @@ COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
|
||||
|
||||
|
||||
def patient_risk_blueprint(repositories) -> Blueprint:
|
||||
"""The blueprint, to register with `url_prefix="/cacu"` only in DEV. `repositories` is `persistance.cacu`."""
|
||||
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
|
||||
blueprint = Blueprint("cacu_patient_risk", __name__)
|
||||
|
||||
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
|
||||
@@ -24,8 +24,8 @@ def patient_risk_blueprint(repositories) -> Blueprint:
|
||||
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
|
||||
if repositories.persona_repository.get(pac_id) is None:
|
||||
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
|
||||
membership = repositories.cohort_repository.membership(pac_id, COHORT_URL)
|
||||
risk = repositories.cohort_repository.current_risk(pac_id)
|
||||
membership = repositories.cohorte_repository.membership(pac_id, COHORT_URL)
|
||||
risk = repositories.cohorte_repository.current_risk(pac_id)
|
||||
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
|
||||
|
||||
return blueprint
|
||||
|
||||
@@ -1,45 +1,46 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, solo en DEV.
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`.
|
||||
|
||||
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
|
||||
|
||||
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
|
||||
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
|
||||
existe (404). La lista la arma el kit (`webapi.follow_up.listing`); aquí solo se valida,
|
||||
Es dato por paciente, sobre datos simulados: toda respuesta lleva `simulado: true`. La ruta se registra
|
||||
siempre; quién puede verla lo decidirá una regla de acceso. La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida,
|
||||
se abre la sesión y se traducen los errores.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||
from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||
from sqlmodel import Session
|
||||
|
||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
|
||||
SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
|
||||
|
||||
|
||||
def in_dev() -> bool:
|
||||
"""Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`)."""
|
||||
def en_dev() -> bool:
|
||||
"""Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará."""
|
||||
warnings.warn("en_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV."""
|
||||
def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"`."""
|
||||
blueprint = Blueprint("cacu_seguimiento", __name__)
|
||||
|
||||
@blueprint.get("/seguimiento")
|
||||
def get_seguimiento():
|
||||
try:
|
||||
pedido = _requested(request.args)
|
||||
pedido = _pedido(request.args)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido)
|
||||
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except PaginaFuera as error:
|
||||
@@ -51,7 +52,7 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
return blueprint
|
||||
|
||||
|
||||
def _requested(args) -> dict:
|
||||
def _pedido(args) -> dict:
|
||||
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
|
||||
pedido = {}
|
||||
if corte := args.get("corte"):
|
||||
Reference in New Issue
Block a user