256 lines
12 KiB
Python
256 lines
12 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 dataclasses import asdict
|
|
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, 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.io.storage import read_queries
|
|
from webapi.orchestration.project import cohort_urls, 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 analyze_eeg(migrate: str, score_ados2: dict, ctx: Context) -> dict[str, int]:
|
|
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
|
|
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo`
|
|
and `eeg_metrica_zona`.
|
|
Waits for `score_ados2` only so the quick scoring doesn't queue behind a long analysis.
|
|
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
|
|
if ctx.eeg_analysis is None:
|
|
return {}
|
|
return asdict(ctx.eeg_analysis())
|
|
|
|
|
|
def score_ados2(migrate: str, ctx: Context) -> dict:
|
|
"""The CSS and classification of each ADOS-2 from its items, module, algorithm and the child's age
|
|
(`ctx.ados2_scoring`), written to bronze before the association and `load` read them. Returns how many
|
|
evaluations were scored; nothing without a scoring (every domain but TEA)."""
|
|
if ctx.ados2_scoring is None:
|
|
return {}
|
|
return asdict(ctx.ados2_scoring())
|
|
|
|
|
|
def relate_ados2(analyze_eeg: dict[str, int], ctx: Context) -> dict:
|
|
"""The ADOS-2 association fitted on the EEGs the analysis left (`ctx.ados2_relation`), written to
|
|
`relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns
|
|
the version and its counts; nothing without an association (every domain but TEA)."""
|
|
if ctx.ados2_relation is None:
|
|
return {}
|
|
return asdict(ctx.ados2_relation())
|
|
|
|
|
|
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], relate_ados2: dict, ctx: Context) -> SQLModel:
|
|
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis and
|
|
the ADOS-2 association.
|
|
|
|
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 las reglas de dbt, su única definición: la población, la fecha índice, las
|
|
exclusiones y las variables son consultas del manifest (`read_queries`), con su ventana de reclutamiento y su
|
|
corte (las variables de dbt), y corren en la base después de `event_models`.
|
|
"""
|
|
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
|
manifest = _manifest(ctx)
|
|
armados = {}
|
|
for url in cohort_urls(ctx.project, manifest):
|
|
consultas = read_queries(manifest, url)
|
|
armados[url] = ctx.repos.gold.cohorts.assemble(
|
|
lambda sesion, consultas=consultas: build_of(sesion, consultas, cohortes=tablas_cohorte))
|
|
return armados
|
|
|
|
|
|
@config.when(with_cohorts=True)
|
|
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[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 a cada estimador de la cohorte
|
|
(`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los
|
|
riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no
|
|
duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. 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 url in cohort_urls(ctx.project, _manifest(ctx)):
|
|
estimadores = ctx.estimators.get(url) or []
|
|
if not estimadores:
|
|
continue
|
|
|
|
def frame(sesion, url=url):
|
|
armado_id = latest_build(sesion, url, cohortes=tablas_cohorte)
|
|
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, cohortes=tablas_cohorte)
|
|
|
|
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
|
|
if armado_id is None:
|
|
continue
|
|
lotes[url] = []
|
|
for estimador in estimadores:
|
|
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
|
lotes[url].append(ctx.repos.gold.cohorts.save_batch(
|
|
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos))
|
|
return lotes
|