CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is /<domain>/indicadores
This commit is contained in:
@@ -15,7 +15,7 @@ from pathlib import Path
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.ejecutor import correr
|
||||
|
||||
PROYECTOS = ("cacu", "cama", "tea")
|
||||
PROYECTOS = ("cacu", "cama")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
|
||||
@@ -11,38 +11,36 @@ Bronce lo escribe la ingesta, fuera del ciclo.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
from functools import partial
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from hamilton.function_modifiers import config
|
||||
from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata
|
||||
from indicadores_kit.esquema import ddl_de_vistas
|
||||
from indicadores_kit.oro.calculo import fecha_de_ultima_carga, medir_con_unidades
|
||||
from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado
|
||||
from indicadores_kit.oro.cohortes.definicion import leer_definicion
|
||||
from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging
|
||||
from indicadores_kit.plata.periodo_observacion import periodos_de_observacion
|
||||
from indicadores_kit.plata.vistas import ddl_de_vistas as ddl_de_v_persona
|
||||
from indicadores_kit.registry.apoyo import (
|
||||
CLAVE_DIM_FECHA_DESDE,
|
||||
filas_de_dim_fecha,
|
||||
grupos_de_edad_de,
|
||||
)
|
||||
from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.registry.parametros import (
|
||||
RUTA_PARAMETROS,
|
||||
leer_parametros,
|
||||
valores_del_archivo,
|
||||
)
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.publicacion import semillas_de
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from persistance.aristas.plata import guardar_carga_en
|
||||
from sqlmodel import SQLModel, select
|
||||
from sqlmodel import SQLModel, func, select
|
||||
|
||||
from webapi.orquestacion.contexto import Contexto
|
||||
from webapi.orquestacion.semantic_layer import catalog_layers, event_views
|
||||
from webapi.orquestacion.proyecto import definiciones_de_cohorte, tipos_de_periodo
|
||||
|
||||
registro_de_eventos = logging.getLogger(__name__)
|
||||
@@ -93,8 +91,8 @@ def cargar(catalogos: dict[str, int], ctx: Contexto) -> SQLModel:
|
||||
|
||||
|
||||
def vistas(cargar: SQLModel, ctx: Contexto) -> int:
|
||||
"""Las vistas de versión vigente y las del proyecto: la DDL la arma el kit y la corre el repositorio."""
|
||||
return len(ctx.repos.plata.vistas.construir(ddl_de_vistas(ctx.proyecto)))
|
||||
"""`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base."""
|
||||
return len(ctx.repos.plata.vistas.construir(ddl_de_v_persona(tablas_de(ctx.proyecto).Persona)))
|
||||
|
||||
|
||||
def registro(migrar: str, ctx: Contexto) -> list[str]:
|
||||
@@ -106,7 +104,7 @@ def registro(migrar: str, ctx: Contexto) -> list[str]:
|
||||
de `ctx.anio_fin` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `<proyecto>.grupos_edad`, si el
|
||||
proyecto los tiene (TEA no).
|
||||
"""
|
||||
tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto)
|
||||
tablas, tipos = tablas_de(ctx.proyecto), tipos_de_periodo(ctx.proyecto, _manifest(ctx))
|
||||
ruta = ctx.parametros or RUTA_PARAMETROS
|
||||
parametros = leer_parametros(ruta, tablas=tablas)
|
||||
periodos = periodos_de_tipos(tipos, ctx.anio_inicio, ctx.anio_fin, tablas=tablas)
|
||||
@@ -132,35 +130,26 @@ def _cubre(fechas, desde: date, hasta: date) -> bool:
|
||||
|
||||
|
||||
def definiciones(migrar: str, ctx: Contexto) -> dict[str, int]:
|
||||
"""Las definiciones del proyecto -> el catálogo de publicación de §6f (`cat_measure*`, `cat_estrato*`).
|
||||
"""The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest.
|
||||
|
||||
Se sincroniza: lo que una unidad de un reporte usa no se borra (T-19b). Se leen y validan todos los
|
||||
archivos antes de escribir: uno inválido no toca las tablas.
|
||||
It's synchronized: what a report's unit uses isn't deleted.
|
||||
"""
|
||||
tablas, rutas = tablas_de(ctx.proyecto), rutas_de_measures(ctx.proyecto)
|
||||
semillas = semillas_de(ctx.proyecto, rutas, valores_del_archivo(ctx.parametros or RUTA_PARAMETROS), tablas=tablas)
|
||||
return {"definiciones": len(semillas.measures), **ctx.repos.oro.publicacion.sincronizar(semillas.por_capas())}
|
||||
capas = catalog_layers(ctx.proyecto, _manifest(ctx))
|
||||
return {"definiciones": len(capas[0]), **ctx.repos.oro.publicacion.sincronizar(capas)}
|
||||
|
||||
|
||||
def calcular(vistas: int, registro: list[str], definiciones: dict[str, int], ctx: Contexto) -> dict[str, list[int]]:
|
||||
"""Cada definición en cada periodo de cada tipo que publica, dentro de los años del contexto.
|
||||
|
||||
Cada reporte se mide y se guarda en una sola sesión (`CalculoRepository.calcular`).
|
||||
"""
|
||||
desde, hasta = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1)
|
||||
calculo, tablas = ctx.repos.oro.calculo, tablas_de(ctx.proyecto)
|
||||
reportes = {}
|
||||
for nombre, medida in measures_de(ctx.proyecto).items():
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo.periodos(tipo, desde, hasta):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=ctx.corte, permitir_sin_definir=ctx.permitir_sin_definir)
|
||||
reportes.setdefault(nombre, []).append(calculo.calcular(medir))
|
||||
return reportes
|
||||
def modelos(cargar: SQLModel, ctx: Contexto) -> int:
|
||||
"""The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base."""
|
||||
return len(ctx.repos.plata.vistas.construir(event_views(_manifest(ctx), ctx.proyecto)))
|
||||
|
||||
|
||||
# `observar` y `verificar_plata` van después de `calcular` para que una regla suya sin definir no lo detenga (I-MD1).
|
||||
def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int]], ctx: Contexto) -> int:
|
||||
def _manifest(ctx: Contexto) -> Path:
|
||||
if ctx.dbt_manifest is None:
|
||||
raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there")
|
||||
return ctx.dbt_manifest
|
||||
|
||||
|
||||
def observar(cargar: SQLModel, registro: list[str], ctx: Contexto) -> int:
|
||||
"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente."""
|
||||
return ctx.repos.plata.observacion.observar(partial(
|
||||
periodos_de_observacion, proyecto=ctx.proyecto, corte=ctx.corte,
|
||||
@@ -168,8 +157,7 @@ def observar(cargar: SQLModel, registro: list[str], calcular: dict[str, list[int
|
||||
))
|
||||
|
||||
|
||||
def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[str, list[int]],
|
||||
ctx: Contexto) -> dict[str, int]:
|
||||
def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], ctx: Contexto) -> dict[str, int]:
|
||||
"""Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro."""
|
||||
conteos = ctx.repos.plata.vinculos.verificar(partial(calidad_de_la_plata, tablas=tablas_de(ctx.proyecto)))
|
||||
for nombre, n in conteos.items():
|
||||
@@ -179,17 +167,19 @@ def verificar_plata(cargar: SQLModel, catalogos: dict[str, int], calcular: dict[
|
||||
|
||||
|
||||
@config.when(con_cohortes=True)
|
||||
def cohortes(cargar: SQLModel, ctx: Contexto) -> dict[str, tuple[int, bool]]:
|
||||
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga)."""
|
||||
def cohortes(modelos: int, ctx: Contexto) -> dict[str, tuple[int, bool]]:
|
||||
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
|
||||
|
||||
Reads dbt's timeline (`modelos` creates it), the same the models and the measures' strata read.
|
||||
"""
|
||||
tablas = tablas_de(ctx.proyecto)
|
||||
tablas_cohorte = import_module(f"indicadores_kit.{ctx.proyecto}.tablas").COHORTES
|
||||
fuentes = import_module(f"indicadores_kit.{ctx.proyecto}.linea_de_tiempo").FUENTES_PLATA
|
||||
inicio, fin = date(ctx.anio_inicio, 1, 1), date(ctx.anio_fin + 1, 1, 1)
|
||||
|
||||
def armado(definicion, sesion):
|
||||
corte = ctx.corte or fecha_de_ultima_carga(sesion, tablas)
|
||||
return armado_de(sesion, definicion, inicio, fin, corte, tablas=tablas, cohortes=tablas_cohorte,
|
||||
fuentes=fuentes)
|
||||
corte = ctx.corte or _fecha_de_ultima_carga(sesion, tablas)
|
||||
return armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
|
||||
linea=ctx.repos.plata.timeline.query)
|
||||
|
||||
armados = {}
|
||||
for ruta in definiciones_de_cohorte(ctx.proyecto):
|
||||
@@ -229,3 +219,11 @@ def estimar(cohortes: dict[str, tuple[int, bool]], ctx: Contexto) -> dict[str, t
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
return lotes
|
||||
|
||||
|
||||
def _fecha_de_ultima_carga(sesion, tablas) -> date | None:
|
||||
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
|
||||
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
|
||||
if ultima is None or isinstance(ultima, date):
|
||||
return ultima.date() if isinstance(ultima, datetime) else ultima
|
||||
return date.fromisoformat(str(ultima)[:10])
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Lo que recibe cada paso del ciclo."""
|
||||
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
@@ -7,6 +8,12 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def manifiesto_de_dbt() -> Path | None:
|
||||
"""The deployment's dbt manifest, from `DBT_MANIFEST`."""
|
||||
ruta = os.environ.get("DBT_MANIFEST")
|
||||
return Path(ruta) if ruta else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Contexto:
|
||||
"""Lo que recibe un paso: el proyecto y las opciones del ciclo.
|
||||
@@ -26,6 +33,9 @@ class Contexto:
|
||||
corte: date | None = None
|
||||
permitir_sin_definir: bool = False
|
||||
parametros: Path | None = None
|
||||
# The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle
|
||||
# creates their event models (`modelos`) and seeds the publication catalog (`definiciones`).
|
||||
dbt_manifest: Path | None = field(default_factory=manifiesto_de_dbt)
|
||||
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimar(columnas, filas)`, `procedencia()`
|
||||
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimar` no hace nada.
|
||||
estimadores: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
"""Lo que el ciclo necesita saber de las definiciones del kit para un proyecto."""
|
||||
"""Lo que el ciclo necesita saber de las definiciones de un proyecto: sus periodos (dbt) y sus cohortes (el kit)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from indicadores_kit.oro.cohortes.definicion import RAIZ
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
|
||||
|
||||
def tipos_de_periodo(proyecto: str) -> list[str]:
|
||||
"""Los tipos de periodo que publican las definiciones del proyecto (semestre y, en CaCu y CaMa, mes)."""
|
||||
return sorted({t for m in measures_de(proyecto).values() for t in m.extension.publicacion.tipos_periodo})
|
||||
def tipos_de_periodo(proyecto: str, manifest: Path) -> list[str]:
|
||||
"""The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest."""
|
||||
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
||||
return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", [])
|
||||
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
|
||||
|
||||
|
||||
def definiciones_de_cohorte(proyecto: str) -> list[Path]:
|
||||
|
||||
@@ -8,8 +8,6 @@ dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión.
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from indicadores_kit.plata.linea_de_tiempo import linea_de_tiempo_plata
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.oro import (
|
||||
CalculoRepository,
|
||||
@@ -21,7 +19,6 @@ from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
TimelineQuery,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
@@ -45,7 +42,7 @@ class Plata:
|
||||
vistas: VistasRepository
|
||||
observacion: ObservacionRepository
|
||||
vinculos: VinculosRepository
|
||||
timeline: TimelineRepository | None = None # the patients' timeline, through the kit's query
|
||||
timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -82,7 +79,7 @@ def repositorios_de(proyecto: str) -> Repositorios:
|
||||
vistas=dominio.vistas_repository,
|
||||
observacion=dominio.observar_repository,
|
||||
vinculos=dominio.vinculos_repository,
|
||||
timeline=dominio.timeline_repository.with_query(timeline_query(proyecto)),
|
||||
timeline=dominio.timeline_repository,
|
||||
),
|
||||
materializador=dominio.materializador,
|
||||
oro=Oro(
|
||||
@@ -96,13 +93,3 @@ def repositorios_de(proyecto: str) -> Repositorios:
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def timeline_query(proyecto: str) -> TimelineQuery:
|
||||
"""The project's timeline query: the kit's `linea_de_tiempo_plata` over its `FUENTES_PLATA`."""
|
||||
tablas = tablas_de(proyecto)
|
||||
fuentes = import_module(f"indicadores_kit.{proyecto}.linea_de_tiempo").FUENTES_PLATA
|
||||
|
||||
def query(*, patients, until, known_until):
|
||||
return linea_de_tiempo_plata(tablas, fuentes, pacientes=patients, hasta=until, conocida_hasta=known_until)
|
||||
|
||||
return query
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""What the cycle takes from dbt's manifest: the event models to create and the catalog the reports point to.
|
||||
|
||||
The measures are defined in dbt's semantic layer (`webapi.metrics`, `webapi.compositions`). Their event models have
|
||||
to exist in the database for a measure to be asked; `event_views` gives the DDL that creates them from dbt's compiled
|
||||
SQL, as `dbt run` would for a view. The publication catalog (`cat_measure*`, `cat_estrato`) is what the reports'
|
||||
units point to; `catalog_layers` builds it from the same definitions, parents before children.
|
||||
"""
|
||||
|
||||
import json
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.compositions import composition_definitions
|
||||
from webapi.durations import OBSERVATION, duration_definitions
|
||||
from webapi.kpis import scoring_of
|
||||
from webapi.metrics import measure_definitions
|
||||
|
||||
CONTRACTS = {"proportion": "C1", "composition": "C2", "continuous-variable": "C3r"} # the publication views
|
||||
STRATUM_LABELS = {"grupo_edad": "Grupo de edad"} # unless the stratum's `etiqueta` says otherwise
|
||||
|
||||
|
||||
def event_views(manifest: Path, project: str) -> list:
|
||||
"""`drop view if exists` and `create view … as <compiled SQL>` for every model the project's measures read,
|
||||
parents first.
|
||||
|
||||
Those are the project's models semantic models count over (`models/<project>/…`) and the timelines its strata
|
||||
read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined
|
||||
in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here.
|
||||
"""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
nodes = {n["unique_id"]: n for n in m["nodes"].values()}
|
||||
by_name = {n["name"]: uid for uid, n in nodes.items() if n["resource_type"] == "model"}
|
||||
roots = {uid for uid in (s["depends_on"]["nodes"][0] for s in m["semantic_models"].values())
|
||||
if nodes[uid]["fqn"][1] == project}
|
||||
roots |= {by_name[spec["linea"]] for metric in m["metrics"].values()
|
||||
if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/")
|
||||
for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec}
|
||||
ordered: list[str] = []
|
||||
|
||||
def visit(uid: str) -> None:
|
||||
if uid in ordered or uid not in nodes:
|
||||
return
|
||||
for parent in nodes[uid]["depends_on"]["nodes"]:
|
||||
visit(parent)
|
||||
if nodes[uid]["config"]["materialized"] != "ephemeral":
|
||||
ordered.append(uid)
|
||||
|
||||
for uid in sorted(roots):
|
||||
visit(uid)
|
||||
ddl = [text(f"drop view if exists {nodes[uid]['alias']}") for uid in reversed(ordered)]
|
||||
return ddl + [text(f"create view {nodes[uid]['alias']} as {nodes[uid]['compiled_code']}") for uid in ordered]
|
||||
|
||||
|
||||
def catalog_layers(project: str, manifest: Path) -> list[list]:
|
||||
"""The catalog rows of every measure the manifest defines for the project, in layers: parents first."""
|
||||
t = import_module(f"core.{project}.indicadores.models")
|
||||
# The title on screen: `meta.titulo` when the label had to differ (dbt wants labels unique in the project).
|
||||
labels = {n["name"]: n["config"].get("meta", {}).get("titulo") or n["label"]
|
||||
for n in json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()}
|
||||
definitions = [d for d in (*measure_definitions(manifest).values(), *composition_definitions(manifest).values(),
|
||||
*duration_definitions(manifest).values()) if d.url.startswith(f"{project}/")]
|
||||
labels_of = {s.name: s.spec.get("etiqueta") or STRATUM_LABELS.get(s.name, s.name)
|
||||
for d in definitions for s in d.strata}
|
||||
strata = sorted(labels_of)
|
||||
measures, children = [], []
|
||||
for d in definitions:
|
||||
contract = CONTRACTS[scoring_of(d)]
|
||||
measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric],
|
||||
contrato=contract, unidad=d.basis))
|
||||
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ())))
|
||||
children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c,
|
||||
etiqueta=c) for c in codes]
|
||||
children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0))
|
||||
children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata]
|
||||
stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata]
|
||||
return [stratum_rows + measures, children]
|
||||
Reference in New Issue
Block a user