73cbf0cfb8
How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the `catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet (`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add` with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's repository. Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and a second code for a form in force is refused before it's written. Loads still read the TOML's aliases.
240 lines
11 KiB
Python
240 lines
11 KiB
Python
"""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.source_mapping import catalog_rows
|
|
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.
|
|
|
|
Then the catalog's own mappings (`cat_mapeo`, system `catalogo`): only the forms with no row yet are added, so a
|
|
mapping edited in the application survives every deploy."""
|
|
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project))
|
|
counts = ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
|
mappings = ctx.repos.silver.mappings
|
|
if mappings is not None:
|
|
system, rows = catalog_rows(ctx.project, mappings)
|
|
mappings.ensure_system(system)
|
|
counts["mapeos_nuevos"] = mappings.seed(rows)
|
|
return counts
|
|
|
|
|
|
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
|
|
"""`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])
|