Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fd711929d9 |
+4
-4
@@ -1,13 +1,13 @@
|
|||||||
[submodule "WebApp"]
|
[submodule "WebApp"]
|
||||||
path = WebApp
|
path = WebApp
|
||||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
|
url = ../WebApp.git
|
||||||
[submodule "WebApi"]
|
[submodule "WebApi"]
|
||||||
path = WebApi
|
path = WebApi
|
||||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
|
url = ../WebApi.git
|
||||||
[submodule "models"]
|
[submodule "models"]
|
||||||
path = models
|
path = models
|
||||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
url = ../models.git
|
||||||
[submodule "indicadores_kit"]
|
[submodule "indicadores_kit"]
|
||||||
path = indicadores_kit
|
path = indicadores_kit
|
||||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/indicadores_kit.git
|
url = ../indicadores_kit.git
|
||||||
branch = dev
|
branch = dev
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
class TipoEstudio(str, Enum):
|
class TipoEstudio(str, Enum):
|
||||||
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders
|
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders (indicadores_kit cama)
|
||||||
BIOPSIA_CHICA = "BIOPSIA_CHICA"
|
BIOPSIA_CHICA = "BIOPSIA_CHICA"
|
||||||
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
|
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Catálogos de la plata (F1)
|
# Catálogos de la plata (F1)
|
||||||
|
|
||||||
Un TOML por proyecto: estudio → resultado → valor.
|
Un TOML por proyecto: estudio → resultado → valor.
|
||||||
El paso `catalogos` de `webapi.orchestration` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
|
El paso `catalogos` de `webapi.orquestacion` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
|
||||||
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
|
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ class ModelPrediction(GovernanceModel, table=True):
|
|||||||
version that produced it.
|
version that produced it.
|
||||||
|
|
||||||
Model training, versioning and promotion live in MLflow, not here
|
Model training, versioning and promotion live in MLflow, not here
|
||||||
(`models.io.registry`); this row only carries the keys to find that version
|
(`models.registry`); this row only carries the keys to find that version
|
||||||
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
|
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
|
||||||
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
|
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
|
||||||
already uses for its own risk evaluations.
|
already uses for its own risk evaluations.
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ def evaluacion_unica() -> UniqueConstraint:
|
|||||||
class TablasCohorte:
|
class TablasCohorte:
|
||||||
"""Las seis tablas de cohortes y riesgos de un dominio, juntas (como `TablasKit` del kit).
|
"""Las seis tablas de cohortes y riesgos de un dominio, juntas (como `TablasKit` del kit).
|
||||||
|
|
||||||
Las declara cada proyecto (`webapi.orchestration.tables.<proyecto>.COHORTES`); el ciclo las lee
|
Las declara cada proyecto (`indicadores_kit.<proyecto>.tablas.COHORTES`); el kit las lee
|
||||||
y Persistance las escribe.
|
y Persistance las escribe.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ CaCu, CaMa, TEA y gobernanza. El esquema está en `../Core`. Cambiar de motor
|
|||||||
| `repository.py` | `Repository`: `get`, `list`, `iter_all`, `count`, `create`, `bulk_upsert` (rechaza o actualiza por llave natural) y `open_session` para escribir varias tablas en una transacción. |
|
| `repository.py` | `Repository`: `get`, `list`, `iter_all`, `count`, `create`, `bulk_upsert` (rechaza o actualiza por llave natural) y `open_session` para escribir varias tablas en una transacción. |
|
||||||
| `identity.py` | Tras insertar ids explícitos, adelanta la secuencia en PostgreSQL (los demás motores lo hacen solos). |
|
| `identity.py` | Tras insertar ids explícitos, adelanta la secuencia en PostgreSQL (los demás motores lo hacen solos). |
|
||||||
| `cacu/`, `cama/`, `tea/`, `governance/` | El ambiente de Alembic de cada base y una instancia de `Repository` por tabla (`persistance.cacu.paciente_repository`, ...). |
|
| `cacu/`, `cama/`, `tea/`, `governance/` | El ambiente de Alembic de cada base y una instancia de `Repository` por tabla (`persistance.cacu.paciente_repository`, ...). |
|
||||||
| `edges/`, `materializer.py` | Repositorios del ciclo de indicadores (`webapi.orchestration`), por capa: bronce, plata y oro. |
|
| `aristas/`, `materializador.py` | Repositorios del ciclo de indicadores (`webapi.orquestacion`), por capa: bronce, plata y oro. |
|
||||||
|
|
||||||
WebApi y `models` usan las mismas instancias de repositorio; no hay otra ruta
|
WebApi y `models` usan las mismas instancias de repositorio; no hay otra ruta
|
||||||
a las tablas.
|
a las tablas.
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
"""Bronce: el staging, como lo deja la ingesta. Aquí solo se lee."""
|
"""Bronce: el staging, como lo deja la ingesta. Aquí solo se lee."""
|
||||||
|
|
||||||
from persistance.edges.bronze.staging import StagingRepository
|
from persistance.aristas.bronce.staging import StagingRepository
|
||||||
|
|
||||||
__all__ = ["StagingRepository"]
|
__all__ = ["StagingRepository"]
|
||||||
+1
-1
@@ -18,7 +18,7 @@ class StagingRepository(Repository):
|
|||||||
def __init__(self, session_factory):
|
def __init__(self, session_factory):
|
||||||
super().__init__(session_factory, None)
|
super().__init__(session_factory, None)
|
||||||
|
|
||||||
def read(self, modelos: Mapping[str, type[SQLModel]]) -> dict[str, list]:
|
def leer(self, modelos: Mapping[str, type[SQLModel]]) -> dict[str, list]:
|
||||||
"""Todas las filas de cada tabla, por nombre, en una sola sesión y en el orden de su llave primaria."""
|
"""Todas las filas de cada tabla, por nombre, en una sola sesión y en el orden de su llave primaria."""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return {
|
return {
|
||||||
+12
-12
@@ -12,23 +12,23 @@ from sqlmodel import Session, SQLModel, delete
|
|||||||
|
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
RowT = TypeVar("RowT", bound=SQLModel)
|
FilaT = TypeVar("FilaT", bound=SQLModel)
|
||||||
|
|
||||||
|
|
||||||
class ReferenceRepository(Repository[RowT]):
|
class RegistroRepository(Repository[FilaT]):
|
||||||
"""Una tabla de registro: se reconstruye desde archivos o se completa, nunca se edita a mano.
|
"""Una tabla de registro: se reconstruye desde archivos o se completa, nunca se edita a mano.
|
||||||
|
|
||||||
Sirve a parámetros, periodos, tablas de apoyo (fechas, grupos de edad)
|
Sirve a parámetros, periodos, tablas de apoyo (fechas, grupos de edad)
|
||||||
y definiciones de indicadores. Cada operación es una sesión.
|
y definiciones de indicadores. Cada operación es una sesión.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def replace_all(self, filas: Iterable[RowT]) -> int:
|
def reemplazar(self, filas: Iterable[FilaT]) -> int:
|
||||||
"""Deja la tabla con exactamente estas filas. Devuelve cuántas. Todo o nada."""
|
"""Deja la tabla con exactamente estas filas. Devuelve cuántas. Todo o nada."""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return replace_in(sesion, self.model, filas)
|
return reemplazar_en(sesion, self.model, filas)
|
||||||
|
|
||||||
def replace_in_bulk(self, filas: Iterable[RowT]) -> int:
|
def reemplazar_en_bloque(self, filas: Iterable[FilaT]) -> int:
|
||||||
"""Como `replace_all`, con un solo INSERT: para tablas grandes de apoyo (`dim_fecha`, decenas de miles de días).
|
"""Como `reemplazar`, con un solo INSERT: para tablas grandes de apoyo (`dim_fecha`, decenas de miles de días).
|
||||||
|
|
||||||
Las filas pueden venir como modelos o como diccionarios de sus columnas.
|
Las filas pueden venir como modelos o como diccionarios de sus columnas.
|
||||||
"""
|
"""
|
||||||
@@ -44,18 +44,18 @@ class ReferenceRepository(Repository[RowT]):
|
|||||||
raise
|
raise
|
||||||
return len(filas)
|
return len(filas)
|
||||||
|
|
||||||
def add_missing(self, filas: Iterable[RowT]) -> int:
|
def agregar_faltantes(self, filas: Iterable[FilaT]) -> int:
|
||||||
"""Agrega las filas cuya llave no está y no toca las demás. Devuelve cuántas agregó.
|
"""Agrega las filas cuya llave no está y no toca las demás. Devuelve cuántas agregó.
|
||||||
|
|
||||||
Para tablas a las que otras apuntan (los reportes apuntan a
|
Para tablas a las que otras apuntan (los reportes apuntan a
|
||||||
`dim_periodo`): reemplazarlas violaría esas llaves foráneas.
|
`dim_periodo`): reemplazarlas violaría esas llaves foráneas.
|
||||||
"""
|
"""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return add_missing_in(sesion, self.model, filas)
|
return agregar_faltantes_en(sesion, self.model, filas)
|
||||||
|
|
||||||
|
|
||||||
def replace_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> int:
|
def reemplazar_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT]) -> int:
|
||||||
"""El cuerpo de `ReferenceRepository.reemplazar`, sobre una sesión que se recibe."""
|
"""El cuerpo de `RegistroRepository.reemplazar`, sobre una sesión que se recibe."""
|
||||||
filas = list(filas)
|
filas = list(filas)
|
||||||
try:
|
try:
|
||||||
sesion.exec(delete(modelo))
|
sesion.exec(delete(modelo))
|
||||||
@@ -67,8 +67,8 @@ def replace_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> in
|
|||||||
return len(filas)
|
return len(filas)
|
||||||
|
|
||||||
|
|
||||||
def add_missing_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> int:
|
def agregar_faltantes_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT]) -> int:
|
||||||
"""El cuerpo de `ReferenceRepository.agregar_faltantes`, sobre una sesión que se recibe."""
|
"""El cuerpo de `RegistroRepository.agregar_faltantes`, sobre una sesión que se recibe."""
|
||||||
llave = modelo.__table__.primary_key.columns.values()
|
llave = modelo.__table__.primary_key.columns.values()
|
||||||
nuevas = [
|
nuevas = [
|
||||||
fila
|
fila
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Oro: el registro (parámetros, periodos, definiciones), los reportes de indicadores y las cohortes con sus riesgos."""
|
||||||
|
|
||||||
|
from persistance.aristas.comun import RegistroRepository
|
||||||
|
from persistance.aristas.oro.calculo import CalculoRepository, MeasureReportRepository, guardar_reporte_en
|
||||||
|
from persistance.aristas.oro.publicacion import PublicacionRepository, sincronizar_publicacion_en
|
||||||
|
from persistance.aristas.oro.cohortes import (
|
||||||
|
ERROR,
|
||||||
|
FINAL,
|
||||||
|
PRELIMINAR,
|
||||||
|
PROCEDENCIA,
|
||||||
|
CohorteRepository,
|
||||||
|
RiesgoFueraDeCohorte,
|
||||||
|
cambiar_estado_en,
|
||||||
|
guardar_armado_en,
|
||||||
|
guardar_lote_en,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ERROR",
|
||||||
|
"FINAL",
|
||||||
|
"PRELIMINAR",
|
||||||
|
"PROCEDENCIA",
|
||||||
|
"CalculoRepository",
|
||||||
|
"CohorteRepository",
|
||||||
|
"MeasureReportRepository",
|
||||||
|
"PublicacionRepository",
|
||||||
|
"RegistroRepository",
|
||||||
|
"RiesgoFueraDeCohorte",
|
||||||
|
"cambiar_estado_en",
|
||||||
|
"guardar_armado_en",
|
||||||
|
"guardar_lote_en",
|
||||||
|
"guardar_reporte_en",
|
||||||
|
"sincronizar_publicacion_en",
|
||||||
|
]
|
||||||
+24
-24
@@ -1,6 +1,6 @@
|
|||||||
"""Oro: los reportes de indicadores. Un reporte se guarda con sus unidades (§6f), todo o nada.
|
"""Oro: los reportes de indicadores. Un reporte se guarda con sus unidades (§6f), todo o nada.
|
||||||
|
|
||||||
`CalculationRepository` es lo que usa la arista `compute`: mide (lo que calcula el
|
`CalculoRepository` es lo que usa la arista `calcular`: mide (lo que calcula el
|
||||||
kit, como función de la sesión) y guarda en la misma sesión, una sola foto de la
|
kit, como función de la sesión) y guarda en la misma sesión, una sola foto de la
|
||||||
base por reporte.
|
base por reporte.
|
||||||
"""
|
"""
|
||||||
@@ -15,14 +15,14 @@ from sqlmodel import Session, SQLModel, select
|
|||||||
|
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
ReportT = TypeVar("ReportT", bound=MeasureReportBase)
|
ReporteT = TypeVar("ReporteT", bound=MeasureReportBase)
|
||||||
Measurement = tuple[MeasureReportBase, Iterable[SQLModel]]
|
Medicion = tuple[MeasureReportBase, Iterable[SQLModel]]
|
||||||
|
|
||||||
|
|
||||||
class MeasureReportRepository(Repository[ReportT]):
|
class MeasureReportRepository(Repository[ReporteT]):
|
||||||
"""Los reportes de indicadores de un dominio. Un reporte se guarda con sus unidades."""
|
"""Los reportes de indicadores de un dominio. Un reporte se guarda con sus unidades."""
|
||||||
|
|
||||||
def save(self, reporte: ReportT, filas: Iterable[SQLModel] = ()) -> int:
|
def guardar(self, reporte: ReporteT, filas: Iterable[SQLModel] = ()) -> int:
|
||||||
"""Guarda un reporte y sus filas hijas con una sola sesión. Devuelve el `report_id`.
|
"""Guarda un reporte y sus filas hijas con una sola sesión. Devuelve el `report_id`.
|
||||||
|
|
||||||
Las filas (las unidades de `measure_report_unidad` y sus estratos, §6f) llegan sin `report_id`:
|
Las filas (las unidades de `measure_report_unidad` y sus estratos, §6f) llegan sin `report_id`:
|
||||||
@@ -32,10 +32,10 @@ class MeasureReportRepository(Repository[ReportT]):
|
|||||||
fecha de corte cuenta para que sea igual (MV-3). Todo o nada.
|
fecha de corte cuenta para que sea igual (MV-3). Todo o nada.
|
||||||
"""
|
"""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return save_report_in(sesion, reporte, filas)
|
return guardar_reporte_en(sesion, reporte, filas)
|
||||||
|
|
||||||
|
|
||||||
def save_report_in(sesion: Session, reporte: MeasureReportBase, filas: Iterable[SQLModel] = ()) -> int:
|
def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Iterable[SQLModel] = ()) -> int:
|
||||||
"""El cuerpo de `MeasureReportRepository.guardar`, sobre una sesión que se recibe.
|
"""El cuerpo de `MeasureReportRepository.guardar`, sobre una sesión que se recibe.
|
||||||
|
|
||||||
`filas` son las unidades del reporte (`measure_report_unidad`, oro restringido) y el estrato de cada
|
`filas` son las unidades del reporte (`measure_report_unidad`, oro restringido) y el estrato de cada
|
||||||
@@ -44,8 +44,8 @@ def save_report_in(sesion: Session, reporte: MeasureReportBase, filas: Iterable[
|
|||||||
"""
|
"""
|
||||||
filas = list(filas)
|
filas = list(filas)
|
||||||
try:
|
try:
|
||||||
anterior = _last_report(sesion, reporte)
|
anterior = _ultimo_reporte(sesion, reporte)
|
||||||
if anterior is not None and _repeats(sesion, anterior, reporte, filas):
|
if anterior is not None and _repite(sesion, anterior, reporte, filas):
|
||||||
return anterior.report_id
|
return anterior.report_id
|
||||||
sesion.add(reporte)
|
sesion.add(reporte)
|
||||||
sesion.flush()
|
sesion.flush()
|
||||||
@@ -61,7 +61,7 @@ def save_report_in(sesion: Session, reporte: MeasureReportBase, filas: Iterable[
|
|||||||
|
|
||||||
|
|
||||||
# Lo que hace distinto a un reporte; la hora en que se generó no cuenta.
|
# Lo que hace distinto a un reporte; la hora en que se generó no cuenta.
|
||||||
_DISTINGUISHING_COLUMNS = (
|
_COLUMNAS_QUE_DISTINGUEN = (
|
||||||
"measure_version",
|
"measure_version",
|
||||||
"kit_version",
|
"kit_version",
|
||||||
"toml_sha",
|
"toml_sha",
|
||||||
@@ -77,7 +77,7 @@ _DISTINGUISHING_COLUMNS = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _last_report(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBase | None:
|
def _ultimo_reporte(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBase | None:
|
||||||
"""El último reporte guardado del mismo indicador y periodo, por `generado_en`."""
|
"""El último reporte guardado del mismo indicador y periodo, por `generado_en`."""
|
||||||
modelo = type(reporte)
|
modelo = type(reporte)
|
||||||
return sesion.exec(
|
return sesion.exec(
|
||||||
@@ -88,14 +88,14 @@ def _last_report(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBa
|
|||||||
).first()
|
).first()
|
||||||
|
|
||||||
|
|
||||||
def _repeats(sesion: Session, anterior: MeasureReportBase, reporte: MeasureReportBase, filas: list[SQLModel]) -> bool:
|
def _repite(sesion: Session, anterior: MeasureReportBase, reporte: MeasureReportBase, filas: list[SQLModel]) -> bool:
|
||||||
"""Si el reporte nuevo es igual al anterior: mismo encabezado (con `huella`) y mismas filas, tabla por tabla."""
|
"""Si el reporte nuevo es igual al anterior: mismo encabezado (con `huella`) y mismas filas, tabla por tabla."""
|
||||||
if any(getattr(anterior, columna) != getattr(reporte, columna) for columna in _DISTINGUISHING_COLUMNS):
|
if any(getattr(anterior, columna) != getattr(reporte, columna) for columna in _COLUMNAS_QUE_DISTINGUEN):
|
||||||
return False
|
return False
|
||||||
return _equal(sesion, anterior.report_id, filas)
|
return _iguales(sesion, anterior.report_id, filas)
|
||||||
|
|
||||||
|
|
||||||
def _equal(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
def _iguales(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||||
"""Las filas de las tablas hijas guardadas con el reporte anterior son estas, tabla por tabla.
|
"""Las filas de las tablas hijas guardadas con el reporte anterior son estas, tabla por tabla.
|
||||||
|
|
||||||
Las filas pueden ser de varias tablas (las unidades de `measure_report_unidad` y sus estratos):
|
Las filas pueden ser de varias tablas (las unidades de `measure_report_unidad` y sus estratos):
|
||||||
@@ -106,27 +106,27 @@ def _equal(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
|||||||
por_tabla.setdefault(type(fila), []).append(fila)
|
por_tabla.setdefault(type(fila), []).append(fila)
|
||||||
for modelo, de_la_tabla in por_tabla.items():
|
for modelo, de_la_tabla in por_tabla.items():
|
||||||
guardadas = sesion.exec(select(modelo).where(modelo.report_id == report_id)).all()
|
guardadas = sesion.exec(select(modelo).where(modelo.report_id == report_id)).all()
|
||||||
if sorted(map(_content, guardadas)) != sorted(map(_content, de_la_tabla)):
|
if sorted(map(_contenido, guardadas)) != sorted(map(_contenido, de_la_tabla)):
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _content(fila: SQLModel) -> str:
|
def _contenido(fila: SQLModel) -> str:
|
||||||
"""Lo que dice una fila hija, sin su `report_id` ni una llave entera que numere la base.
|
"""Lo que dice una fila hija, sin su `report_id` ni una llave entera que numere la base.
|
||||||
|
|
||||||
En `measure_report_unidad`, `valor_id` es la categoría y sí cuenta (T-19b).
|
En `measure_report_unidad`, `valor_id` es la categoría y sí cuenta (T-19b).
|
||||||
"""
|
"""
|
||||||
llave = type(fila).__table__.primary_key.columns
|
llave = type(fila).__table__.primary_key.columns
|
||||||
puesta_por_la_base = {c.name for c in llave} if len(llave) == 1 and _whole_key(llave) else set()
|
puesta_por_la_base = {c.name for c in llave} if len(llave) == 1 and _llave_entera(llave) else set()
|
||||||
return json.dumps(fila.model_dump(exclude={"report_id", *puesta_por_la_base}), sort_keys=True, default=str)
|
return json.dumps(fila.model_dump(exclude={"report_id", *puesta_por_la_base}), sort_keys=True, default=str)
|
||||||
|
|
||||||
|
|
||||||
def _whole_key(columnas) -> bool:
|
def _llave_entera(columnas) -> bool:
|
||||||
"""Si la única columna de la llave es entera: la numera la base."""
|
"""Si la única columna de la llave es entera: la numera la base."""
|
||||||
return all(c.type.python_type is int for c in columnas)
|
return all(c.type.python_type is int for c in columnas)
|
||||||
|
|
||||||
|
|
||||||
class CalculationRepository(MeasureReportRepository):
|
class CalculoRepository(MeasureReportRepository):
|
||||||
"""Los reportes de un dominio, calculados en una sola sesión: una sola foto de la base por reporte.
|
"""Los reportes de un dominio, calculados en una sola sesión: una sola foto de la base por reporte.
|
||||||
|
|
||||||
`periodo` es la tabla `dim_periodo` del dominio.
|
`periodo` es la tabla `dim_periodo` del dominio.
|
||||||
@@ -136,7 +136,7 @@ class CalculationRepository(MeasureReportRepository):
|
|||||||
super().__init__(session_factory, model)
|
super().__init__(session_factory, model)
|
||||||
self.periodo = periodo
|
self.periodo = periodo
|
||||||
|
|
||||||
def periods(self, tipo: str, desde: date, hasta: date) -> list[str]:
|
def periodos(self, tipo: str, desde: date, hasta: date) -> list[str]:
|
||||||
"""Los `periodo_id` de `tipo` que caben enteros en `[desde, hasta)`, en orden. Falla si no hay ninguno."""
|
"""Los `periodo_id` de `tipo` que caben enteros en `[desde, hasta)`, en orden. Falla si no hay ninguno."""
|
||||||
p = self.periodo
|
p = self.periodo
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
@@ -146,15 +146,15 @@ class CalculationRepository(MeasureReportRepository):
|
|||||||
if not ids:
|
if not ids:
|
||||||
raise LookupError(
|
raise LookupError(
|
||||||
f"dim_periodo no tiene periodos {tipo!r} entre {desde} y {hasta}: "
|
f"dim_periodo no tiene periodos {tipo!r} entre {desde} y {hasta}: "
|
||||||
"se agregan con la arista `registry`."
|
"se agregan con la arista `registro`."
|
||||||
)
|
)
|
||||||
return ids
|
return ids
|
||||||
|
|
||||||
def compute(self, medir: Callable[[Session], Measurement]) -> int:
|
def calcular(self, medir: Callable[[Session], Medicion]) -> int:
|
||||||
"""Mide con `medir(sesion)` (el reporte y sus unidades) y lo guarda en esa misma sesión.
|
"""Mide con `medir(sesion)` (el reporte y sus unidades) y lo guarda en esa misma sesión.
|
||||||
|
|
||||||
Devuelve el `report_id`; si el reporte repite al último del periodo, el de ese (`guardar`).
|
Devuelve el `report_id`; si el reporte repite al último del periodo, el de ese (`guardar`).
|
||||||
"""
|
"""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
reporte, filas = medir(sesion)
|
reporte, filas = medir(sesion)
|
||||||
return save_report_in(sesion, reporte, filas)
|
return guardar_reporte_en(sesion, reporte, filas)
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""Oro: cohortes para modelos y sus lotes de riesgos, la escritura (ADR-MD-003, ADR-MD-005).
|
||||||
|
|
||||||
|
El kit arma el marco de una cohorte (quién entra, su fecha índice, sus variables,
|
||||||
|
la atrición) y sus huellas. Aquí se guarda: el armado con sus filas, el lote de
|
||||||
|
riesgos con las llaves de MLflow, y los cambios de estado de las evaluaciones.
|
||||||
|
|
||||||
|
Rearmar lo mismo no guarda otro armado (misma `huella` y mismo `marco_sha`), y
|
||||||
|
puntuar lo mismo otra vez no guarda otro lote (misma `huella` del lote). Una
|
||||||
|
evaluación solo crece: confirmarla (`preliminary` -> `final`) o anularla
|
||||||
|
(`entered-in-error`) agrega una versión con su motivo.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from collections.abc import Callable, Iterable
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import TypeVar
|
||||||
|
|
||||||
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlmodel import Session, SQLModel, select
|
||||||
|
|
||||||
|
from persistance.repository import Repository
|
||||||
|
|
||||||
|
PROCEDENCIA = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||||
|
PRELIMINAR, FINAL, ERROR = "preliminary", "final", "entered-in-error"
|
||||||
|
|
||||||
|
|
||||||
|
# Lo que el kit entrega para guardar un armado: la fila del armado y sus hijas, sin `armado_id`.
|
||||||
|
Armado = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
|
||||||
|
|
||||||
|
|
||||||
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
|
class RiesgoFueraDeCohorte(ValueError):
|
||||||
|
"""Se quiso guardar el riesgo de alguien que no es miembro del armado puntuado."""
|
||||||
|
|
||||||
|
|
||||||
|
class CohorteRepository(Repository):
|
||||||
|
"""Los armados de cohortes de un dominio y sus lotes de riesgos. Cada método, una sesión."""
|
||||||
|
|
||||||
|
def __init__(self, session_factory, cohortes: TablasCohorte):
|
||||||
|
super().__init__(session_factory, cohortes.CohorteArmado)
|
||||||
|
self.cohortes = cohortes
|
||||||
|
|
||||||
|
def armar(self, armado: Callable[[Session], Armado]) -> tuple[int, bool]:
|
||||||
|
"""Calcula el armado con `armado(sesion)` y lo guarda en esa sesión. Devuelve (`armado_id`, nuevo)."""
|
||||||
|
with self._session_factory() as sesion:
|
||||||
|
return guardar_armado_en(sesion, *armado(sesion))
|
||||||
|
|
||||||
|
def leer(self, leer: Callable[[Session], T]) -> T:
|
||||||
|
"""Lo que `leer(sesion)` lee de las cohortes, en una sesión (el marco de un armado para estimar). No escribe."""
|
||||||
|
with self._session_factory() as sesion:
|
||||||
|
return leer(sesion)
|
||||||
|
|
||||||
|
def guardar_lote(
|
||||||
|
self, armado_id: int, procedencia: dict, desenlace: str, riesgos, *, ahora: datetime | None = None
|
||||||
|
) -> tuple[int, bool]:
|
||||||
|
with self._session_factory() as sesion:
|
||||||
|
return guardar_lote_en(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
|
||||||
|
ahora=ahora)
|
||||||
|
|
||||||
|
def cambiar_estado(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
|
||||||
|
with self._session_factory() as sesion:
|
||||||
|
return cambiar_estado_en(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
||||||
|
|
||||||
|
|
||||||
|
def guardar_armado_en(
|
||||||
|
sesion: Session, armado: SQLModel, exclusiones: Iterable[SQLModel], miembros: Iterable[SQLModel],
|
||||||
|
variables: Iterable[SQLModel],
|
||||||
|
) -> tuple[int, bool]:
|
||||||
|
"""Guarda un armado con su atrición, sus miembros y sus variables. Devuelve (`armado_id`, nuevo). Todo o nada.
|
||||||
|
|
||||||
|
Las hijas llegan sin `armado_id`: se lo pone este cuerpo. Si ya hay un armado
|
||||||
|
con la misma `huella` y el mismo `marco_sha`, no guarda y devuelve ese.
|
||||||
|
"""
|
||||||
|
modelo = type(armado)
|
||||||
|
previo = sesion.exec(
|
||||||
|
select(modelo).where(modelo.huella == armado.huella, modelo.marco_sha == armado.marco_sha)
|
||||||
|
).first()
|
||||||
|
if previo is not None:
|
||||||
|
return previo.armado_id, False
|
||||||
|
try:
|
||||||
|
sesion.add(armado)
|
||||||
|
sesion.flush()
|
||||||
|
armado_id = armado.armado_id
|
||||||
|
for grupo in (exclusiones, miembros, variables):
|
||||||
|
filas = list(grupo)
|
||||||
|
for fila in filas:
|
||||||
|
fila.armado_id = armado_id
|
||||||
|
sesion.add_all(filas)
|
||||||
|
sesion.flush() # los miembros antes que sus variables (llave foránea)
|
||||||
|
sesion.commit()
|
||||||
|
except Exception:
|
||||||
|
sesion.rollback()
|
||||||
|
raise
|
||||||
|
return armado_id, True
|
||||||
|
|
||||||
|
|
||||||
|
def guardar_lote_en(
|
||||||
|
sesion: Session,
|
||||||
|
armado_id: int,
|
||||||
|
procedencia: dict,
|
||||||
|
desenlace: str,
|
||||||
|
riesgos: list[tuple[int, float, float, float | None, float | None]],
|
||||||
|
*,
|
||||||
|
cohortes: TablasCohorte,
|
||||||
|
ahora: datetime | None = None,
|
||||||
|
) -> tuple[int, bool]:
|
||||||
|
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
|
||||||
|
|
||||||
|
No copia nada de MLflow: guarda sus llaves (`PROCEDENCIA`). Puntuar lo mismo
|
||||||
|
otra vez (mismo armado, modelo y riesgos) no duplica: la huella del lote ya está.
|
||||||
|
"""
|
||||||
|
faltan = [c for c in PROCEDENCIA if not procedencia.get(c)]
|
||||||
|
if faltan:
|
||||||
|
raise ValueError(f"La procedencia no trae {faltan}.")
|
||||||
|
miembro = cohortes.CohorteMiembro
|
||||||
|
miembros = set(sesion.exec(select(miembro.pac_id).where(miembro.armado_id == armado_id)))
|
||||||
|
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
|
||||||
|
if ajenos:
|
||||||
|
raise RiesgoFueraDeCohorte(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||||
|
huella = _sha_json({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROCEDENCIA},
|
||||||
|
"riesgos": sorted(riesgos)})
|
||||||
|
lote = cohortes.EvaluacionRiesgoLote
|
||||||
|
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
|
||||||
|
if previo is not None:
|
||||||
|
return previo.lote_id, False
|
||||||
|
momento = ahora or datetime.now(timezone.utc)
|
||||||
|
try:
|
||||||
|
fila = lote(armado_id=armado_id, desenlace=desenlace, evaluado_en=momento, n_evaluaciones=len(riesgos),
|
||||||
|
huella=huella, **{c: str(procedencia[c]) for c in PROCEDENCIA})
|
||||||
|
sesion.add(fila)
|
||||||
|
sesion.flush()
|
||||||
|
sesion.add_all(
|
||||||
|
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, horizonte_anios=float(h), probabilidad=float(p),
|
||||||
|
ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR, registrado_en=momento)
|
||||||
|
for pac, h, p, bajo, alto in riesgos
|
||||||
|
)
|
||||||
|
sesion.commit()
|
||||||
|
except Exception:
|
||||||
|
sesion.rollback()
|
||||||
|
raise
|
||||||
|
return fila.lote_id, True
|
||||||
|
|
||||||
|
|
||||||
|
def cambiar_estado_en(
|
||||||
|
sesion: Session, lote_id: int, estado: str, motivo: str, *, cohortes: TablasCohorte,
|
||||||
|
ahora: datetime | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""Agrega una versión con `estado` a cada evaluación vigente del lote. Devuelve cuántas cambió."""
|
||||||
|
if estado not in (FINAL, ERROR):
|
||||||
|
raise ValueError(f"Estado desconocido: {estado!r} (se confirma a {FINAL!r} o se anula con {ERROR!r}).")
|
||||||
|
e = cohortes.EvaluacionRiesgo
|
||||||
|
ultima = (
|
||||||
|
select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
|
||||||
|
.where(e.lote_id == lote_id)
|
||||||
|
.group_by(e.pac_id, e.horizonte_anios)
|
||||||
|
.subquery()
|
||||||
|
)
|
||||||
|
vigentes = sesion.exec(
|
||||||
|
select(e).join(ultima, (e.pac_id == ultima.c.pac_id) & (e.horizonte_anios == ultima.c.horizonte_anios)
|
||||||
|
& (e.version == ultima.c.version)).where(e.lote_id == lote_id, e.estado != estado)
|
||||||
|
).all()
|
||||||
|
momento = ahora or datetime.now(timezone.utc)
|
||||||
|
try:
|
||||||
|
sesion.add_all(
|
||||||
|
e(lote_id=lote_id, pac_id=v.pac_id, horizonte_anios=v.horizonte_anios, probabilidad=v.probabilidad,
|
||||||
|
ic_bajo=v.ic_bajo, ic_alto=v.ic_alto, version=v.version + 1, estado=estado, motivo=motivo,
|
||||||
|
registrado_en=momento)
|
||||||
|
for v in vigentes
|
||||||
|
)
|
||||||
|
sesion.commit()
|
||||||
|
except Exception:
|
||||||
|
sesion.rollback()
|
||||||
|
raise
|
||||||
|
return len(vigentes)
|
||||||
|
|
||||||
|
|
||||||
|
def _sha_json(objeto) -> str:
|
||||||
|
"""sha256 del JSON canónico (el mismo de `indicadores_kit.oro.cohortes.definicion.sha_json`)."""
|
||||||
|
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
||||||
|
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
||||||
+12
-12
@@ -1,6 +1,6 @@
|
|||||||
"""Oro: el catálogo de publicación (§6f, MD-19), `cat_measure*` y `cat_estrato*`, sincronizado con los TOML del kit.
|
"""Oro: el catálogo de publicación (§6f, MD-19), `cat_measure*` y `cat_estrato*`, sincronizado con los TOML del kit.
|
||||||
|
|
||||||
Las filas llegan ya armadas y por capas (`webapi.orchestration.reference.publicacion.semillas_de`). No se
|
Las filas llegan ya armadas y por capas (`indicadores_kit.registry.publicacion.semillas_de`). No se
|
||||||
reemplazan enteras: las unidades de los reportes guardados apuntan a `cat_measure_resultado` y a
|
reemplazan enteras: las unidades de los reportes guardados apuntan a `cat_measure_resultado` y a
|
||||||
`cat_estrato_valor`. Se inserta o actualiza por llave, y se borra solo lo que ya no viene **y nadie usa**.
|
`cat_estrato_valor`. Se inserta o actualiza por llave, y se borra solo lo que ya no viene **y nadie usa**.
|
||||||
Lo que una fila de otra tabla todavía referencia se queda.
|
Lo que una fila de otra tabla todavía referencia se queda.
|
||||||
@@ -15,25 +15,25 @@ from sqlmodel import Session, SQLModel, select
|
|||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
class PublicationRepository(Repository):
|
class PublicacionRepository(Repository):
|
||||||
"""Las siete tablas del catálogo de publicación de un dominio, en orden de llaves foráneas."""
|
"""Las siete tablas del catálogo de publicación de un dominio, en orden de llaves foráneas."""
|
||||||
|
|
||||||
def __init__(self, session_factory: Callable[[], Session], modelos: Sequence[type[SQLModel]]):
|
def __init__(self, session_factory: Callable[[], Session], modelos: Sequence[type[SQLModel]]):
|
||||||
super().__init__(session_factory, modelos[0])
|
super().__init__(session_factory, modelos[0])
|
||||||
self.modelos = tuple(modelos)
|
self.modelos = tuple(modelos)
|
||||||
|
|
||||||
def sync(self, capas: Iterable[Iterable[SQLModel]]) -> dict[str, int]:
|
def sincronizar(self, capas: Iterable[Iterable[SQLModel]]) -> dict[str, int]:
|
||||||
"""Inserta o actualiza las filas, capa por capa, y borra lo que no vino y nadie usa. Una sesión, todo o nada."""
|
"""Inserta o actualiza las filas, capa por capa, y borra lo que no vino y nadie usa. Una sesión, todo o nada."""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return sync_publication_in(sesion, capas, self.modelos)
|
return sincronizar_publicacion_en(sesion, capas, self.modelos)
|
||||||
|
|
||||||
|
|
||||||
def sync_publication_in(
|
def sincronizar_publicacion_en(
|
||||||
sesion: Session, capas: Iterable[Iterable[SQLModel]], modelos: Sequence[type[SQLModel]]
|
sesion: Session, capas: Iterable[Iterable[SQLModel]], modelos: Sequence[type[SQLModel]]
|
||||||
) -> dict[str, int]:
|
) -> dict[str, int]:
|
||||||
"""El cuerpo de `PublicationRepository.sincronizar`, sobre una sesión que se recibe.
|
"""El cuerpo de `PublicacionRepository.sincronizar`, sobre una sesión que se recibe.
|
||||||
|
|
||||||
`capas`: listas de filas, cada una con sus padres en una capa anterior. `event_models`: las tablas que se
|
`capas`: listas de filas, cada una con sus padres en una capa anterior. `modelos`: las tablas que se
|
||||||
sincronizan, padres antes que hijos; de ellas se borra lo que no vino, de los hijos a los padres.
|
sincronizan, padres antes que hijos; de ellas se borra lo que no vino, de los hijos a los padres.
|
||||||
Devuelve cuántas filas llegaron, cuántas se borraron y cuántas se conservaron por estar en uso.
|
Devuelve cuántas filas llegaron, cuántas se borraron y cuántas se conservaron por estar en uso.
|
||||||
"""
|
"""
|
||||||
@@ -42,15 +42,15 @@ def sync_publication_in(
|
|||||||
try:
|
try:
|
||||||
for capa in capas:
|
for capa in capas:
|
||||||
for fila in capa:
|
for fila in capa:
|
||||||
vienen.setdefault(type(fila), set()).add(_key(fila))
|
vienen.setdefault(type(fila), set()).add(_llave(fila))
|
||||||
sesion.merge(fila)
|
sesion.merge(fila)
|
||||||
cuenta["filas"] += 1
|
cuenta["filas"] += 1
|
||||||
sesion.flush()
|
sesion.flush()
|
||||||
for modelo in reversed(modelos):
|
for modelo in reversed(modelos):
|
||||||
for fila in sesion.exec(select(modelo)).all():
|
for fila in sesion.exec(select(modelo)).all():
|
||||||
if _key(fila) in vienen[modelo]:
|
if _llave(fila) in vienen[modelo]:
|
||||||
continue
|
continue
|
||||||
if _in_use(sesion, fila):
|
if _en_uso(sesion, fila):
|
||||||
cuenta["en_uso"] += 1
|
cuenta["en_uso"] += 1
|
||||||
continue
|
continue
|
||||||
sesion.delete(fila)
|
sesion.delete(fila)
|
||||||
@@ -63,11 +63,11 @@ def sync_publication_in(
|
|||||||
return cuenta
|
return cuenta
|
||||||
|
|
||||||
|
|
||||||
def _key(fila: SQLModel) -> tuple:
|
def _llave(fila: SQLModel) -> tuple:
|
||||||
return tuple(getattr(fila, columna.name) for columna in type(fila).__table__.primary_key.columns)
|
return tuple(getattr(fila, columna.name) for columna in type(fila).__table__.primary_key.columns)
|
||||||
|
|
||||||
|
|
||||||
def _in_use(sesion: Session, fila: SQLModel) -> bool:
|
def _en_uso(sesion: Session, fila: SQLModel) -> bool:
|
||||||
"""Si alguna fila de otra tabla del mismo registro apunta a esta por una llave foránea."""
|
"""Si alguna fila de otra tabla del mismo registro apunta a esta por una llave foránea."""
|
||||||
tabla = type(fila).__table__
|
tabla = type(fila).__table__
|
||||||
for otra in tabla.metadata.tables.values():
|
for otra in tabla.metadata.tables.values():
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación y la verificación."""
|
||||||
|
|
||||||
|
from persistance.aristas.plata.carga import (
|
||||||
|
CargaRepository,
|
||||||
|
abrir_carga,
|
||||||
|
cerrar_carga,
|
||||||
|
guardar_carga_en,
|
||||||
|
)
|
||||||
|
from persistance.aristas.plata.catalogos import CatalogoRepository
|
||||||
|
from persistance.aristas.plata.observacion import ObservacionRepository
|
||||||
|
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||||
|
from persistance.aristas.plata.vinculos import VinculosRepository
|
||||||
|
from persistance.aristas.plata.vistas import VistasRepository
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CargaRepository",
|
||||||
|
"CatalogoRepository",
|
||||||
|
"ObservacionRepository",
|
||||||
|
"VinculosRepository",
|
||||||
|
"VistasRepository",
|
||||||
|
"abrir_carga",
|
||||||
|
"cerrar_carga",
|
||||||
|
"guardar_carga_en",
|
||||||
|
"guardar_plata_en",
|
||||||
|
]
|
||||||
+21
-21
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Desde F6 (ADR-MD-009) no hay tablas de hechos por tipo ni sus versiones: el kit arma la
|
Desde F6 (ADR-MD-009) no hay tablas de hechos por tipo ni sus versiones: el kit arma la
|
||||||
plata del staging directo (`plata_desde_staging`) y aquí se escribe en una transacción
|
plata del staging directo (`plata_desde_staging`) y aquí se escribe en una transacción
|
||||||
(`save_load_in`, con `save_silver_in`). Aquí no se sabe qué es un indicador.
|
(`guardar_carga_en`, con `guardar_plata_en`). Aquí no se sabe qué es un indicador.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -13,13 +13,13 @@ from typing import TypeVar
|
|||||||
from core.indicadores.comunes import CargaBase, PersonaBase
|
from core.indicadores.comunes import CargaBase, PersonaBase
|
||||||
from sqlmodel import Session, SQLModel
|
from sqlmodel import Session, SQLModel
|
||||||
|
|
||||||
from persistance.edges.silver.procedures import save_silver_in
|
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
LoadT = TypeVar("LoadT", bound=CargaBase)
|
CargaT = TypeVar("CargaT", bound=CargaBase)
|
||||||
|
|
||||||
|
|
||||||
class LoadRepository(Repository[LoadT]):
|
class CargaRepository(Repository[CargaT]):
|
||||||
"""Las cargas de un dominio. Una carga se escribe aquí, entera.
|
"""Las cargas de un dominio. Una carga se escribe aquí, entera.
|
||||||
|
|
||||||
`persona` es la tabla de personas del mismo dominio: la carga agrega
|
`persona` es la tabla de personas del mismo dominio: la carga agrega
|
||||||
@@ -30,7 +30,7 @@ class LoadRepository(Repository[LoadT]):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
session_factory: Callable[[], Session],
|
session_factory: Callable[[], Session],
|
||||||
model: type[LoadT],
|
model: type[CargaT],
|
||||||
*,
|
*,
|
||||||
persona: type[PersonaBase],
|
persona: type[PersonaBase],
|
||||||
procedimiento: type[SQLModel] | None = None,
|
procedimiento: type[SQLModel] | None = None,
|
||||||
@@ -41,24 +41,24 @@ class LoadRepository(Repository[LoadT]):
|
|||||||
self.procedimiento = procedimiento
|
self.procedimiento = procedimiento
|
||||||
self.observacion = observacion
|
self.observacion = observacion
|
||||||
|
|
||||||
def save_load(
|
def guardar_carga(
|
||||||
self, *, fuente: str, personas: Iterable[PersonaBase], plata, codigo_sha: str | None = None
|
self, *, fuente: str, personas: Iterable[PersonaBase], plata, codigo_sha: str | None = None
|
||||||
) -> LoadT:
|
) -> CargaT:
|
||||||
"""Escribe una carga con una sola sesión y devuelve su fila de `carga` (`save_load_in`)."""
|
"""Escribe una carga con una sola sesión y devuelve su fila de `carga` (`guardar_carga_en`)."""
|
||||||
if self.procedimiento is None or self.observacion is None:
|
if self.procedimiento is None or self.observacion is None:
|
||||||
raise ValueError("Una carga con plata necesita las tablas procedimiento, observacion.")
|
raise ValueError("Una carga con plata necesita las tablas procedimiento, observacion.")
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return save_load_in(
|
return guardar_carga_en(
|
||||||
sesion, carga=self.model, persona=self.persona, procedimiento=self.procedimiento,
|
sesion, carga=self.model, persona=self.persona, procedimiento=self.procedimiento,
|
||||||
observacion=self.observacion, fuente=fuente, personas=personas, plata=plata,
|
observacion=self.observacion, fuente=fuente, personas=personas, plata=plata,
|
||||||
codigo_sha=codigo_sha,
|
codigo_sha=codigo_sha,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def save_load_in(
|
def guardar_carga_en(
|
||||||
sesion: Session,
|
sesion: Session,
|
||||||
*,
|
*,
|
||||||
carga: type[LoadT],
|
carga: type[CargaT],
|
||||||
persona: type[PersonaBase],
|
persona: type[PersonaBase],
|
||||||
procedimiento: type[SQLModel],
|
procedimiento: type[SQLModel],
|
||||||
observacion: type[SQLModel],
|
observacion: type[SQLModel],
|
||||||
@@ -66,7 +66,7 @@ def save_load_in(
|
|||||||
personas: Iterable[PersonaBase],
|
personas: Iterable[PersonaBase],
|
||||||
plata,
|
plata,
|
||||||
codigo_sha: str | None = None,
|
codigo_sha: str | None = None,
|
||||||
) -> LoadT:
|
) -> CargaT:
|
||||||
"""La carga del staging directo (T-20c): personas y plata, sin tablas por tipo. Una transacción.
|
"""La carga del staging directo (T-20c): personas y plata, sin tablas por tipo. Una transacción.
|
||||||
|
|
||||||
Los contadores de `carga` cuentan **procedimientos** por su efecto: nuevos; cambiados, ellos o
|
Los contadores de `carga` cuentan **procedimientos** por su efecto: nuevos; cambiados, ellos o
|
||||||
@@ -76,9 +76,9 @@ def save_load_in(
|
|||||||
Se puede repetir: lo que no cambió no se toca. Todo o nada.
|
Se puede repetir: lo que no cambió no se toca. Todo o nada.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
fila = open_load(sesion, carga, fuente=fuente, codigo_sha=codigo_sha)
|
fila = abrir_carga(sesion, carga, fuente=fuente, codigo_sha=codigo_sha)
|
||||||
_put_persons(sesion, persona, personas)
|
_poner_personas(sesion, persona, personas)
|
||||||
cuenta = save_silver_in(sesion, plata, procedimiento=procedimiento, observacion=observacion,
|
cuenta = guardar_plata_en(sesion, plata, procedimiento=procedimiento, observacion=observacion,
|
||||||
carga_id=fila.carga_id)
|
carga_id=fila.carga_id)
|
||||||
fila.filas_nuevas = cuenta["procedimientos_nuevos"]
|
fila.filas_nuevas = cuenta["procedimientos_nuevos"]
|
||||||
fila.filas_cambiadas = cuenta["procedimientos_tocados"]
|
fila.filas_cambiadas = cuenta["procedimientos_tocados"]
|
||||||
@@ -86,7 +86,7 @@ def save_load_in(
|
|||||||
- cuenta["procedimientos_nuevos"] - cuenta["procedimientos_tocados"])
|
- cuenta["procedimientos_nuevos"] - cuenta["procedimientos_tocados"])
|
||||||
descartes = {**plata.descartes, **({"huerfanos": cuenta["huerfanos"]} if cuenta["huerfanos"] else {})}
|
descartes = {**plata.descartes, **({"huerfanos": cuenta["huerfanos"]} if cuenta["huerfanos"] else {})}
|
||||||
fila.descartes = json.dumps(descartes, sort_keys=True, ensure_ascii=False) if descartes else None
|
fila.descartes = json.dumps(descartes, sort_keys=True, ensure_ascii=False) if descartes else None
|
||||||
close_load(sesion, fila)
|
cerrar_carga(sesion, fila)
|
||||||
sesion.commit()
|
sesion.commit()
|
||||||
except Exception:
|
except Exception:
|
||||||
sesion.rollback()
|
sesion.rollback()
|
||||||
@@ -95,7 +95,7 @@ def save_load_in(
|
|||||||
return fila
|
return fila
|
||||||
|
|
||||||
|
|
||||||
def _put_persons(sesion: Session, persona: type[PersonaBase], personas: Iterable[PersonaBase]) -> None:
|
def _poner_personas(sesion: Session, persona: type[PersonaBase], personas: Iterable[PersonaBase]) -> None:
|
||||||
"""Agrega las personas que falten y pone al día las que ya estaban."""
|
"""Agrega las personas que falten y pone al día las que ya estaban."""
|
||||||
for nueva in personas:
|
for nueva in personas:
|
||||||
actual = sesion.get(persona, nueva.pac_id)
|
actual = sesion.get(persona, nueva.pac_id)
|
||||||
@@ -110,9 +110,9 @@ def _put_persons(sesion: Session, persona: type[PersonaBase], personas: Iterable
|
|||||||
sesion.flush()
|
sesion.flush()
|
||||||
|
|
||||||
|
|
||||||
def open_load(
|
def abrir_carga(
|
||||||
sesion: Session, carga: type[LoadT], fuente: str, codigo_sha: str | None = None
|
sesion: Session, carga: type[CargaT], fuente: str, codigo_sha: str | None = None
|
||||||
) -> LoadT:
|
) -> CargaT:
|
||||||
"""Registra el inicio de una carga y devuelve su fila, ya con `carga_id`."""
|
"""Registra el inicio de una carga y devuelve su fila, ya con `carga_id`."""
|
||||||
fila = carga(fuente=fuente, inicio=datetime.now(timezone.utc), codigo_sha=codigo_sha)
|
fila = carga(fuente=fuente, inicio=datetime.now(timezone.utc), codigo_sha=codigo_sha)
|
||||||
sesion.add(fila)
|
sesion.add(fila)
|
||||||
@@ -120,7 +120,7 @@ def open_load(
|
|||||||
return fila
|
return fila
|
||||||
|
|
||||||
|
|
||||||
def close_load(sesion: Session, carga: CargaBase) -> None:
|
def cerrar_carga(sesion: Session, carga: CargaBase) -> None:
|
||||||
"""Registra el fin de una carga; los conteos ya van en la fila."""
|
"""Registra el fin de una carga; los conteos ya van en la fila."""
|
||||||
carga.fin = datetime.now(timezone.utc)
|
carga.fin = datetime.now(timezone.utc)
|
||||||
sesion.add(carga)
|
sesion.add(carga)
|
||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
"""Plata: `catalogs`, materializar el catálogo del proyecto en `cat_estudio`, `cat_resultado` y `cat_valor`.
|
"""Plata: `catalogos`, materializar el catálogo del proyecto en `cat_estudio`, `cat_resultado` y `cat_valor`.
|
||||||
|
|
||||||
Las filas llegan ya armadas (el kit lee `core/catalogos/<proyecto>.toml`). Nada se
|
Las filas llegan ya armadas (el kit lee `core/catalogos/<proyecto>.toml`). Nada se
|
||||||
borra: un valor que salió del archivo pasa a `retirado`, porque lo pueden seguir
|
borra: un valor que salió del archivo pasa a `retirado`, porque lo pueden seguir
|
||||||
@@ -12,7 +12,7 @@ from sqlmodel import Session, SQLModel, select
|
|||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
class CatalogRepository(Repository):
|
class CatalogoRepository(Repository):
|
||||||
"""Las tres tablas de catálogo de un dominio. `get`, `list` y `count` leen los estudios."""
|
"""Las tres tablas de catálogo de un dominio. `get`, `list` y `count` leen los estudios."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -26,7 +26,7 @@ class CatalogRepository(Repository):
|
|||||||
self.resultado = resultado
|
self.resultado = resultado
|
||||||
self.valor = valor
|
self.valor = valor
|
||||||
|
|
||||||
def sync(
|
def sincronizar(
|
||||||
self, estudios: Iterable[SQLModel], resultados: Iterable[SQLModel], valores: Iterable[SQLModel]
|
self, estudios: Iterable[SQLModel], resultados: Iterable[SQLModel], valores: Iterable[SQLModel]
|
||||||
) -> dict[str, int]:
|
) -> dict[str, int]:
|
||||||
"""Inserta o actualiza por llave y retira los valores que ya no vienen. Una sesión, todo o nada.
|
"""Inserta o actualiza por llave y retira los valores que ya no vienen. Una sesión, todo o nada.
|
||||||
+4
-4
@@ -1,16 +1,16 @@
|
|||||||
"""Plata: `observe`, reemplazar `periodo_observacion` con las filas que se calculan en la misma sesión."""
|
"""Plata: `observar`, reemplazar `periodo_observacion` con las filas que se calculan en la misma sesión."""
|
||||||
|
|
||||||
from collections.abc import Callable, Iterable
|
from collections.abc import Callable, Iterable
|
||||||
|
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
from persistance.edges.common import ReferenceRepository, replace_in
|
from persistance.aristas.comun import RegistroRepository, reemplazar_en
|
||||||
|
|
||||||
|
|
||||||
class ObservationRepository(ReferenceRepository):
|
class ObservacionRepository(RegistroRepository):
|
||||||
"""`periodo_observacion` de un dominio."""
|
"""`periodo_observacion` de un dominio."""
|
||||||
|
|
||||||
def observar(self, periodos: Callable[[Session], Iterable]) -> int:
|
def observar(self, periodos: Callable[[Session], Iterable]) -> int:
|
||||||
"""Calcula los periodos con `periodos(sesion)` y deja la tabla con exactamente esos. Devuelve cuántos."""
|
"""Calcula los periodos con `periodos(sesion)` y deja la tabla con exactamente esos. Devuelve cuántos."""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return replace_in(sesion, self.model, periodos(sesion))
|
return reemplazar_en(sesion, self.model, periodos(sesion))
|
||||||
+14
-14
@@ -24,12 +24,12 @@ import logging
|
|||||||
|
|
||||||
from sqlmodel import Session, SQLModel, select
|
from sqlmodel import Session, SQLModel, select
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
registro = logging.getLogger(__name__)
|
||||||
|
|
||||||
KEY = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
|
LLAVE = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
|
||||||
|
|
||||||
|
|
||||||
def save_silver_in(
|
def guardar_plata_en(
|
||||||
sesion: Session, plata, *, procedimiento: type[SQLModel], observacion: type[SQLModel], carga_id: int
|
sesion: Session, plata, *, procedimiento: type[SQLModel], observacion: type[SQLModel], carga_id: int
|
||||||
) -> dict[str, int]:
|
) -> dict[str, int]:
|
||||||
"""Escribe los procedimientos y las observaciones del lote. Devuelve cuántos se agregaron y cuántos cambiaron.
|
"""Escribe los procedimientos y las observaciones del lote. Devuelve cuántos se agregaron y cuántos cambiaron.
|
||||||
@@ -45,16 +45,16 @@ def save_silver_in(
|
|||||||
huerfanos: set = set()
|
huerfanos: set = set()
|
||||||
nuevos: set = set()
|
nuevos: set = set()
|
||||||
tocados: set = set()
|
tocados: set = set()
|
||||||
existentes = {tuple(getattr(fila, c) for c in KEY): fila for fila in sesion.exec(select(procedimiento))}
|
existentes = {tuple(getattr(fila, c) for c in LLAVE): fila for fila in sesion.exec(select(procedimiento))}
|
||||||
ordenes: dict[int, SQLModel] = {}
|
ordenes: dict[int, SQLModel] = {}
|
||||||
for fila in sorted(existentes.values(), key=lambda f: f.procedimiento_id):
|
for fila in sorted(existentes.values(), key=lambda f: f.procedimiento_id):
|
||||||
if fila.clase == "orden" and fila.numero_hospital is not None:
|
if fila.clase == "orden" and fila.numero_hospital is not None:
|
||||||
ordenes.setdefault(fila.numero_hospital, fila)
|
ordenes.setdefault(fila.numero_hospital, fila)
|
||||||
|
|
||||||
for p in plata.procedimientos:
|
for p in plata.procedimientos:
|
||||||
padre = _parent(p["padres"], existentes, ordenes)
|
padre = _padre(p["padres"], existentes, ordenes)
|
||||||
datos = {c: v for c, v in p.items() if c not in ("llave", "padres", "fecha_del_padre")}
|
datos = {c: v for c, v in p.items() if c not in ("llave", "padres", "fecha_del_padre")}
|
||||||
datos.update(dict(zip(KEY, p["llave"])))
|
datos.update(dict(zip(LLAVE, p["llave"])))
|
||||||
datos["padre_id"] = None if padre is None else padre.procedimiento_id
|
datos["padre_id"] = None if padre is None else padre.procedimiento_id
|
||||||
if datos.get("pac_id") is None:
|
if datos.get("pac_id") is None:
|
||||||
if padre is None:
|
if padre is None:
|
||||||
@@ -71,12 +71,12 @@ def save_silver_in(
|
|||||||
existentes[p["llave"]] = fila
|
existentes[p["llave"]] = fila
|
||||||
cuenta["procedimientos_nuevos"] += 1
|
cuenta["procedimientos_nuevos"] += 1
|
||||||
nuevos.add(p["llave"])
|
nuevos.add(p["llave"])
|
||||||
elif _update(fila, datos, carga_id):
|
elif _actualizar(fila, datos, carga_id):
|
||||||
cuenta["procedimientos_cambiados"] += 1
|
cuenta["procedimientos_cambiados"] += 1
|
||||||
tocados.add(p["llave"])
|
tocados.add(p["llave"])
|
||||||
if fila.clase == "orden" and fila.numero_hospital is not None:
|
if fila.clase == "orden" and fila.numero_hospital is not None:
|
||||||
ordenes.setdefault(fila.numero_hospital, fila)
|
ordenes.setdefault(fila.numero_hospital, fila)
|
||||||
ligados_tarde = _link_to_its_order(existentes.values(), ordenes, carga_id)
|
ligados_tarde = _ligar_con_su_orden(existentes.values(), ordenes, carga_id)
|
||||||
cuenta["procedimientos_cambiados"] += ligados_tarde
|
cuenta["procedimientos_cambiados"] += ligados_tarde
|
||||||
|
|
||||||
ids = [fila.procedimiento_id for fila in existentes.values()]
|
ids = [fila.procedimiento_id for fila in existentes.values()]
|
||||||
@@ -96,7 +96,7 @@ def save_silver_in(
|
|||||||
if fila is None:
|
if fila is None:
|
||||||
sesion.add(observacion.model_validate({**datos, "carga_id": carga_id}))
|
sesion.add(observacion.model_validate({**datos, "carga_id": carga_id}))
|
||||||
cuenta["observaciones_nuevas"] += 1
|
cuenta["observaciones_nuevas"] += 1
|
||||||
elif _update(fila, datos, carga_id):
|
elif _actualizar(fila, datos, carga_id):
|
||||||
cuenta["observaciones_cambiadas"] += 1
|
cuenta["observaciones_cambiadas"] += 1
|
||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
@@ -106,16 +106,16 @@ def save_silver_in(
|
|||||||
cuenta["huerfanos"] = len(huerfanos)
|
cuenta["huerfanos"] = len(huerfanos)
|
||||||
cuenta["procedimientos_tocados"] = len(tocados) + ligados_tarde
|
cuenta["procedimientos_tocados"] = len(tocados) + ligados_tarde
|
||||||
if huerfanos:
|
if huerfanos:
|
||||||
log.warning("%d procedimientos sin paciente ni padre no se escribieron (p. ej. %s).",
|
registro.warning("%d procedimientos sin paciente ni padre no se escribieron (p. ej. %s).",
|
||||||
len(huerfanos), sorted(huerfanos)[0])
|
len(huerfanos), sorted(huerfanos)[0])
|
||||||
return cuenta
|
return cuenta
|
||||||
|
|
||||||
|
|
||||||
def _link_to_its_order(procedimientos, ordenes: dict, carga_id: int) -> int:
|
def _ligar_con_su_orden(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||||
"""Los procedimientos sin padre que traen un número de orden, ligados a la orden que ya llegó.
|
"""Los procedimientos sin padre que traen un número de orden, ligados a la orden que ya llegó.
|
||||||
|
|
||||||
Las órdenes pueden llegar en un lote posterior al de sus tomas (en CaCu, las tomas en
|
Las órdenes pueden llegar en un lote posterior al de sus tomas (en CaCu, las tomas en
|
||||||
`load` y las órdenes en `cargar_resultados`). Devuelve cuántos se ligaron.
|
`cargar` y las órdenes en `cargar_resultados`). Devuelve cuántos se ligaron.
|
||||||
"""
|
"""
|
||||||
ligados = 0
|
ligados = 0
|
||||||
for fila in procedimientos:
|
for fila in procedimientos:
|
||||||
@@ -127,7 +127,7 @@ def _link_to_its_order(procedimientos, ordenes: dict, carga_id: int) -> int:
|
|||||||
return ligados
|
return ligados
|
||||||
|
|
||||||
|
|
||||||
def _parent(padres, existentes: dict, ordenes: dict):
|
def _padre(padres, existentes: dict, ordenes: dict):
|
||||||
"""El primer padre que se encuentre: por su llave, o la orden por su número del hospital."""
|
"""El primer padre que se encuentre: por su llave, o la orden por su número del hospital."""
|
||||||
for llave in padres:
|
for llave in padres:
|
||||||
fila = ordenes.get(llave[1]) if llave[0] == "orden" and len(llave) == 2 else existentes.get(tuple(llave))
|
fila = ordenes.get(llave[1]) if llave[0] == "orden" and len(llave) == 2 else existentes.get(tuple(llave))
|
||||||
@@ -136,7 +136,7 @@ def _parent(padres, existentes: dict, ordenes: dict):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _update(fila: SQLModel, datos: dict, carga_id: int) -> bool:
|
def _actualizar(fila: SQLModel, datos: dict, carga_id: int) -> bool:
|
||||||
"""Pone en la fila lo que cambió; si algo cambió, también su `carga_id`. Devuelve si cambió."""
|
"""Pone en la fila lo que cambió; si algo cambió, también su `carga_id`. Devuelve si cambió."""
|
||||||
cambios = {c: v for c, v in datos.items() if getattr(fila, c) != v}
|
cambios = {c: v for c, v in datos.items() if getattr(fila, c) != v}
|
||||||
for columna, valor in cambios.items():
|
for columna, valor in cambios.items():
|
||||||
+4
-4
@@ -10,13 +10,13 @@ from persistance.repository import Repository
|
|||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
class LinksRepository(Repository):
|
class VinculosRepository(Repository):
|
||||||
"""Cuenta, con lo que calcula el kit sobre la sesión, cuántos resultados encuentran su toma."""
|
"""Cuenta, con lo que calcula el kit sobre la sesión, cuántos resultados encuentran su toma."""
|
||||||
|
|
||||||
def __init__(self, session_factory):
|
def __init__(self, session_factory):
|
||||||
super().__init__(session_factory, None)
|
super().__init__(session_factory, None)
|
||||||
|
|
||||||
def check(self, check: Callable[[Session], T]) -> T:
|
def verificar(self, verificar: Callable[[Session], T]) -> T:
|
||||||
"""Corre `check(sesion)` en una sesión de solo lectura (no hace commit)."""
|
"""Corre `verificar(sesion)` en una sesión de solo lectura (no hace commit)."""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
return check(sesion)
|
return verificar(sesion)
|
||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
"""Plata: las vistas de un dominio (desde F6, solo `v_persona`; ADR-MD-009).
|
"""Plata: las vistas de un dominio (desde F6, solo `v_persona`; ADR-MD-009).
|
||||||
|
|
||||||
Las define el ciclo, como sentencias DDL ya armadas y en orden (`webapi.orchestration.silver.views`, dbt's views);
|
Las define el kit, como sentencias DDL ya armadas y en orden (`indicadores_kit.esquema.ddl_de_vistas`);
|
||||||
aquí solo se ejecutan, en una transacción.
|
aquí solo se ejecutan, en una transacción.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -12,13 +12,13 @@ from sqlalchemy.sql.expression import Executable
|
|||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
class ViewsRepository(Repository):
|
class VistasRepository(Repository):
|
||||||
"""Las vistas no tienen modelo: se crean o reemplazan con la DDL que se recibe."""
|
"""Las vistas no tienen modelo: se crean o reemplazan con la DDL que se recibe."""
|
||||||
|
|
||||||
def __init__(self, session_factory):
|
def __init__(self, session_factory):
|
||||||
super().__init__(session_factory, None)
|
super().__init__(session_factory, None)
|
||||||
|
|
||||||
def build_all(self, ddl: Iterable[Executable]) -> list[str]:
|
def construir(self, ddl: Iterable[Executable]) -> list[str]:
|
||||||
"""Ejecuta cada sentencia en orden, en una transacción. Devuelve los nombres de las vistas de la base."""
|
"""Ejecuta cada sentencia en orden, en una transacción. Devuelve los nombres de las vistas de la base."""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
conexion = sesion.connection()
|
conexion = sesion.connection()
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
"""Assets: what each step of a Hamilton graph reads and produces.
|
|
||||||
|
|
||||||
A function named after the asset it produces returns an `Asset`; its parameters are the assets it
|
|
||||||
reads. Tags describe each producing function: `layer` (a `Layer`), `owner` (an `Owner`),
|
|
||||||
`depends_on` (parameters that only order the step, without passing data) and `deprecated_by` (the
|
|
||||||
dbt selector that will replace it). This module doesn't import Hamilton: `validate` and `mermaid`
|
|
||||||
work on the nodes a driver lists with `list_available_variables()`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from collections.abc import Iterable
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from enum import StrEnum
|
|
||||||
|
|
||||||
|
|
||||||
class Layer(StrEnum):
|
|
||||||
BRONZE = "bronze"
|
|
||||||
SILVER = "silver"
|
|
||||||
GOLD = "gold"
|
|
||||||
MODEL = "model"
|
|
||||||
|
|
||||||
|
|
||||||
class Owner(StrEnum):
|
|
||||||
EXTERNAL = "external"
|
|
||||||
PYTHON = "python"
|
|
||||||
DBT = "dbt"
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class Asset:
|
|
||||||
"""An asset as a step leaves it: a handle to what was written, never the data."""
|
|
||||||
|
|
||||||
name: str
|
|
||||||
rows: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class InvalidGraph(ValueError):
|
|
||||||
"""A graph whose assets don't line up; the message lists every problem, one per line."""
|
|
||||||
|
|
||||||
|
|
||||||
def validate(nodes: Iterable, sources: Iterable[str] = ()) -> None:
|
|
||||||
"""Raise `InvalidGraph` unless every asset has a producer or is a declared source, every
|
|
||||||
producing function has valid `layer` and `owner` tags, and every `depends_on` is a parameter."""
|
|
||||||
sources = set(sources)
|
|
||||||
problems = []
|
|
||||||
for node in nodes:
|
|
||||||
if node.is_external_input:
|
|
||||||
if _produces_asset(node) and node.name not in sources:
|
|
||||||
problems.append(f"{node.name}: read as an asset, but nothing produces it and it isn't a declared source")
|
|
||||||
continue
|
|
||||||
if _produces_asset(node):
|
|
||||||
layer, owner = node.tags.get("layer"), node.tags.get("owner")
|
|
||||||
if layer not in {value.value for value in Layer}:
|
|
||||||
problems.append(f"{node.name}: `layer` tag is {layer!r}; expected one of {[value.value for value in Layer]}")
|
|
||||||
if owner not in {value.value for value in Owner}:
|
|
||||||
problems.append(f"{node.name}: `owner` tag is {owner!r}; expected one of {[value.value for value in Owner]}")
|
|
||||||
for name in _tag_values(node, "depends_on"):
|
|
||||||
if name not in _dependencies(node):
|
|
||||||
problems.append(f"{node.name}: `depends_on` names {name!r}, which isn't one of its parameters")
|
|
||||||
if problems:
|
|
||||||
raise InvalidGraph("\n".join(problems))
|
|
||||||
|
|
||||||
|
|
||||||
def mermaid(nodes: Iterable) -> str:
|
|
||||||
"""The asset graph as a Mermaid flowchart: one box per asset with its layer and owner, an arrow
|
|
||||||
from each asset to the assets that read it, dotted when the dependency only orders the step.
|
|
||||||
Functions that don't produce an asset (a dict split with `@extract_fields`, a configuration
|
|
||||||
value) don't appear: an arrow goes through them to the nearest asset upstream."""
|
|
||||||
by_name = {node.name: node for node in nodes}
|
|
||||||
assets = sorted(name for name, node in by_name.items() if _produces_asset(node))
|
|
||||||
lines = ["flowchart LR"]
|
|
||||||
for name in assets:
|
|
||||||
node = by_name[name]
|
|
||||||
layer, owner = node.tags.get("layer", "?"), node.tags.get("owner", "source")
|
|
||||||
lines.append(f' {name}["{name}<br/>{layer} · {owner}"]')
|
|
||||||
for name in assets:
|
|
||||||
order_only = set(_tag_values(by_name[name], "depends_on"))
|
|
||||||
for upstream in sorted(_upstream_assets(by_name, name)):
|
|
||||||
arrow = "-.->" if upstream in order_only else "-->"
|
|
||||||
lines.append(f" {upstream} {arrow} {name}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def _produces_asset(node) -> bool:
|
|
||||||
return isinstance(node.type, type) and issubclass(node.type, Asset)
|
|
||||||
|
|
||||||
|
|
||||||
def _dependencies(node) -> set[str]:
|
|
||||||
return set(node.required_dependencies) | set(node.optional_dependencies)
|
|
||||||
|
|
||||||
|
|
||||||
def _tag_values(node, tag: str) -> list[str]:
|
|
||||||
value = node.tags.get(tag)
|
|
||||||
if value is None:
|
|
||||||
return []
|
|
||||||
values = value if isinstance(value, (list, tuple)) else str(value).split(",")
|
|
||||||
return [item.strip() for item in values if item.strip()]
|
|
||||||
|
|
||||||
|
|
||||||
def _upstream_assets(by_name: dict, name: str) -> set[str]:
|
|
||||||
found, pending, seen = set(), list(_dependencies(by_name[name])), set()
|
|
||||||
while pending:
|
|
||||||
current = pending.pop()
|
|
||||||
if current in seen or current not in by_name:
|
|
||||||
continue
|
|
||||||
seen.add(current)
|
|
||||||
if _produces_asset(by_name[current]):
|
|
||||||
found.add(current)
|
|
||||||
elif not by_name[current].is_external_input:
|
|
||||||
pending.extend(_dependencies(by_name[current]))
|
|
||||||
return found
|
|
||||||
@@ -40,24 +40,16 @@ from core.cacu.models import (
|
|||||||
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
|
|
||||||
from persistance.edges.bronze import StagingRepository
|
from persistance.aristas.bronce import StagingRepository
|
||||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
from persistance.aristas.comun import RegistroRepository
|
||||||
from persistance.edges.common import ReferenceRepository
|
from persistance.materializador import Materializador
|
||||||
from persistance.materializer import Materializer
|
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||||
from persistance.edges.gold import (
|
from persistance.aristas.plata import (
|
||||||
CalculationRepository,
|
CargaRepository,
|
||||||
CohortRepository,
|
CatalogoRepository,
|
||||||
MeasureHistoryRepository,
|
ObservacionRepository,
|
||||||
MeasureReportRepository,
|
VinculosRepository,
|
||||||
PublicationRepository,
|
VistasRepository,
|
||||||
)
|
|
||||||
from persistance.edges.silver import (
|
|
||||||
LoadRepository,
|
|
||||||
CatalogRepository,
|
|
||||||
ObservationRepository,
|
|
||||||
TimelineRepository,
|
|
||||||
LinksRepository,
|
|
||||||
ViewsRepository,
|
|
||||||
)
|
)
|
||||||
from persistance.db import get_cacu_session
|
from persistance.db import get_cacu_session
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
@@ -71,23 +63,23 @@ biometria_hematica_repository = Repository(get_cacu_session, BiometriaHematica)
|
|||||||
episodio_clinico_repository = Repository(get_cacu_session, EpisodioClinico)
|
episodio_clinico_repository = Repository(get_cacu_session, EpisodioClinico)
|
||||||
|
|
||||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||||
persona_repository = Repository(get_cacu_session, Persona)
|
persona_repository = Repository(get_cacu_session, Persona)
|
||||||
periodo_observacion_repository = ReferenceRepository(get_cacu_session, PeriodoObservacion)
|
periodo_observacion_repository = RegistroRepository(get_cacu_session, PeriodoObservacion)
|
||||||
carga_repository = LoadRepository(get_cacu_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
carga_repository = CargaRepository(get_cacu_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||||
def_parametro_repository = ReferenceRepository(get_cacu_session, DefParametro)
|
def_parametro_repository = RegistroRepository(get_cacu_session, DefParametro)
|
||||||
dim_periodo_repository = ReferenceRepository(get_cacu_session, DimPeriodo)
|
dim_periodo_repository = RegistroRepository(get_cacu_session, DimPeriodo)
|
||||||
dim_fecha_repository = ReferenceRepository(get_cacu_session, DimFecha)
|
dim_fecha_repository = RegistroRepository(get_cacu_session, DimFecha)
|
||||||
dim_grupo_edad_repository = ReferenceRepository(get_cacu_session, DimGrupoEdad)
|
dim_grupo_edad_repository = RegistroRepository(get_cacu_session, DimGrupoEdad)
|
||||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||||
cat_measure_repository = ReferenceRepository(get_cacu_session, CatMeasure)
|
cat_measure_repository = RegistroRepository(get_cacu_session, CatMeasure)
|
||||||
cat_measure_resultado_repository = ReferenceRepository(get_cacu_session, CatMeasureResultado)
|
cat_measure_resultado_repository = RegistroRepository(get_cacu_session, CatMeasureResultado)
|
||||||
cat_measure_valor_repository = ReferenceRepository(get_cacu_session, CatMeasureValor)
|
cat_measure_valor_repository = RegistroRepository(get_cacu_session, CatMeasureValor)
|
||||||
cat_measure_grupo_repository = ReferenceRepository(get_cacu_session, CatMeasureGrupo)
|
cat_measure_grupo_repository = RegistroRepository(get_cacu_session, CatMeasureGrupo)
|
||||||
cat_estrato_repository = ReferenceRepository(get_cacu_session, CatEstrato)
|
cat_estrato_repository = RegistroRepository(get_cacu_session, CatEstrato)
|
||||||
cat_estrato_valor_repository = ReferenceRepository(get_cacu_session, CatEstratoValor)
|
cat_estrato_valor_repository = RegistroRepository(get_cacu_session, CatEstratoValor)
|
||||||
cat_measure_estrato_repository = ReferenceRepository(get_cacu_session, CatMeasureEstrato)
|
cat_measure_estrato_repository = RegistroRepository(get_cacu_session, CatMeasureEstrato)
|
||||||
publication_repository = PublicationRepository(
|
publicacion_repository = PublicacionRepository(
|
||||||
get_cacu_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
get_cacu_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||||
)
|
)
|
||||||
measure_report_unidad_repository = Repository(get_cacu_session, MeasureReportUnidad)
|
measure_report_unidad_repository = Repository(get_cacu_session, MeasureReportUnidad)
|
||||||
@@ -99,23 +91,17 @@ cat_valor_repository = Repository(get_cacu_session, CatValor)
|
|||||||
procedimiento_repository = Repository(get_cacu_session, Procedimiento)
|
procedimiento_repository = Repository(get_cacu_session, Procedimiento)
|
||||||
observacion_repository = Repository(get_cacu_session, Observacion)
|
observacion_repository = Repository(get_cacu_session, Observacion)
|
||||||
|
|
||||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||||
staging_repository = StagingRepository(get_cacu_session)
|
staging_repository = StagingRepository(get_cacu_session)
|
||||||
catalog_repository = CatalogRepository(get_cacu_session, CatEstudio, CatResultado, CatValor)
|
catalogo_repository = CatalogoRepository(get_cacu_session, CatEstudio, CatResultado, CatValor)
|
||||||
calculation_repository = CalculationRepository(get_cacu_session, MeasureReport, periodo=DimPeriodo)
|
calculo_repository = CalculoRepository(get_cacu_session, MeasureReport, periodo=DimPeriodo)
|
||||||
history_repository = MeasureHistoryRepository(get_cacu_session, MeasureReport, unit_model=MeasureReportUnidad,
|
observar_repository = ObservacionRepository(get_cacu_session, PeriodoObservacion)
|
||||||
stratum_model=MeasureReportUnidadEstrato,
|
vistas_repository = VistasRepository(get_cacu_session)
|
||||||
value_model=CatEstratoValor)
|
vinculos_repository = VinculosRepository(get_cacu_session)
|
||||||
observation_period_repository = ObservationRepository(get_cacu_session, PeriodoObservacion)
|
cohorte_repository = CohorteRepository(
|
||||||
views_repository = ViewsRepository(get_cacu_session)
|
|
||||||
links_repository = LinksRepository(get_cacu_session)
|
|
||||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
|
||||||
timeline_repository = DbtTimelineRepository(get_cacu_session, "cacu")
|
|
||||||
dbt_query_repository = DbtQueryRepository(get_cacu_session)
|
|
||||||
cohort_repository = CohortRepository(
|
|
||||||
get_cacu_session,
|
get_cacu_session,
|
||||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||||
)
|
)
|
||||||
|
|
||||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||||
materializer = Materializer(get_cacu_session)
|
materializador = Materializador(get_cacu_session)
|
||||||
|
|||||||
@@ -40,24 +40,16 @@ from core.cama.models import (
|
|||||||
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
|
|
||||||
from persistance.edges.bronze import StagingRepository
|
from persistance.aristas.bronce import StagingRepository
|
||||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
from persistance.aristas.comun import RegistroRepository
|
||||||
from persistance.edges.common import ReferenceRepository
|
from persistance.materializador import Materializador
|
||||||
from persistance.materializer import Materializer
|
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||||
from persistance.edges.gold import (
|
from persistance.aristas.plata import (
|
||||||
CalculationRepository,
|
CargaRepository,
|
||||||
CohortRepository,
|
CatalogoRepository,
|
||||||
MeasureHistoryRepository,
|
ObservacionRepository,
|
||||||
MeasureReportRepository,
|
VinculosRepository,
|
||||||
PublicationRepository,
|
VistasRepository,
|
||||||
)
|
|
||||||
from persistance.edges.silver import (
|
|
||||||
LoadRepository,
|
|
||||||
CatalogRepository,
|
|
||||||
ObservationRepository,
|
|
||||||
TimelineRepository,
|
|
||||||
LinksRepository,
|
|
||||||
ViewsRepository,
|
|
||||||
)
|
)
|
||||||
from persistance.db import get_cama_session
|
from persistance.db import get_cama_session
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
@@ -71,23 +63,23 @@ biometria_hematica_repository = Repository(get_cama_session, BiometriaHematica)
|
|||||||
episodio_clinico_repository = Repository(get_cama_session, EpisodioClinico)
|
episodio_clinico_repository = Repository(get_cama_session, EpisodioClinico)
|
||||||
|
|
||||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||||
persona_repository = Repository(get_cama_session, Persona)
|
persona_repository = Repository(get_cama_session, Persona)
|
||||||
periodo_observacion_repository = ReferenceRepository(get_cama_session, PeriodoObservacion)
|
periodo_observacion_repository = RegistroRepository(get_cama_session, PeriodoObservacion)
|
||||||
carga_repository = LoadRepository(get_cama_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
carga_repository = CargaRepository(get_cama_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||||
def_parametro_repository = ReferenceRepository(get_cama_session, DefParametro)
|
def_parametro_repository = RegistroRepository(get_cama_session, DefParametro)
|
||||||
dim_periodo_repository = ReferenceRepository(get_cama_session, DimPeriodo)
|
dim_periodo_repository = RegistroRepository(get_cama_session, DimPeriodo)
|
||||||
dim_fecha_repository = ReferenceRepository(get_cama_session, DimFecha)
|
dim_fecha_repository = RegistroRepository(get_cama_session, DimFecha)
|
||||||
dim_grupo_edad_repository = ReferenceRepository(get_cama_session, DimGrupoEdad)
|
dim_grupo_edad_repository = RegistroRepository(get_cama_session, DimGrupoEdad)
|
||||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||||
cat_measure_repository = ReferenceRepository(get_cama_session, CatMeasure)
|
cat_measure_repository = RegistroRepository(get_cama_session, CatMeasure)
|
||||||
cat_measure_resultado_repository = ReferenceRepository(get_cama_session, CatMeasureResultado)
|
cat_measure_resultado_repository = RegistroRepository(get_cama_session, CatMeasureResultado)
|
||||||
cat_measure_valor_repository = ReferenceRepository(get_cama_session, CatMeasureValor)
|
cat_measure_valor_repository = RegistroRepository(get_cama_session, CatMeasureValor)
|
||||||
cat_measure_grupo_repository = ReferenceRepository(get_cama_session, CatMeasureGrupo)
|
cat_measure_grupo_repository = RegistroRepository(get_cama_session, CatMeasureGrupo)
|
||||||
cat_estrato_repository = ReferenceRepository(get_cama_session, CatEstrato)
|
cat_estrato_repository = RegistroRepository(get_cama_session, CatEstrato)
|
||||||
cat_estrato_valor_repository = ReferenceRepository(get_cama_session, CatEstratoValor)
|
cat_estrato_valor_repository = RegistroRepository(get_cama_session, CatEstratoValor)
|
||||||
cat_measure_estrato_repository = ReferenceRepository(get_cama_session, CatMeasureEstrato)
|
cat_measure_estrato_repository = RegistroRepository(get_cama_session, CatMeasureEstrato)
|
||||||
publication_repository = PublicationRepository(
|
publicacion_repository = PublicacionRepository(
|
||||||
get_cama_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
get_cama_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||||
)
|
)
|
||||||
measure_report_unidad_repository = Repository(get_cama_session, MeasureReportUnidad)
|
measure_report_unidad_repository = Repository(get_cama_session, MeasureReportUnidad)
|
||||||
@@ -99,23 +91,17 @@ cat_valor_repository = Repository(get_cama_session, CatValor)
|
|||||||
procedimiento_repository = Repository(get_cama_session, Procedimiento)
|
procedimiento_repository = Repository(get_cama_session, Procedimiento)
|
||||||
observacion_repository = Repository(get_cama_session, Observacion)
|
observacion_repository = Repository(get_cama_session, Observacion)
|
||||||
|
|
||||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||||
staging_repository = StagingRepository(get_cama_session)
|
staging_repository = StagingRepository(get_cama_session)
|
||||||
catalog_repository = CatalogRepository(get_cama_session, CatEstudio, CatResultado, CatValor)
|
catalogo_repository = CatalogoRepository(get_cama_session, CatEstudio, CatResultado, CatValor)
|
||||||
calculation_repository = CalculationRepository(get_cama_session, MeasureReport, periodo=DimPeriodo)
|
calculo_repository = CalculoRepository(get_cama_session, MeasureReport, periodo=DimPeriodo)
|
||||||
history_repository = MeasureHistoryRepository(get_cama_session, MeasureReport, unit_model=MeasureReportUnidad,
|
observar_repository = ObservacionRepository(get_cama_session, PeriodoObservacion)
|
||||||
stratum_model=MeasureReportUnidadEstrato,
|
vistas_repository = VistasRepository(get_cama_session)
|
||||||
value_model=CatEstratoValor)
|
vinculos_repository = VinculosRepository(get_cama_session)
|
||||||
observation_period_repository = ObservationRepository(get_cama_session, PeriodoObservacion)
|
cohorte_repository = CohorteRepository(
|
||||||
views_repository = ViewsRepository(get_cama_session)
|
|
||||||
links_repository = LinksRepository(get_cama_session)
|
|
||||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
|
||||||
timeline_repository = DbtTimelineRepository(get_cama_session, "cama")
|
|
||||||
dbt_query_repository = DbtQueryRepository(get_cama_session)
|
|
||||||
cohort_repository = CohortRepository(
|
|
||||||
get_cama_session,
|
get_cama_session,
|
||||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||||
)
|
)
|
||||||
|
|
||||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||||
materializer = Materializer(get_cama_session)
|
materializador = Materializador(get_cama_session)
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
"""What dbt owns in a domain's database and Python reads: the timeline view and the queries dbt compiled.
|
|
||||||
|
|
||||||
dbt creates and changes these relations, so there's no ORM class and no Alembic migration for them. Both repositories
|
|
||||||
read on a `ReadSession`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
|
|
||||||
text, so a compiled query is trusted to be the `select` dbt wrote; a database account that can only read is what
|
|
||||||
guarantees it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from collections.abc import Callable, Iterable
|
|
||||||
from datetime import date, datetime
|
|
||||||
|
|
||||||
from core.indicadores.tipos import FechaHoraUTC
|
|
||||||
from sqlalchemy import Date, Select, bindparam, column, select, table, text
|
|
||||||
from sqlalchemy.exc import DBAPIError
|
|
||||||
|
|
||||||
from persistance.edges.silver.timeline import TIMELINE_COLUMNS, TimelineRepository
|
|
||||||
from persistance.materializer import ReadSession
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
|
|
||||||
class DbtRelationError(RuntimeError):
|
|
||||||
"""A relation dbt should have created can't be read."""
|
|
||||||
|
|
||||||
|
|
||||||
def timeline_view(domain: str) -> str:
|
|
||||||
return f"{domain}_linea_de_tiempo"
|
|
||||||
|
|
||||||
|
|
||||||
class DbtTimelineRepository(TimelineRepository):
|
|
||||||
"""The domain's timeline, read from dbt's view `<domain>_linea_de_tiempo`.
|
|
||||||
|
|
||||||
`fecha` comes back as a date and `conocida_en` as an aware UTC datetime on every engine. The filters run in the database; `patients` becomes one bound
|
|
||||||
parameter per patient, so a long list can exceed an engine's limit (SQL Server's is 2,100): read without it and join.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, session_factory: Callable, domain: str):
|
|
||||||
self.view = timeline_view(domain)
|
|
||||||
super().__init__(session_factory, self._query)
|
|
||||||
|
|
||||||
def _query(self, *, patients: Iterable[int] | None, until: date | None, known_until: datetime | None):
|
|
||||||
types = {"fecha": Date, "conocida_en": FechaHoraUTC}
|
|
||||||
view = table(self.view, *(column(name, types.get(name)) for name in TIMELINE_COLUMNS))
|
|
||||||
query = select(*(view.c[name] for name in TIMELINE_COLUMNS))
|
|
||||||
if patients is not None:
|
|
||||||
query = query.where(view.c.pac_id.in_(list(patients)))
|
|
||||||
if until is not None:
|
|
||||||
query = query.where(view.c.fecha <= until)
|
|
||||||
if known_until is not None:
|
|
||||||
query = query.where(view.c.conocida_en <= known_until)
|
|
||||||
return query.order_by(view.c.pac_id, view.c.fecha, view.c.fuente_tabla, view.c.fuente_id)
|
|
||||||
|
|
||||||
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
|
||||||
known_until: datetime | None = None) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return super().read(patients=patients, until=until, known_until=known_until)
|
|
||||||
except DBAPIError as error:
|
|
||||||
raise DbtRelationError(f"can't read {self.view} ({error.orig}): is it created? "
|
|
||||||
f"Run `dbt run --select {self.view}` in Transformation") from error
|
|
||||||
|
|
||||||
|
|
||||||
class DbtQueryRepository(Repository):
|
|
||||||
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row.
|
|
||||||
|
|
||||||
A query compiled with `--vars '{bind: true}'` has placeholders (`:periodo_inicio`) instead of values: `parameters`
|
|
||||||
gives them, and a list or tuple fills an `in :name`. The database does the work; only what the query selects
|
|
||||||
comes back.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, session_factory: Callable):
|
|
||||||
super().__init__(session_factory, None)
|
|
||||||
|
|
||||||
def read(self, sql: str, parameters: dict | None = None) -> list[dict]:
|
|
||||||
columns, rows = self.rows(sql, parameters)
|
|
||||||
return [dict(zip(columns, row)) for row in rows]
|
|
||||||
|
|
||||||
def rows(self, sql: str | Select, parameters: dict | None = None) -> tuple[list[str], list[tuple]]:
|
|
||||||
"""The column names and the rows; the names come back even when there are no rows.
|
|
||||||
|
|
||||||
`sql` can also be a `select` built over dbt's relations, which carries its own bound values.
|
|
||||||
"""
|
|
||||||
parameters = parameters or {}
|
|
||||||
query = sql if isinstance(sql, Select) else text(sql).bindparams(*(
|
|
||||||
bindparam(name, value, expanding=isinstance(value, (list, tuple))) for name, value in parameters.items()
|
|
||||||
))
|
|
||||||
with self._session_factory() as session:
|
|
||||||
result = ReadSession(session).execute(query)
|
|
||||||
return list(result.keys()), [tuple(row) for row in result]
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
"""Oro: el registro (parámetros, periodos, definiciones), los reportes de indicadores y las cohortes con sus riesgos."""
|
|
||||||
|
|
||||||
from persistance.edges.common import ReferenceRepository
|
|
||||||
from persistance.edges.gold.calculation import CalculationRepository, MeasureReportRepository, save_report_in
|
|
||||||
from persistance.edges.gold.history import MeasureHistoryRepository
|
|
||||||
from persistance.edges.gold.publication import PublicationRepository, sync_publication_in
|
|
||||||
from persistance.edges.gold.cohorts import (
|
|
||||||
ERROR,
|
|
||||||
FINAL,
|
|
||||||
PRELIMINAR,
|
|
||||||
PROVENANCE,
|
|
||||||
CohortBuild,
|
|
||||||
CohortRepository,
|
|
||||||
CohortMember,
|
|
||||||
PatientMembership,
|
|
||||||
PatientRisk,
|
|
||||||
RiskOutsideCohort,
|
|
||||||
RiskHorizon,
|
|
||||||
change_state_in,
|
|
||||||
save_build_in,
|
|
||||||
save_batch_in,
|
|
||||||
)
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"ERROR",
|
|
||||||
"FINAL",
|
|
||||||
"PRELIMINAR",
|
|
||||||
"PROVENANCE",
|
|
||||||
"CalculationRepository",
|
|
||||||
"CohortBuild",
|
|
||||||
"CohortRepository",
|
|
||||||
"CohortMember",
|
|
||||||
"MeasureHistoryRepository",
|
|
||||||
"MeasureReportRepository",
|
|
||||||
"PatientMembership",
|
|
||||||
"PatientRisk",
|
|
||||||
"PublicationRepository",
|
|
||||||
"ReferenceRepository",
|
|
||||||
"RiskOutsideCohort",
|
|
||||||
"RiskHorizon",
|
|
||||||
"change_state_in",
|
|
||||||
"save_build_in",
|
|
||||||
"save_batch_in",
|
|
||||||
"save_report_in",
|
|
||||||
"sync_publication_in",
|
|
||||||
]
|
|
||||||
@@ -1,337 +0,0 @@
|
|||||||
"""Oro: cohortes para modelos y sus lotes de riesgos, la escritura (ADR-MD-003, ADR-MD-005).
|
|
||||||
|
|
||||||
El kit arma el marco de una cohorte (quién entra, su fecha índice, sus variables,
|
|
||||||
la atrición) y sus huellas. Aquí se guarda: el armado con sus filas, el lote de
|
|
||||||
riesgos con las llaves de MLflow, y los cambios de estado de las evaluaciones.
|
|
||||||
|
|
||||||
Rearmar lo mismo no guarda otro armado (misma `huella` y mismo `marco_sha`), y
|
|
||||||
puntuar lo mismo otra vez no guarda otro lote (misma `huella` del lote). Una
|
|
||||||
evaluación solo crece: confirmarla (`preliminary` -> `final`) o anularla
|
|
||||||
(`entered-in-error`) agrega una versión con su motivo.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
from collections.abc import Callable, Iterable
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
from typing import TypeVar
|
|
||||||
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
|
||||||
from sqlalchemy import func
|
|
||||||
from sqlmodel import Session, SQLModel, select
|
|
||||||
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
|
||||||
PRELIMINAR, FINAL, ERROR = "preliminary", "final", "entered-in-error"
|
|
||||||
|
|
||||||
|
|
||||||
# Lo que el kit entrega para guardar un armado: la fila del armado y sus hijas, sin `armado_id`.
|
|
||||||
BuildModel = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
|
|
||||||
|
|
||||||
|
|
||||||
T = TypeVar("T")
|
|
||||||
|
|
||||||
|
|
||||||
class RiskOutsideCohort(ValueError):
|
|
||||||
"""Se quiso guardar el riesgo de alguien que no es miembro del armado puntuado."""
|
|
||||||
|
|
||||||
|
|
||||||
class CohortRepository(Repository):
|
|
||||||
"""Los armados de cohortes de un dominio y sus lotes de riesgos. Cada método, una sesión."""
|
|
||||||
|
|
||||||
def __init__(self, session_factory, cohortes: TablasCohorte):
|
|
||||||
super().__init__(session_factory, cohortes.CohorteArmado)
|
|
||||||
self.cohortes = cohortes
|
|
||||||
|
|
||||||
def assemble(self, armado: Callable[[Session], BuildModel]) -> tuple[int, bool]:
|
|
||||||
"""Calcula el armado con `armado(sesion)` y lo guarda en esa sesión. Devuelve (`armado_id`, nuevo)."""
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
return save_build_in(sesion, *armado(sesion))
|
|
||||||
|
|
||||||
def read(self, leer: Callable[[Session], T]) -> T:
|
|
||||||
"""Lo que `leer(sesion)` lee de las cohortes, en una sesión (el marco de un armado para estimar). No escribe."""
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
return leer(sesion)
|
|
||||||
|
|
||||||
def save_batch(
|
|
||||||
self, armado_id: int, procedencia: dict, desenlace: str, riesgos, *, ahora: datetime | None = None
|
|
||||||
) -> tuple[int, bool]:
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
return save_batch_in(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
|
|
||||||
ahora=ahora)
|
|
||||||
|
|
||||||
def change_state(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
return change_state_in(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
|
||||||
|
|
||||||
def latest_build(self, url: str) -> int | None:
|
|
||||||
"""The most recent build of the cohort `url`, or `None` if it has none."""
|
|
||||||
build = self.cohortes.CohorteArmado
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
return sesion.exec(
|
|
||||||
select(build.armado_id).where(build.url == url).order_by(build.armado_id.desc()).limit(1)
|
|
||||||
).first()
|
|
||||||
|
|
||||||
def members(self, build_id: int) -> list["CohortMember"]:
|
|
||||||
"""The members of a build, ordered by `pac_id`; empty if the build doesn't exist."""
|
|
||||||
member = self.cohortes.CohorteMiembro
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
rows = sesion.exec(select(member).where(member.armado_id == build_id).order_by(member.pac_id)).all()
|
|
||||||
return [CohortMember(row.pac_id, row.fecha_indice, row.indice_fuente_tabla, row.indice_fuente_id)
|
|
||||||
for row in rows]
|
|
||||||
|
|
||||||
def build(self, build_id: int) -> "CohortBuild | None":
|
|
||||||
"""A build's lineage fields, or `None` if it doesn't exist."""
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
row = sesion.get(self.cohortes.CohorteArmado, build_id)
|
|
||||||
return None if row is None else _cohort_build(row)
|
|
||||||
|
|
||||||
def builds(self, url: str | None = None) -> list["CohortBuild"]:
|
|
||||||
"""Every build, newest first, with its lineage fields; only those of the cohort `url` if given."""
|
|
||||||
armado = self.cohortes.CohorteArmado
|
|
||||||
query = select(armado).order_by(armado.armado_id.desc())
|
|
||||||
if url is not None:
|
|
||||||
query = query.where(armado.url == url)
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
return [_cohort_build(row) for row in sesion.exec(query).all()]
|
|
||||||
|
|
||||||
|
|
||||||
def membership(self, pac_id: int, url: str) -> "PatientMembership | None":
|
|
||||||
"""The patient in the cohort's latest build: its version, index date and stored variables (`c`, `l`, `r`,
|
|
||||||
`pap_0`, `hpv_0`...); `None` if the cohort has no build or the patient isn't a member of the latest one."""
|
|
||||||
if (build_id := self.latest_build(url)) is None:
|
|
||||||
return None
|
|
||||||
member, variable = self.cohortes.CohorteMiembro, self.cohortes.CohorteVariable
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
row = sesion.get(member, (build_id, pac_id))
|
|
||||||
if row is None:
|
|
||||||
return None
|
|
||||||
build = sesion.get(self.cohortes.CohorteArmado, build_id)
|
|
||||||
values = sesion.exec(select(variable).where(variable.armado_id == build_id, variable.pac_id == pac_id)).all()
|
|
||||||
return PatientMembership(build_id, url, build.version, row.fecha_indice,
|
|
||||||
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
|
|
||||||
for v in values})
|
|
||||||
|
|
||||||
def current_risk(self, pac_id: int) -> "PatientRisk | None":
|
|
||||||
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
|
|
||||||
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
|
|
||||||
horizons whose latest version is `entered-in-error` are left out. `None` if no batch of the patient is
|
|
||||||
confirmed."""
|
|
||||||
e = self.cohortes.EvaluacionRiesgo
|
|
||||||
with self._session_factory() as sesion:
|
|
||||||
batches = sesion.exec(select(e.lote_id).where(e.pac_id == pac_id).distinct().order_by(e.lote_id.desc())).all()
|
|
||||||
for lote_id in batches:
|
|
||||||
latest = _latest_versions(sesion, e, lote_id)
|
|
||||||
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
|
||||||
.where(e.lote_id == lote_id, e.estado == FINAL).limit(1)).first():
|
|
||||||
continue
|
|
||||||
rows = sesion.exec(select(e).join(latest, _same_version(e, latest))
|
|
||||||
.where(e.lote_id == lote_id, e.pac_id == pac_id, e.estado != ERROR)
|
|
||||||
.order_by(e.horizonte_anios)).all()
|
|
||||||
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
|
|
||||||
return PatientRisk(lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
|
|
||||||
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado)
|
|
||||||
for r in rows])
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class PatientMembership:
|
|
||||||
"""A patient in a cohort's latest build: which build, from which index date, and its stored variables."""
|
|
||||||
|
|
||||||
armado_id: int
|
|
||||||
url: str
|
|
||||||
version: str
|
|
||||||
fecha_indice: date
|
|
||||||
variables: dict
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RiskHorizon:
|
|
||||||
"""A patient's risk at one horizon, at its latest version."""
|
|
||||||
|
|
||||||
horizonte_anios: float
|
|
||||||
probabilidad: float
|
|
||||||
ic_bajo: float | None
|
|
||||||
ic_alto: float | None
|
|
||||||
estado: str
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class PatientRisk:
|
|
||||||
"""A patient's risks in the current batch, with the model that produced them."""
|
|
||||||
|
|
||||||
lote_id: int
|
|
||||||
modelo_nombre: str
|
|
||||||
modelo_version: str
|
|
||||||
evaluado_en: datetime
|
|
||||||
estado_lote: str
|
|
||||||
horizontes: list[RiskHorizon]
|
|
||||||
|
|
||||||
|
|
||||||
def _latest_versions(sesion: Session, e, lote_id: int):
|
|
||||||
"""The latest version of each (patient, horizon) of a batch, as a subquery."""
|
|
||||||
return (select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
|
|
||||||
.where(e.lote_id == lote_id).group_by(e.pac_id, e.horizonte_anios).subquery())
|
|
||||||
|
|
||||||
|
|
||||||
def _same_version(e, latest):
|
|
||||||
return (e.pac_id == latest.c.pac_id) & (e.horizonte_anios == latest.c.horizonte_anios) & (e.version == latest.c.version)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class CohortMember:
|
|
||||||
"""A member of a cohort build: who, from which index date, and the row of its index event."""
|
|
||||||
|
|
||||||
pac_id: int
|
|
||||||
fecha_indice: date
|
|
||||||
indice_fuente_tabla: str
|
|
||||||
indice_fuente_id: str
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class CohortBuild:
|
|
||||||
"""What identifies a cohort build in a model's lineage.
|
|
||||||
|
|
||||||
`datos_as_of` is the clinical cut-off; `conocida_hasta` is what had been loaded when the build was made
|
|
||||||
(`None`: everything loaded at the time). Reading the timeline again with both reproduces the build's input
|
|
||||||
once silver keeps its history.
|
|
||||||
"""
|
|
||||||
|
|
||||||
armado_id: int
|
|
||||||
url: str
|
|
||||||
version: str
|
|
||||||
huella: str
|
|
||||||
marco_sha: str
|
|
||||||
datos_as_of: date
|
|
||||||
conocida_hasta: datetime | None
|
|
||||||
n_miembros: int
|
|
||||||
armado_en: datetime
|
|
||||||
|
|
||||||
|
|
||||||
def _cohort_build(row: SQLModel) -> CohortBuild:
|
|
||||||
"""A `cohorte_armado` row as `CohortBuild`; `conocida_hasta` comes from its parameters."""
|
|
||||||
known_until = json.loads(row.parametros or "{}").get("conocida_hasta")
|
|
||||||
return CohortBuild(row.armado_id, row.url, row.version, row.huella, row.marco_sha, row.datos_as_of,
|
|
||||||
None if known_until is None else datetime.fromisoformat(known_until),
|
|
||||||
row.n_miembros, row.armado_en)
|
|
||||||
|
|
||||||
|
|
||||||
def save_build_in(
|
|
||||||
sesion: Session, armado: SQLModel, exclusiones: Iterable[SQLModel], miembros: Iterable[SQLModel],
|
|
||||||
variables: Iterable[SQLModel],
|
|
||||||
) -> tuple[int, bool]:
|
|
||||||
"""Guarda un armado con su atrición, sus miembros y sus variables. Devuelve (`armado_id`, nuevo). Todo o nada.
|
|
||||||
|
|
||||||
Las hijas llegan sin `armado_id`: se lo pone este cuerpo. Si ya hay un armado
|
|
||||||
con la misma `huella` y el mismo `marco_sha`, no guarda y devuelve ese.
|
|
||||||
"""
|
|
||||||
modelo = type(armado)
|
|
||||||
previo = sesion.exec(
|
|
||||||
select(modelo).where(modelo.huella == armado.huella, modelo.marco_sha == armado.marco_sha)
|
|
||||||
).first()
|
|
||||||
if previo is not None:
|
|
||||||
return previo.armado_id, False
|
|
||||||
try:
|
|
||||||
sesion.add(armado)
|
|
||||||
sesion.flush()
|
|
||||||
armado_id = armado.armado_id
|
|
||||||
for grupo in (exclusiones, miembros, variables):
|
|
||||||
filas = list(grupo)
|
|
||||||
for fila in filas:
|
|
||||||
fila.armado_id = armado_id
|
|
||||||
sesion.add_all(filas)
|
|
||||||
sesion.flush() # los miembros antes que sus variables (llave foránea)
|
|
||||||
sesion.commit()
|
|
||||||
except Exception:
|
|
||||||
sesion.rollback()
|
|
||||||
raise
|
|
||||||
return armado_id, True
|
|
||||||
|
|
||||||
|
|
||||||
def save_batch_in(
|
|
||||||
sesion: Session,
|
|
||||||
armado_id: int,
|
|
||||||
procedencia: dict,
|
|
||||||
desenlace: str,
|
|
||||||
riesgos: list[tuple[int, float, float, float | None, float | None]],
|
|
||||||
*,
|
|
||||||
cohortes: TablasCohorte,
|
|
||||||
ahora: datetime | None = None,
|
|
||||||
) -> tuple[int, bool]:
|
|
||||||
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
|
|
||||||
|
|
||||||
No copia nada de MLflow: guarda sus llaves (`PROVENANCE`). Puntuar lo mismo
|
|
||||||
otra vez (mismo armado, modelo y riesgos) no duplica: la huella del lote ya está.
|
|
||||||
"""
|
|
||||||
faltan = [c for c in PROVENANCE if not procedencia.get(c)]
|
|
||||||
if faltan:
|
|
||||||
raise ValueError(f"La procedencia no trae {faltan}.")
|
|
||||||
miembro = cohortes.CohorteMiembro
|
|
||||||
miembros = set(sesion.exec(select(miembro.pac_id).where(miembro.armado_id == armado_id)))
|
|
||||||
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
|
|
||||||
if ajenos:
|
|
||||||
raise RiskOutsideCohort(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
|
||||||
huella = _json_sha({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROVENANCE},
|
|
||||||
"riesgos": sorted(riesgos)})
|
|
||||||
lote = cohortes.EvaluacionRiesgoLote
|
|
||||||
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
|
|
||||||
if previo is not None:
|
|
||||||
return previo.lote_id, False
|
|
||||||
momento = ahora or datetime.now(timezone.utc)
|
|
||||||
try:
|
|
||||||
fila = lote(armado_id=armado_id, desenlace=desenlace, evaluado_en=momento, n_evaluaciones=len(riesgos),
|
|
||||||
huella=huella, **{c: str(procedencia[c]) for c in PROVENANCE})
|
|
||||||
sesion.add(fila)
|
|
||||||
sesion.flush()
|
|
||||||
sesion.add_all(
|
|
||||||
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, horizonte_anios=float(h), probabilidad=float(p),
|
|
||||||
ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR, registrado_en=momento)
|
|
||||||
for pac, h, p, bajo, alto in riesgos
|
|
||||||
)
|
|
||||||
sesion.commit()
|
|
||||||
except Exception:
|
|
||||||
sesion.rollback()
|
|
||||||
raise
|
|
||||||
return fila.lote_id, True
|
|
||||||
|
|
||||||
|
|
||||||
def change_state_in(
|
|
||||||
sesion: Session, lote_id: int, estado: str, motivo: str, *, cohortes: TablasCohorte,
|
|
||||||
ahora: datetime | None = None,
|
|
||||||
) -> int:
|
|
||||||
"""Agrega una versión con `estado` a cada evaluación vigente del lote. Devuelve cuántas cambió."""
|
|
||||||
if estado not in (FINAL, ERROR):
|
|
||||||
raise ValueError(f"Estado desconocido: {estado!r} (se confirma a {FINAL!r} o se anula con {ERROR!r}).")
|
|
||||||
e = cohortes.EvaluacionRiesgo
|
|
||||||
ultima = (
|
|
||||||
select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
|
|
||||||
.where(e.lote_id == lote_id)
|
|
||||||
.group_by(e.pac_id, e.horizonte_anios)
|
|
||||||
.subquery()
|
|
||||||
)
|
|
||||||
vigentes = sesion.exec(
|
|
||||||
select(e).join(ultima, (e.pac_id == ultima.c.pac_id) & (e.horizonte_anios == ultima.c.horizonte_anios)
|
|
||||||
& (e.version == ultima.c.version)).where(e.lote_id == lote_id, e.estado != estado)
|
|
||||||
).all()
|
|
||||||
momento = ahora or datetime.now(timezone.utc)
|
|
||||||
try:
|
|
||||||
sesion.add_all(
|
|
||||||
e(lote_id=lote_id, pac_id=v.pac_id, horizonte_anios=v.horizonte_anios, probabilidad=v.probabilidad,
|
|
||||||
ic_bajo=v.ic_bajo, ic_alto=v.ic_alto, version=v.version + 1, estado=estado, motivo=motivo,
|
|
||||||
registrado_en=momento)
|
|
||||||
for v in vigentes
|
|
||||||
)
|
|
||||||
sesion.commit()
|
|
||||||
except Exception:
|
|
||||||
sesion.rollback()
|
|
||||||
raise
|
|
||||||
return len(vigentes)
|
|
||||||
|
|
||||||
|
|
||||||
def _json_sha(objeto) -> str:
|
|
||||||
"""sha256 del JSON canónico (el mismo de `models.cohorts.definition.json_sha`)."""
|
|
||||||
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
|
||||||
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
"""Oro: measures asked for on request, each answer kept once under the full key of the question.
|
|
||||||
|
|
||||||
A question is a measure and its definition's version, a period, the event cut-off (`fecha`), the knowledge cut-off
|
|
||||||
(`conocida_en`) and the values of its rules. Its answer is a `measure_report` whose `parametros` is that key and
|
|
||||||
whose `parametros_sha` is the key's hash, with its units in `measure_report_unidad` and their strata in
|
|
||||||
`measure_report_unidad_estrato`, so the publication views read it as any other report. The database writes those
|
|
||||||
rows (`INSERT … SELECT`): they never pass through Python. A stratum value not yet in `cat_estrato_valor` is added
|
|
||||||
there first, labelled with itself, so the foreign key from `measure_report_unidad_estrato` holds.
|
|
||||||
|
|
||||||
Asking a stored key again reads it and writes nothing; what was answered can't drift when later loads change silver.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from collections.abc import Callable, Iterable
|
|
||||||
|
|
||||||
from sqlalchemy import Select, and_, distinct, exists, func, insert, literal, select
|
|
||||||
from sqlmodel import SQLModel
|
|
||||||
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
|
|
||||||
class MeasureHistoryRepository(Repository):
|
|
||||||
"""The reports of a domain's measures asked for on request. `unit_model` and `stratum_model` are the domain's
|
|
||||||
`measure_report_unidad` and `measure_report_unidad_estrato`; `value_model`, its `cat_estrato_valor`."""
|
|
||||||
|
|
||||||
def __init__(self, session_factory, model, *, unit_model, stratum_model, value_model):
|
|
||||||
super().__init__(session_factory, model)
|
|
||||||
self.unit_model, self.stratum_model, self.value_model = unit_model, stratum_model, value_model
|
|
||||||
|
|
||||||
def counts(self, report_id: int) -> dict[tuple[str, str, str, str | None], int]:
|
|
||||||
"""A stored answer's units counted from its rows: `{(stratum, value, resultado_id, valor_id): units}`, the
|
|
||||||
total as `("total", "total", …)`. No view is needed to read what was answered."""
|
|
||||||
u, e = self.unit_model, self.stratum_model
|
|
||||||
units = func.count(distinct(u.unidad_id))
|
|
||||||
with self._session_factory() as session:
|
|
||||||
total = session.execute(select(u.resultado_id, u.valor_id, units).where(u.report_id == report_id)
|
|
||||||
.group_by(u.resultado_id, u.valor_id)).all()
|
|
||||||
by_stratum = session.execute(
|
|
||||||
select(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id, units)
|
|
||||||
.join(e, (e.report_id == u.report_id) & (e.unidad_id == u.unidad_id))
|
|
||||||
.where(u.report_id == report_id)
|
|
||||||
.group_by(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id)).all()
|
|
||||||
return {**{("total", "total", r, v): n for r, v, n in total},
|
|
||||||
**{(s, sv, r, v): n for s, sv, r, v, n in by_stratum}}
|
|
||||||
|
|
||||||
def find(self, measure_url: str, key_sha: str) -> int | None:
|
|
||||||
"""The report already answering this key, if it was asked before."""
|
|
||||||
report = self.model
|
|
||||||
with self._session_factory() as session:
|
|
||||||
return session.execute(
|
|
||||||
select(report.report_id)
|
|
||||||
.where(report.measure_url == measure_url, report.parametros_sha == key_sha)
|
|
||||||
.order_by(report.report_id)
|
|
||||||
.limit(1)
|
|
||||||
).scalar()
|
|
||||||
|
|
||||||
def record(self, report: SQLModel, rows: Callable[[int], Iterable[tuple[type[SQLModel], Select]]]) -> int:
|
|
||||||
"""Saves the report and, in the same transaction, what each `(model, select)` of `rows(report_id)` gives.
|
|
||||||
|
|
||||||
Each select names its columns as the model's table does. All or nothing. Returns the `report_id`.
|
|
||||||
"""
|
|
||||||
with self._session_factory() as session:
|
|
||||||
try:
|
|
||||||
session.add(report)
|
|
||||||
session.flush()
|
|
||||||
report_id = report.report_id
|
|
||||||
for model, query in rows(report_id):
|
|
||||||
table = model.__table__
|
|
||||||
if model is self.stratum_model:
|
|
||||||
session.execute(self._new_values(query))
|
|
||||||
session.execute(insert(table).from_select([table.c[c.name] for c in query.selected_columns], query))
|
|
||||||
session.commit()
|
|
||||||
except Exception:
|
|
||||||
session.rollback()
|
|
||||||
raise
|
|
||||||
return report_id
|
|
||||||
|
|
||||||
def _new_values(self, strata: Select):
|
|
||||||
"""`INSERT … SELECT` of the stratum values `strata` gives that `cat_estrato_valor` doesn't have yet."""
|
|
||||||
catalog, given = self.value_model.__table__, strata.subquery()
|
|
||||||
new = (select(given.c.estrato_id, given.c.estrato_valor, given.c.estrato_valor, literal(0))
|
|
||||||
.where(~exists().where(and_(catalog.c.estrato_id == given.c.estrato_id,
|
|
||||||
catalog.c.valor_id == given.c.estrato_valor)))
|
|
||||||
.distinct())
|
|
||||||
return insert(catalog).from_select(["estrato_id", "valor_id", "etiqueta", "orden"], new)
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
|
||||||
|
|
||||||
from persistance.edges.silver.loads import (
|
|
||||||
LoadRepository,
|
|
||||||
open_load,
|
|
||||||
close_load,
|
|
||||||
save_load_in,
|
|
||||||
)
|
|
||||||
from persistance.edges.silver.catalogs import CatalogRepository
|
|
||||||
from persistance.edges.silver.observation import ObservationRepository
|
|
||||||
from persistance.edges.silver.procedures import save_silver_in
|
|
||||||
from persistance.edges.silver.timeline import (
|
|
||||||
TIMELINE_COLUMNS,
|
|
||||||
TimelineContractError,
|
|
||||||
TimelineQuery,
|
|
||||||
TimelineQueryMissing,
|
|
||||||
TimelineRepository,
|
|
||||||
)
|
|
||||||
from persistance.edges.silver.links import LinksRepository
|
|
||||||
from persistance.edges.silver.views import ViewsRepository
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"LoadRepository",
|
|
||||||
"CatalogRepository",
|
|
||||||
"ObservationRepository",
|
|
||||||
"TIMELINE_COLUMNS",
|
|
||||||
"TimelineContractError",
|
|
||||||
"TimelineQuery",
|
|
||||||
"TimelineQueryMissing",
|
|
||||||
"TimelineRepository",
|
|
||||||
"LinksRepository",
|
|
||||||
"ViewsRepository",
|
|
||||||
"open_load",
|
|
||||||
"close_load",
|
|
||||||
"save_load_in",
|
|
||||||
"save_silver_in",
|
|
||||||
]
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
"""Silver: each patient's timeline of procedures and observations, under a fixed column contract.
|
|
||||||
|
|
||||||
The query is injected. Each domain module binds dbt's view (`persistance.edges.dbt`), which the orchestration,
|
|
||||||
the cohort builds, the models' pipelines and the measures' strata all read; a test can bind another with
|
|
||||||
`with_query`. Readers keep the same columns and filters.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from collections.abc import Callable, Iterable
|
|
||||||
from datetime import date, datetime
|
|
||||||
from typing import Protocol
|
|
||||||
|
|
||||||
from sqlalchemy import Select
|
|
||||||
|
|
||||||
from persistance.materializer import ReadSession
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
TIMELINE_COLUMNS = (
|
|
||||||
"pac_id", "fecha", "conocida_en", "clase", "tipo", "codigo", "valor_codigo", "valor_numerico",
|
|
||||||
"fuente_tabla", "fuente_id",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TimelineQuery(Protocol):
|
|
||||||
def __call__(self, *, patients: Iterable[int] | None, until: date | None,
|
|
||||||
known_until: datetime | None) -> Select: ...
|
|
||||||
|
|
||||||
|
|
||||||
class TimelineContractError(ValueError):
|
|
||||||
"""The injected query returned columns other than `TIMELINE_COLUMNS`."""
|
|
||||||
|
|
||||||
|
|
||||||
class TimelineQueryMissing(RuntimeError):
|
|
||||||
"""`read` was called on a repository that has no query yet (see `with_query`)."""
|
|
||||||
|
|
||||||
|
|
||||||
class TimelineRepository(Repository):
|
|
||||||
"""Reads the timeline of some patients, or of everyone, cut at a date and at what was loaded by then.
|
|
||||||
|
|
||||||
Created with a query, or without one and bound later with `with_query`, so neither side names what it
|
|
||||||
can't import.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, session_factory: Callable, query: TimelineQuery | None = None):
|
|
||||||
super().__init__(session_factory, None)
|
|
||||||
self._query = query
|
|
||||||
|
|
||||||
def with_query(self, query: TimelineQuery) -> "TimelineRepository":
|
|
||||||
"""The same repository, reading through `query`."""
|
|
||||||
return TimelineRepository(self._session_factory, query)
|
|
||||||
|
|
||||||
def query(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
|
||||||
known_until: datetime | None = None) -> Select:
|
|
||||||
"""The `select` `read` runs, for a caller that runs it on its own session (a cohort build, in its write)."""
|
|
||||||
if self._query is None:
|
|
||||||
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
|
|
||||||
return self._query(patients=None if patients is None else list(patients), until=until,
|
|
||||||
known_until=known_until)
|
|
||||||
|
|
||||||
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
|
||||||
known_until: datetime | None = None) -> list[dict]:
|
|
||||||
"""One dict per event, keyed by `TIMELINE_COLUMNS`, in the query's order.
|
|
||||||
|
|
||||||
`until` keeps events up to that clinical date; `known_until` keeps rows already loaded at that
|
|
||||||
moment. The query runs on a read-only session.
|
|
||||||
"""
|
|
||||||
query = self.query(patients=patients, until=until, known_until=known_until)
|
|
||||||
with self._session_factory() as session:
|
|
||||||
result = ReadSession(session).execute(query)
|
|
||||||
columns = tuple(result.keys())
|
|
||||||
if columns != TIMELINE_COLUMNS:
|
|
||||||
raise TimelineContractError(f"expected columns {TIMELINE_COLUMNS}, got {columns}")
|
|
||||||
return [dict(zip(columns, row)) for row in result]
|
|
||||||
+14
-14
@@ -1,11 +1,11 @@
|
|||||||
"""El materializador de MD-20 (T0; ADR-MD-009): la E/S de una transformación.
|
"""El materializador de MD-20 (T0; ADR-MD-009): la E/S de una transformación.
|
||||||
|
|
||||||
Una transformación es una función pura del kit que lee por una `ReadSession` y devuelve
|
Una transformación es una función pura del kit que lee por una `SesionDeLectura` y devuelve
|
||||||
lo que hay que escribir. El materializador abre una sola sesión, se la da a la función de
|
lo que hay que escribir. El materializador abre una sola sesión, se la da a la función de
|
||||||
solo lectura, escribe lo que devolvió con un **cuerpo** y hace un solo commit, el del cuerpo.
|
solo lectura, escribe lo que devolvió con un **cuerpo** y hace un solo commit, el del cuerpo.
|
||||||
Sin cuerpo, solo lee: es una prueba o una lectura.
|
Sin cuerpo, solo lee: es una prueba o una lectura.
|
||||||
|
|
||||||
Es lo mismo que hace cada subclase de repositorio de `persistance/edges/`, una sola vez:
|
Es lo mismo que hace cada subclase de repositorio de `persistance/aristas/`, una sola vez:
|
||||||
el cuerpo es lo único que cambia de una a otra. Convive con ellas hasta MD-20 T2.
|
el cuerpo es lo único que cambia de una a otra. Convive con ellas hasta MD-20 T2.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -15,18 +15,18 @@ from typing import Any, TypeVar
|
|||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
Body = Callable[[Session, Any], Any]
|
Cuerpo = Callable[[Session, Any], Any]
|
||||||
|
|
||||||
|
|
||||||
class ReadOnly(RuntimeError):
|
class SoloLectura(RuntimeError):
|
||||||
"""Una transformación quiso escribir por la sesión que solo le da para leer."""
|
"""Una transformación quiso escribir por la sesión que solo le da para leer."""
|
||||||
|
|
||||||
|
|
||||||
class ReadSession:
|
class SesionDeLectura:
|
||||||
"""La sesión que recibe una transformación: lee como una `Session` y no puede escribir.
|
"""La sesión que recibe una transformación: lee como una `Session` y no puede escribir.
|
||||||
|
|
||||||
`add`, `add_all`, `delete`, `merge`, `flush`, `commit` y un `exec`/`execute` de INSERT,
|
`add`, `add_all`, `delete`, `merge`, `flush`, `commit` y un `exec`/`execute` de INSERT,
|
||||||
UPDATE o DELETE lanzan `ReadOnly`. Lo demás (`exec`, `execute`, `get`, `scalar`,
|
UPDATE o DELETE lanzan `SoloLectura`. Lo demás (`exec`, `execute`, `get`, `scalar`,
|
||||||
`scalars`) va a la sesión de verdad.
|
`scalars`) va a la sesión de verdad.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -37,35 +37,35 @@ class ReadSession:
|
|||||||
self._sesion = sesion
|
self._sesion = sesion
|
||||||
|
|
||||||
def exec(self, consulta, *args, **kwargs):
|
def exec(self, consulta, *args, **kwargs):
|
||||||
return self._sesion.exec(self._read_only(consulta), *args, **kwargs)
|
return self._sesion.exec(self._solo_lectura(consulta), *args, **kwargs)
|
||||||
|
|
||||||
def execute(self, consulta, *args, **kwargs):
|
def execute(self, consulta, *args, **kwargs):
|
||||||
return self._sesion.execute(self._read_only(consulta), *args, **kwargs)
|
return self._sesion.execute(self._solo_lectura(consulta), *args, **kwargs)
|
||||||
|
|
||||||
def __getattr__(self, nombre: str):
|
def __getattr__(self, nombre: str):
|
||||||
if nombre in self._ESCRIBEN:
|
if nombre in self._ESCRIBEN:
|
||||||
raise ReadOnly(f"Una transformación no escribe: `{nombre}` en una SesionDeLectura.")
|
raise SoloLectura(f"Una transformación no escribe: `{nombre}` en una SesionDeLectura.")
|
||||||
return getattr(self._sesion, nombre)
|
return getattr(self._sesion, nombre)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _read_only(consulta):
|
def _solo_lectura(consulta):
|
||||||
if getattr(consulta, "is_dml", False) and not getattr(consulta, "is_select", False):
|
if getattr(consulta, "is_dml", False) and not getattr(consulta, "is_select", False):
|
||||||
raise ReadOnly(f"Una transformación no escribe: {type(consulta).__name__} en una SesionDeLectura.")
|
raise SoloLectura(f"Una transformación no escribe: {type(consulta).__name__} en una SesionDeLectura.")
|
||||||
return consulta
|
return consulta
|
||||||
|
|
||||||
|
|
||||||
class Materializer:
|
class Materializador:
|
||||||
"""La E/S de las transformaciones de un dominio: una sesión, la función, el cuerpo y un commit."""
|
"""La E/S de las transformaciones de un dominio: una sesión, la función, el cuerpo y un commit."""
|
||||||
|
|
||||||
def __init__(self, session_factory: Callable[[], Session]):
|
def __init__(self, session_factory: Callable[[], Session]):
|
||||||
self._session_factory = session_factory
|
self._session_factory = session_factory
|
||||||
|
|
||||||
def materialize(self, funcion: Callable[[ReadSession], T], cuerpo: Body | None = None):
|
def materializar(self, funcion: Callable[[SesionDeLectura], T], cuerpo: Cuerpo | None = None):
|
||||||
"""`funcion(sesion_de_lectura)` y, con `cuerpo`, `cuerpo(sesion, lo_que_devolvio)` (escribe y hace commit).
|
"""`funcion(sesion_de_lectura)` y, con `cuerpo`, `cuerpo(sesion, lo_que_devolvio)` (escribe y hace commit).
|
||||||
|
|
||||||
Devuelve lo que devuelve el cuerpo (su resumen), o lo que devolvió la función si no hay cuerpo.
|
Devuelve lo que devuelve el cuerpo (su resumen), o lo que devolvió la función si no hay cuerpo.
|
||||||
"""
|
"""
|
||||||
with self._session_factory() as sesion:
|
with self._session_factory() as sesion:
|
||||||
datos = funcion(ReadSession(sesion))
|
datos = funcion(SesionDeLectura(sesion))
|
||||||
return datos if cuerpo is None else cuerpo(sesion, datos)
|
return datos if cuerpo is None else cuerpo(sesion, datos)
|
||||||
|
|
||||||
@@ -43,24 +43,16 @@ from core.tea.models import (
|
|||||||
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
from core.indicadores.cohortes import TablasCohorte
|
||||||
|
|
||||||
from persistance.edges.bronze import StagingRepository
|
from persistance.aristas.bronce import StagingRepository
|
||||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
from persistance.aristas.comun import RegistroRepository
|
||||||
from persistance.edges.common import ReferenceRepository
|
from persistance.materializador import Materializador
|
||||||
from persistance.materializer import Materializer
|
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||||
from persistance.edges.gold import (
|
from persistance.aristas.plata import (
|
||||||
CalculationRepository,
|
CargaRepository,
|
||||||
CohortRepository,
|
CatalogoRepository,
|
||||||
MeasureHistoryRepository,
|
ObservacionRepository,
|
||||||
MeasureReportRepository,
|
VinculosRepository,
|
||||||
PublicationRepository,
|
VistasRepository,
|
||||||
)
|
|
||||||
from persistance.edges.silver import (
|
|
||||||
LoadRepository,
|
|
||||||
CatalogRepository,
|
|
||||||
ObservationRepository,
|
|
||||||
TimelineRepository,
|
|
||||||
LinksRepository,
|
|
||||||
ViewsRepository,
|
|
||||||
)
|
)
|
||||||
from persistance.db import get_tea_session
|
from persistance.db import get_tea_session
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
@@ -77,23 +69,23 @@ parto_neonatal_repository = Repository(get_tea_session, PartoNeonatal)
|
|||||||
instrumento_aplicado_repository = Repository(get_tea_session, InstrumentoAplicado)
|
instrumento_aplicado_repository = Repository(get_tea_session, InstrumentoAplicado)
|
||||||
|
|
||||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||||
persona_repository = Repository(get_tea_session, Persona)
|
persona_repository = Repository(get_tea_session, Persona)
|
||||||
periodo_observacion_repository = ReferenceRepository(get_tea_session, PeriodoObservacion)
|
periodo_observacion_repository = RegistroRepository(get_tea_session, PeriodoObservacion)
|
||||||
carga_repository = LoadRepository(get_tea_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
carga_repository = CargaRepository(get_tea_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||||
def_parametro_repository = ReferenceRepository(get_tea_session, DefParametro)
|
def_parametro_repository = RegistroRepository(get_tea_session, DefParametro)
|
||||||
dim_periodo_repository = ReferenceRepository(get_tea_session, DimPeriodo)
|
dim_periodo_repository = RegistroRepository(get_tea_session, DimPeriodo)
|
||||||
dim_fecha_repository = ReferenceRepository(get_tea_session, DimFecha)
|
dim_fecha_repository = RegistroRepository(get_tea_session, DimFecha)
|
||||||
dim_grupo_edad_repository = ReferenceRepository(get_tea_session, DimGrupoEdad)
|
dim_grupo_edad_repository = RegistroRepository(get_tea_session, DimGrupoEdad)
|
||||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||||
cat_measure_repository = ReferenceRepository(get_tea_session, CatMeasure)
|
cat_measure_repository = RegistroRepository(get_tea_session, CatMeasure)
|
||||||
cat_measure_resultado_repository = ReferenceRepository(get_tea_session, CatMeasureResultado)
|
cat_measure_resultado_repository = RegistroRepository(get_tea_session, CatMeasureResultado)
|
||||||
cat_measure_valor_repository = ReferenceRepository(get_tea_session, CatMeasureValor)
|
cat_measure_valor_repository = RegistroRepository(get_tea_session, CatMeasureValor)
|
||||||
cat_measure_grupo_repository = ReferenceRepository(get_tea_session, CatMeasureGrupo)
|
cat_measure_grupo_repository = RegistroRepository(get_tea_session, CatMeasureGrupo)
|
||||||
cat_estrato_repository = ReferenceRepository(get_tea_session, CatEstrato)
|
cat_estrato_repository = RegistroRepository(get_tea_session, CatEstrato)
|
||||||
cat_estrato_valor_repository = ReferenceRepository(get_tea_session, CatEstratoValor)
|
cat_estrato_valor_repository = RegistroRepository(get_tea_session, CatEstratoValor)
|
||||||
cat_measure_estrato_repository = ReferenceRepository(get_tea_session, CatMeasureEstrato)
|
cat_measure_estrato_repository = RegistroRepository(get_tea_session, CatMeasureEstrato)
|
||||||
publication_repository = PublicationRepository(
|
publicacion_repository = PublicacionRepository(
|
||||||
get_tea_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
get_tea_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||||
)
|
)
|
||||||
measure_report_unidad_repository = Repository(get_tea_session, MeasureReportUnidad)
|
measure_report_unidad_repository = Repository(get_tea_session, MeasureReportUnidad)
|
||||||
@@ -105,23 +97,17 @@ cat_valor_repository = Repository(get_tea_session, CatValor)
|
|||||||
procedimiento_repository = Repository(get_tea_session, Procedimiento)
|
procedimiento_repository = Repository(get_tea_session, Procedimiento)
|
||||||
observacion_repository = Repository(get_tea_session, Observacion)
|
observacion_repository = Repository(get_tea_session, Observacion)
|
||||||
|
|
||||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||||
staging_repository = StagingRepository(get_tea_session)
|
staging_repository = StagingRepository(get_tea_session)
|
||||||
catalog_repository = CatalogRepository(get_tea_session, CatEstudio, CatResultado, CatValor)
|
catalogo_repository = CatalogoRepository(get_tea_session, CatEstudio, CatResultado, CatValor)
|
||||||
calculation_repository = CalculationRepository(get_tea_session, MeasureReport, periodo=DimPeriodo)
|
calculo_repository = CalculoRepository(get_tea_session, MeasureReport, periodo=DimPeriodo)
|
||||||
history_repository = MeasureHistoryRepository(get_tea_session, MeasureReport, unit_model=MeasureReportUnidad,
|
observar_repository = ObservacionRepository(get_tea_session, PeriodoObservacion)
|
||||||
stratum_model=MeasureReportUnidadEstrato,
|
vistas_repository = VistasRepository(get_tea_session)
|
||||||
value_model=CatEstratoValor)
|
vinculos_repository = VinculosRepository(get_tea_session)
|
||||||
observation_period_repository = ObservationRepository(get_tea_session, PeriodoObservacion)
|
cohorte_repository = CohorteRepository(
|
||||||
views_repository = ViewsRepository(get_tea_session)
|
|
||||||
links_repository = LinksRepository(get_tea_session)
|
|
||||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
|
||||||
timeline_repository = DbtTimelineRepository(get_tea_session, "tea")
|
|
||||||
dbt_query_repository = DbtQueryRepository(get_tea_session)
|
|
||||||
cohort_repository = CohortRepository(
|
|
||||||
get_tea_session,
|
get_tea_session,
|
||||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||||
)
|
)
|
||||||
|
|
||||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||||
materializer = Materializer(get_tea_session)
|
materializador = Materializador(get_tea_session)
|
||||||
|
|||||||
@@ -33,6 +33,4 @@ packages = ["persistance"]
|
|||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
dev = [
|
dev = [
|
||||||
"pytest>=8.0.0",
|
"pytest>=8.0.0",
|
||||||
# Only the tests of `persistance.assets` build Hamilton graphs; the package itself doesn't import it.
|
|
||||||
"apache-hamilton>=1.90",
|
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,151 +0,0 @@
|
|||||||
"""What this module covers: `persistance.assets` (`validate`, `mermaid`, `Asset`, `Layer`, `Owner`) on real Hamilton graphs.
|
|
||||||
|
|
||||||
Fixtures: no pytest fixtures. The module-level functions `staging`, `hechos`, `registro__python`,
|
|
||||||
`measure_report` and `periodo_observacion` form a small indicator cycle (`CYCLE`); `_nodes` builds a
|
|
||||||
Hamilton driver from some of them and returns its nodes. Tests that need a broken graph define the
|
|
||||||
offending function inside the test.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import itertools
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from hamilton import ad_hoc_utils, driver
|
|
||||||
from hamilton.function_modifiers import config, extract_fields, tag
|
|
||||||
|
|
||||||
from persistance.assets import Asset, InvalidGraph, Layer, Owner, mermaid, validate
|
|
||||||
|
|
||||||
_module_names = itertools.count()
|
|
||||||
|
|
||||||
|
|
||||||
def _nodes(*functions, **settings):
|
|
||||||
"""The nodes of a Hamilton graph built from `functions` (each call gets its own module), configured with `settings`."""
|
|
||||||
module = ad_hoc_utils.create_temporary_module(*functions, module_name=f"assets_graph_{next(_module_names)}")
|
|
||||||
return driver.Builder().with_modules(module).with_config(settings).build().list_available_variables()
|
|
||||||
|
|
||||||
|
|
||||||
@tag(layer="bronze", owner="external")
|
|
||||||
def staging() -> Asset:
|
|
||||||
"""Source asset (bronze, external): what the ingestion leaves."""
|
|
||||||
return Asset("staging")
|
|
||||||
|
|
||||||
|
|
||||||
@tag(layer="silver", owner="python")
|
|
||||||
def hechos(staging: Asset) -> Asset:
|
|
||||||
"""Silver asset read from `staging`."""
|
|
||||||
return Asset("hechos", 120)
|
|
||||||
|
|
||||||
|
|
||||||
@config.when(registro_owner="python")
|
|
||||||
@extract_fields({"def_parametro": Asset, "dim_periodo": Asset})
|
|
||||||
@tag(layer="silver", owner="python")
|
|
||||||
def registro__python() -> dict:
|
|
||||||
"""One function, two silver assets (`def_parametro`, `dim_periodo`), selected by `registro_owner="python"`."""
|
|
||||||
return {"def_parametro": Asset("def_parametro"), "dim_periodo": Asset("dim_periodo")}
|
|
||||||
|
|
||||||
|
|
||||||
@tag(layer="gold", owner="python")
|
|
||||||
def measure_report(hechos: Asset, def_parametro: Asset, dim_periodo: Asset) -> Asset:
|
|
||||||
"""Gold asset that reads `hechos` and the two `registry` assets."""
|
|
||||||
return Asset("measure_report", 37)
|
|
||||||
|
|
||||||
|
|
||||||
@tag(layer="silver", owner="python", depends_on="measure_report")
|
|
||||||
def periodo_observacion(hechos: Asset, measure_report: Asset) -> Asset:
|
|
||||||
"""Silver asset that reads `hechos` and waits for `measure_report` without using its data (`depends_on`)."""
|
|
||||||
return Asset("periodo_observacion")
|
|
||||||
|
|
||||||
|
|
||||||
CYCLE = (staging, hechos, registro__python, measure_report, periodo_observacion)
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_consistent_cycle_passes():
|
|
||||||
"""Pins down: a cycle where every asset has a producer, valid tags and a real `depends_on` validates,
|
|
||||||
including the assets split out with `@extract_fields`.
|
|
||||||
|
|
||||||
Fails if `validate` rejects a valid graph, or if tags stop reaching the nodes `@extract_fields` creates.
|
|
||||||
"""
|
|
||||||
validate(_nodes(*CYCLE, registro_owner="python"))
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_asset_with_no_producer_must_be_a_declared_source():
|
|
||||||
"""Pins down: an `Asset` input nobody produces is an error unless it's declared as a source.
|
|
||||||
|
|
||||||
Fails if `validate` stops treating Hamilton's required inputs of type `Asset` as missing producers,
|
|
||||||
or ignores `sources`.
|
|
||||||
"""
|
|
||||||
nodes = _nodes(hechos)
|
|
||||||
with pytest.raises(InvalidGraph, match="staging: read as an asset"):
|
|
||||||
validate(nodes)
|
|
||||||
validate(nodes, sources={"staging"})
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_producing_function_needs_valid_layer_and_owner():
|
|
||||||
"""Pins down: a function returning `Asset` carries a `layer` from `Layer` and an `owner` from `Owner`.
|
|
||||||
|
|
||||||
Fails if either check is dropped or the enum values change.
|
|
||||||
"""
|
|
||||||
@tag(layer="platinum")
|
|
||||||
def cohorte_miembro(hechos: Asset) -> Asset:
|
|
||||||
"""An asset with an unknown layer and no owner."""
|
|
||||||
return Asset("cohorte_miembro")
|
|
||||||
|
|
||||||
with pytest.raises(InvalidGraph) as error:
|
|
||||||
validate(_nodes(staging, hechos, cohorte_miembro))
|
|
||||||
assert "cohorte_miembro: `layer` tag is 'platinum'" in str(error.value)
|
|
||||||
assert "cohorte_miembro: `owner` tag is None" in str(error.value)
|
|
||||||
|
|
||||||
|
|
||||||
def test_depends_on_must_name_a_parameter():
|
|
||||||
"""Pins down: `depends_on` names a parameter of the same function, so an order-only dependency is real
|
|
||||||
in the graph.
|
|
||||||
|
|
||||||
Fails if `validate` stops comparing the tag with the node's dependencies.
|
|
||||||
"""
|
|
||||||
@tag(layer="silver", owner="python", depends_on="measure_report")
|
|
||||||
def periodo_observacion(hechos: Asset) -> Asset:
|
|
||||||
"""Declares `depends_on` on an asset that isn't one of its parameters."""
|
|
||||||
return Asset("periodo_observacion")
|
|
||||||
|
|
||||||
with pytest.raises(InvalidGraph, match="depends_on` names 'measure_report'"):
|
|
||||||
validate(_nodes(staging, hechos, periodo_observacion))
|
|
||||||
|
|
||||||
|
|
||||||
def test_every_problem_is_reported_at_once():
|
|
||||||
"""Pins down: `validate` reports every problem in one error, one per line, instead of stopping at the
|
|
||||||
first.
|
|
||||||
|
|
||||||
Fails if it raises on the first problem or changes the one-line-per-problem format.
|
|
||||||
"""
|
|
||||||
@tag(layer="silver")
|
|
||||||
def cohorte_miembro(staging: Asset) -> Asset:
|
|
||||||
"""Reads `staging`, which nobody produces, and has no owner: two problems."""
|
|
||||||
return Asset("cohorte_miembro")
|
|
||||||
|
|
||||||
with pytest.raises(InvalidGraph) as error:
|
|
||||||
validate(_nodes(cohorte_miembro))
|
|
||||||
assert len(str(error.value).splitlines()) == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
|
|
||||||
"""Pins down: `mermaid` draws one box per asset with its layer and owner, an arrow from producer to
|
|
||||||
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registry`).
|
|
||||||
|
|
||||||
Fails if the diagram format changes, intermediate functions appear, or the order-only arrow stops
|
|
||||||
being dotted.
|
|
||||||
"""
|
|
||||||
diagram = mermaid(_nodes(*CYCLE, registro_owner="python"))
|
|
||||||
assert diagram.startswith("flowchart LR")
|
|
||||||
assert 'hechos["hechos<br/>silver · python"]' in diagram
|
|
||||||
assert " staging --> hechos" in diagram
|
|
||||||
assert " def_parametro --> measure_report" in diagram
|
|
||||||
assert "registro" not in diagram.replace("registro_owner", "")
|
|
||||||
assert " measure_report -.-> periodo_observacion" in diagram
|
|
||||||
assert " hechos --> periodo_observacion" in diagram
|
|
||||||
|
|
||||||
|
|
||||||
def test_enum_values_are_the_tag_values():
|
|
||||||
"""Pins down: the enum values are the strings written in the tags (`"silver"`, `"dbt"`).
|
|
||||||
|
|
||||||
Fails if a value is renamed, which would invalidate every tag already written.
|
|
||||||
"""
|
|
||||||
assert Layer.SILVER == "silver" and Owner.DBT == "dbt"
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
"""What this module covers: the cohort-build reads of `CohortRepository`: `latest_build`, `members`,
|
|
||||||
`build` and `builds`.
|
|
||||||
|
|
||||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables and three builds; `_build`
|
|
||||||
writes one `cohorte_armado` row.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from core.cacu.base import CaCuModel
|
|
||||||
from core.cacu.indicadores.models import (
|
|
||||||
CohorteArmado,
|
|
||||||
CohorteExclusion,
|
|
||||||
CohorteMiembro,
|
|
||||||
CohorteVariable,
|
|
||||||
EvaluacionRiesgo,
|
|
||||||
EvaluacionRiesgoLote,
|
|
||||||
)
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
|
||||||
from sqlmodel import Session, create_engine
|
|
||||||
|
|
||||||
from persistance.edges.gold import CohortBuild, CohortRepository, CohortMember
|
|
||||||
|
|
||||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
|
||||||
EvaluacionRiesgo)
|
|
||||||
|
|
||||||
|
|
||||||
def _build(armado_id, url, fingerprint, known_until=None):
|
|
||||||
"""A `cohorte_armado` row with the parameters the cohort builder writes; `known_until` is its
|
|
||||||
`conocida_hasta`.
|
|
||||||
"""
|
|
||||||
parameters = {"reclutamiento_inicio": "2025-01-01", "reclutamiento_fin": "2026-01-01", "corte": "2025-12-31",
|
|
||||||
"conocida_hasta": known_until}
|
|
||||||
return CohorteArmado(armado_id=armado_id, url=url, version="0.2.0", definicion_sha="d", reglas_sha="r",
|
|
||||||
parametros=json.dumps(parameters), datos_as_of=date(2025, 12, 31), huella=fingerprint, marco_sha="m" + fingerprint,
|
|
||||||
n_miembros=2, armado_en=datetime(2026, 1, armado_id, tzinfo=timezone.utc))
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def repository():
|
|
||||||
"""Builds 1 and 3 of `cacu/cohorte_vigilancia` and build 2 of `cacu/otra`. Build 3 has patients 20 and
|
|
||||||
10 (inserted in that order) and `conocida_hasta` 2026-01-02 08:00 UTC; build 1 has patient 99 and no
|
|
||||||
load cut-off.
|
|
||||||
"""
|
|
||||||
engine = create_engine("sqlite:///:memory:")
|
|
||||||
CaCuModel.metadata.create_all(engine)
|
|
||||||
with Session(engine) as session:
|
|
||||||
session.add_all([
|
|
||||||
_build(1, "cacu/cohorte_vigilancia", "a"),
|
|
||||||
_build(2, "cacu/otra", "b"),
|
|
||||||
_build(3, "cacu/cohorte_vigilancia", "c", known_until="2026-01-02T08:00:00+00:00"),
|
|
||||||
CohorteMiembro(armado_id=3, pac_id=20, fecha_indice=date(2025, 3, 1), indice_fuente_tabla="citologiacervical",
|
|
||||||
indice_fuente_id="20"),
|
|
||||||
CohorteMiembro(armado_id=3, pac_id=10, fecha_indice=date(2025, 2, 1), indice_fuente_tabla="citologiacervical",
|
|
||||||
indice_fuente_id="10"),
|
|
||||||
CohorteMiembro(armado_id=1, pac_id=99, fecha_indice=date(2024, 1, 1), indice_fuente_tabla="citologiacervical",
|
|
||||||
indice_fuente_id="99"),
|
|
||||||
])
|
|
||||||
session.commit()
|
|
||||||
return CohortRepository(lambda: Session(engine), TABLES)
|
|
||||||
|
|
||||||
|
|
||||||
def test_latest_build_of_a_cohort_among_several(repository):
|
|
||||||
"""Pins down: `latest_build` returns the highest build id of the given cohort, ignoring other cohorts.
|
|
||||||
|
|
||||||
Fails if it stops filtering by `url` or picks the build by something other than its id.
|
|
||||||
"""
|
|
||||||
assert repository.latest_build("cacu/cohorte_vigilancia") == 3
|
|
||||||
assert repository.latest_build("cacu/otra") == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_members_of_a_build_in_order(repository):
|
|
||||||
"""Pins down: `members` returns only that build's members, as `CohortMember`, ordered by `pac_id`.
|
|
||||||
|
|
||||||
Fails if the order or the fields of `CohortMember` change, or members of other builds leak in.
|
|
||||||
"""
|
|
||||||
assert repository.members(3) == [
|
|
||||||
CohortMember(10, date(2025, 2, 1), "citologiacervical", "10"),
|
|
||||||
CohortMember(20, date(2025, 3, 1), "citologiacervical", "20"),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def test_lineage_fields_of_a_build(repository):
|
|
||||||
"""Pins down: `build` returns the lineage fields, with `conocida_hasta` parsed from the build's
|
|
||||||
parameters.
|
|
||||||
|
|
||||||
Fails if a field of `CohortBuild` is dropped or reordered, or `conocida_hasta` stops being read from
|
|
||||||
`parametros`.
|
|
||||||
"""
|
|
||||||
assert repository.build(3) == CohortBuild(3, "cacu/cohorte_vigilancia", "0.2.0", "c", "mc", date(2025, 12, 31),
|
|
||||||
datetime(2026, 1, 2, 8, tzinfo=timezone.utc), 2,
|
|
||||||
datetime(2026, 1, 3, tzinfo=timezone.utc))
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_build_made_without_a_load_cut_has_no_known_until(repository):
|
|
||||||
"""Pins down: a build whose `conocida_hasta` is null reports `None`.
|
|
||||||
|
|
||||||
Fails if a null cut-off is turned into a date.
|
|
||||||
"""
|
|
||||||
assert repository.build(1).conocida_hasta is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_every_build_newest_first_or_those_of_one_cohort(repository):
|
|
||||||
"""Pins down: `builds` lists every build newest first, as `CohortBuild` with its lineage fields
|
|
||||||
(`conocida_hasta` read from the parameters), and only one cohort's with `url`; an unknown cohort gives an
|
|
||||||
empty list.
|
|
||||||
|
|
||||||
Fails if the order changes, the `url` filter is dropped, or a build's fields differ from `build`'s.
|
|
||||||
"""
|
|
||||||
assert [b.armado_id for b in repository.builds()] == [3, 2, 1]
|
|
||||||
assert [b.armado_id for b in repository.builds("cacu/cohorte_vigilancia")] == [3, 1]
|
|
||||||
assert repository.builds("cacu/cohorte_vigilancia")[0] == repository.build(3)
|
|
||||||
assert repository.builds("cacu/no_existe") == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_cohort_or_build(repository):
|
|
||||||
"""Pins down: an unknown cohort or build gives `None` or an empty list, not an error.
|
|
||||||
|
|
||||||
Fails if any of the three reads raises on missing data.
|
|
||||||
"""
|
|
||||||
assert repository.latest_build("cacu/no_existe") is None
|
|
||||||
assert repository.build(42) is None
|
|
||||||
assert repository.members(42) == []
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
"""What this module covers: `persistance.edges.dbt`, reading what dbt owns: the timeline from its view
|
|
||||||
(`DbtTimelineRepository`) and the queries it compiled (`DbtQueryRepository`).
|
|
||||||
|
|
||||||
Fixtures: `database`, an in-memory SQLite database with a table behind a `cacu_linea_de_tiempo` view holding three
|
|
||||||
events, dates as text as dbt-sqlite leaves them, and a session factory over it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from sqlalchemy import create_engine, text
|
|
||||||
from sqlalchemy.pool import StaticPool
|
|
||||||
from sqlmodel import Session
|
|
||||||
|
|
||||||
from persistance.edges.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
|
|
||||||
from persistance.edges.silver import TIMELINE_COLUMNS
|
|
||||||
|
|
||||||
EVENTS = [
|
|
||||||
(2, "2025-02-01", "2025-06-01T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
|
|
||||||
(1, "2025-03-01", "2025-03-02T00:00:00+00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
|
|
||||||
(1, "2025-01-05", "2025-01-06T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def database():
|
|
||||||
"""The view over a plain table, and a session factory on the same in-memory connection."""
|
|
||||||
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
|
||||||
with engine.begin() as connection:
|
|
||||||
connection.execute(text(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})"))
|
|
||||||
connection.execute(text("create view cacu_linea_de_tiempo as select * from eventos"))
|
|
||||||
for row in EVENTS:
|
|
||||||
connection.execute(text(f"insert into eventos values ({', '.join(':c%d' % i for i in range(10))})"),
|
|
||||||
{f"c{i}": value for i, value in enumerate(row)})
|
|
||||||
return engine, lambda: Session(engine)
|
|
||||||
|
|
||||||
|
|
||||||
def test_timeline_comes_from_the_view_in_order_with_dates(database):
|
|
||||||
"""Pins down: every event of the view, with the column contract, ordered by patient and date, and `fecha` as a
|
|
||||||
date although SQLite stores text. Fails if the view's name, the order or the date type changes."""
|
|
||||||
_, session_factory = database
|
|
||||||
rows = DbtTimelineRepository(session_factory, "cacu").read()
|
|
||||||
|
|
||||||
assert [(row["pac_id"], row["fuente_id"]) for row in rows] == [(1, "1"), (1, "7"), (2, "3")]
|
|
||||||
assert tuple(rows[0]) == TIMELINE_COLUMNS and rows[0]["fecha"] == date(2025, 1, 5)
|
|
||||||
|
|
||||||
|
|
||||||
def test_filters_run_in_the_query(database):
|
|
||||||
"""Pins down: `patients`, `until` and `known_until` each narrow the rows, the last as an aware datetime against the
|
|
||||||
load times as stored. Fails if a filter is ignored or the load time is compared as text."""
|
|
||||||
_, session_factory = database
|
|
||||||
repository = DbtTimelineRepository(session_factory, "cacu")
|
|
||||||
|
|
||||||
assert {row["pac_id"] for row in repository.read(patients=[2])} == {2}
|
|
||||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
|
||||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1, tzinfo=timezone.utc))] == ["1"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_missing_view_names_the_dbt_command(database):
|
|
||||||
"""Pins down: reading a domain whose view isn't created says which `dbt run` creates it. Fails if the driver's
|
|
||||||
error reaches the caller unexplained."""
|
|
||||||
_, session_factory = database
|
|
||||||
|
|
||||||
with pytest.raises(DbtRelationError, match="dbt run --select cama_linea_de_tiempo"):
|
|
||||||
DbtTimelineRepository(session_factory, "cama").read()
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_compiled_query_gives_one_dict_per_row(database):
|
|
||||||
"""Pins down: a query dbt compiled runs as written and returns its own columns. Fails if the rows lose their
|
|
||||||
column names or the query is altered."""
|
|
||||||
_, session_factory = database
|
|
||||||
rows = DbtQueryRepository(session_factory).read(
|
|
||||||
"with b as (select pac_id from cacu_linea_de_tiempo where tipo = 'biopsia') select distinct pac_id from b")
|
|
||||||
|
|
||||||
assert rows == [{"pac_id": 1}]
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_query_compiled_with_placeholders_takes_its_values_and_lists(database):
|
|
||||||
"""Pins down: a query compiled with bind placeholders runs with the values given, a list filling `in :name`, so
|
|
||||||
one compiled query serves every period. Fails if `parameters` stops being bound or lists stop expanding."""
|
|
||||||
_, session_factory = database
|
|
||||||
rows = DbtQueryRepository(session_factory).read(
|
|
||||||
"select pac_id, fecha from cacu_linea_de_tiempo where fecha >= :desde and tipo in :tipos order by fecha",
|
|
||||||
{"desde": "2025-02-01", "tipos": ["citologia", "biopsia"]})
|
|
||||||
|
|
||||||
assert rows == [{"pac_id": 2, "fecha": "2025-02-01"}, {"pac_id": 1, "fecha": "2025-03-01"}]
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_empty_result_keeps_its_columns(database):
|
|
||||||
"""Pins down: a query with no rows still says which columns it selects, so whoever reads it can count zero.
|
|
||||||
Fails if `rows` builds the column names from the rows."""
|
|
||||||
_, session_factory = database
|
|
||||||
columns, rows = DbtQueryRepository(session_factory).rows(
|
|
||||||
"select pac_id, tipo from cacu_linea_de_tiempo where fecha > :hasta", {"hasta": "2030-01-01"})
|
|
||||||
|
|
||||||
assert (columns, rows) == (["pac_id", "tipo"], [])
|
|
||||||
|
|
||||||
|
|
||||||
def test_reading_writes_nothing(database):
|
|
||||||
"""Pins down: both repositories read on a read-only session and leave the database as it was. Fails if a read
|
|
||||||
starts committing or creating objects."""
|
|
||||||
engine, session_factory = database
|
|
||||||
DbtTimelineRepository(session_factory, "cacu").read()
|
|
||||||
DbtQueryRepository(session_factory).read("select count(*) as n from cacu_linea_de_tiempo")
|
|
||||||
|
|
||||||
with engine.connect() as connection:
|
|
||||||
names = connection.execute(text("select name from sqlite_master order by name")).fetchall()
|
|
||||||
assert names == [("cacu_linea_de_tiempo",), ("eventos",)]
|
|
||||||
@@ -2,27 +2,27 @@ import pytest
|
|||||||
from sqlalchemy import Column, Integer, MetaData, Table, create_engine, insert, select
|
from sqlalchemy import Column, Integer, MetaData, Table, create_engine, insert, select
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
from persistance.materializer import Materializer, ReadOnly
|
from persistance.materializador import Materializador, SoloLectura
|
||||||
|
|
||||||
metadata = MetaData()
|
metadata = MetaData()
|
||||||
numeros = Table("numeros", metadata, Column("n", Integer, primary_key=True))
|
numeros = Table("numeros", metadata, Column("n", Integer, primary_key=True))
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def materializer():
|
def materializador():
|
||||||
engine = create_engine("sqlite://")
|
engine = create_engine("sqlite://")
|
||||||
metadata.create_all(engine)
|
metadata.create_all(engine)
|
||||||
return Materializer(lambda: Session(engine))
|
return Materializador(lambda: Session(engine))
|
||||||
|
|
||||||
|
|
||||||
def test_the_function_reads_and_the_body_writes(materializer):
|
def test_the_function_reads_and_the_body_writes(materializador):
|
||||||
def escribir(sesion, filas):
|
def escribir(sesion, filas):
|
||||||
sesion.execute(insert(numeros), [{"n": n} for n in filas])
|
sesion.execute(insert(numeros), [{"n": n} for n in filas])
|
||||||
sesion.commit()
|
sesion.commit()
|
||||||
return len(filas)
|
return len(filas)
|
||||||
|
|
||||||
assert materializer.materialize(lambda sesion: [1, 2, 3], escribir) == 3
|
assert materializador.materializar(lambda sesion: [1, 2, 3], escribir) == 3
|
||||||
assert materializer.materialize(lambda sesion: sesion.execute(select(numeros.c.n)).scalars().all()) == [1, 2, 3]
|
assert materializador.materializar(lambda sesion: sesion.execute(select(numeros.c.n)).scalars().all()) == [1, 2, 3]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("escribe", [
|
@pytest.mark.parametrize("escribe", [
|
||||||
@@ -30,6 +30,6 @@ def test_the_function_reads_and_the_body_writes(materializer):
|
|||||||
lambda sesion: sesion.commit(),
|
lambda sesion: sesion.commit(),
|
||||||
lambda sesion: sesion.execute(insert(numeros).values(n=1)),
|
lambda sesion: sesion.execute(insert(numeros).values(n=1)),
|
||||||
])
|
])
|
||||||
def test_the_function_cannot_write(materializer, escribe):
|
def test_the_function_cannot_write(materializador, escribe):
|
||||||
with pytest.raises(ReadOnly):
|
with pytest.raises(SoloLectura):
|
||||||
materializer.materialize(escribe)
|
materializador.materializar(escribe)
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
"""What this module covers: the per-patient reads of `CohortRepository` behind the risk route: `membership` (the
|
|
||||||
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons).
|
|
||||||
|
|
||||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables: builds 1 and 2 of the surveillance cohort
|
|
||||||
(patient 10 in both, patient 20 only in build 1), patient 10's variables in build 2, and batches written and confirmed
|
|
||||||
through the repository itself.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from core.cacu.base import CaCuModel
|
|
||||||
from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, CohorteMiembro, CohorteVariable,
|
|
||||||
EvaluacionRiesgo, EvaluacionRiesgoLote)
|
|
||||||
from core.indicadores.cohortes import TablasCohorte
|
|
||||||
from sqlmodel import Session, create_engine
|
|
||||||
|
|
||||||
from persistance.edges.gold import CohortRepository, RiskHorizon
|
|
||||||
|
|
||||||
URL = "cacu/cohorte_vigilancia"
|
|
||||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
|
||||||
EvaluacionRiesgo)
|
|
||||||
PROVENANCE = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"}
|
|
||||||
|
|
||||||
|
|
||||||
def _build(armado_id):
|
|
||||||
return CohorteArmado(armado_id=armado_id, url=URL, version=f"0.{armado_id}.0", definicion_sha="d", reglas_sha="r",
|
|
||||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella=f"h{armado_id}", marco_sha="m",
|
|
||||||
n_miembros=2, armado_en=datetime(2027, 1, armado_id, tzinfo=timezone.utc))
|
|
||||||
|
|
||||||
|
|
||||||
def _member(armado_id, pac_id):
|
|
||||||
return CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=date(2025, 1, armado_id),
|
|
||||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def repository():
|
|
||||||
engine = create_engine("sqlite:///:memory:")
|
|
||||||
CaCuModel.metadata.create_all(engine)
|
|
||||||
with Session(engine) as session:
|
|
||||||
session.add_all([_build(1), _build(2), _member(1, 10), _member(1, 20), _member(2, 10)])
|
|
||||||
session.add_all([CohorteVariable(armado_id=2, pac_id=10, variable="pap_0", valor_codigo="ASC-US"),
|
|
||||||
CohorteVariable(armado_id=2, pac_id=10, variable="c", valor_numerico=0.0)])
|
|
||||||
session.commit()
|
|
||||||
return CohortRepository(lambda: Session(engine), TABLES)
|
|
||||||
|
|
||||||
|
|
||||||
def _batch(repository, version, risks, armado_id=2):
|
|
||||||
return repository.save_batch(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_membership_is_in_the_latest_build_with_its_variables(repository):
|
|
||||||
"""Pins down: the patient is looked up in the cohort's latest build, and its variables come as code or number.
|
|
||||||
Fails if an older build is used (patient 20 would appear) or a numeric variable is lost."""
|
|
||||||
found = repository.membership(10, URL)
|
|
||||||
|
|
||||||
assert (found.armado_id, found.version, found.fecha_indice) == (2, "0.2.0", date(2025, 1, 2))
|
|
||||||
assert found.variables == {"pap_0": "ASC-US", "c": 0.0}
|
|
||||||
assert repository.membership(20, URL) is None and repository.membership(10, "cacu/otra") is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_unconfirmed_batch_is_not_current(repository):
|
|
||||||
"""Pins down: a batch with only preliminary evaluations isn't shown. Fails if a risk nobody confirmed reaches the
|
|
||||||
patient's record."""
|
|
||||||
_batch(repository, "1", [(10, 1.0, 0.2, None, None)])
|
|
||||||
|
|
||||||
assert repository.current_risk(10) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(repository):
|
|
||||||
"""Pins down: among confirmed batches the newest wins, even when a newer unconfirmed one exists; its horizons come
|
|
||||||
in ascending order with their latest state. Fails if the newest batch is taken regardless of its state, or the
|
|
||||||
horizons come unordered."""
|
|
||||||
first = _batch(repository, "1", [(10, 3.0, 0.3, None, None), (10, 1.0, 0.1, 0.05, 0.2)])
|
|
||||||
repository.change_state(first, "final", "revisado")
|
|
||||||
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
|
|
||||||
|
|
||||||
risk = repository.current_risk(10)
|
|
||||||
|
|
||||||
assert (risk.lote_id, risk.modelo_version, risk.estado_lote) == (first, "1", "final")
|
|
||||||
assert risk.horizontes == [RiskHorizon(1.0, 0.1, 0.05, 0.2, "final"), RiskHorizon(3.0, 0.3, None, None, "final")]
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_annulled_batch_is_no_longer_current(repository):
|
|
||||||
"""Pins down: once a confirmed batch is marked `entered-in-error`, its latest versions aren't final and it stops
|
|
||||||
being current. Fails if any version ever confirmed keeps a withdrawn risk on the record."""
|
|
||||||
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
|
|
||||||
repository.change_state(first, "final", "revisado")
|
|
||||||
repository.change_state(first, "entered-in-error", "modelo equivocado")
|
|
||||||
|
|
||||||
assert repository.current_risk(10) is None
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
"""What this module covers: `TimelineRepository` (column contract, filters, read-only session, binding the
|
|
||||||
query) and the `timeline_repository` each domain module binds to dbt's view.
|
|
||||||
|
|
||||||
Fixtures: `session_factory`, an in-memory SQLite table `timeline_events` with the three events in `ROWS`;
|
|
||||||
`timeline_query` stands in for the injected query over that table.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import date, datetime
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, create_engine, insert, select
|
|
||||||
from sqlalchemy.pool import StaticPool
|
|
||||||
from sqlmodel import Session
|
|
||||||
|
|
||||||
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineContractError, TimelineQueryMissing, TimelineRepository
|
|
||||||
from persistance.materializer import ReadOnly
|
|
||||||
|
|
||||||
metadata = MetaData()
|
|
||||||
events = Table(
|
|
||||||
"timeline_events", metadata,
|
|
||||||
Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime),
|
|
||||||
Column("clase", String), Column("tipo", String), Column("codigo", String),
|
|
||||||
Column("valor_codigo", String), Column("valor_numerico", Float),
|
|
||||||
Column("fuente_tabla", String), Column("fuente_id", String),
|
|
||||||
)
|
|
||||||
|
|
||||||
ROWS = [
|
|
||||||
{"pac_id": 1, "fecha": date(2025, 1, 5), "conocida_en": datetime(2025, 1, 6), "clase": "procedimiento",
|
|
||||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "SATISFACTORIA", "valor_numerico": None,
|
|
||||||
"fuente_tabla": "citologiacervical", "fuente_id": "1"},
|
|
||||||
{"pac_id": 1, "fecha": date(2025, 3, 1), "conocida_en": datetime(2025, 3, 2), "clase": "medicion",
|
|
||||||
"tipo": "biopsia", "codigo": "cin", "valor_codigo": "LIEAG", "valor_numerico": None,
|
|
||||||
"fuente_tabla": "biopsiacervical", "fuente_id": "7"},
|
|
||||||
{"pac_id": 2, "fecha": date(2025, 2, 1), "conocida_en": datetime(2025, 6, 1), "clase": "procedimiento",
|
|
||||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": None, "valor_numerico": None,
|
|
||||||
"fuente_tabla": "citologiacervical", "fuente_id": "3"},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def session_factory():
|
|
||||||
"""Three events: patient 1, a cytology (2025-01-05) and a biopsy (2025-03-01), both loaded early in
|
|
||||||
2025; patient 2, a cytology (2025-02-01) loaded on 2025-06-01.
|
|
||||||
"""
|
|
||||||
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
|
||||||
metadata.create_all(engine)
|
|
||||||
with engine.begin() as connection:
|
|
||||||
connection.execute(insert(events), ROWS)
|
|
||||||
return lambda: Session(engine)
|
|
||||||
|
|
||||||
|
|
||||||
def timeline_query(*, patients, until, known_until):
|
|
||||||
"""Stands in for the injected query: same columns and filters, over a plain table."""
|
|
||||||
query = select(*(events.c[name] for name in TIMELINE_COLUMNS))
|
|
||||||
if patients is not None:
|
|
||||||
query = query.where(events.c.pac_id.in_(patients))
|
|
||||||
if until is not None:
|
|
||||||
query = query.where(events.c.fecha <= until)
|
|
||||||
if known_until is not None:
|
|
||||||
query = query.where(events.c.conocida_en <= known_until)
|
|
||||||
return query.order_by(events.c.pac_id, events.c.fecha)
|
|
||||||
|
|
||||||
|
|
||||||
def test_reads_every_event_with_the_contract_columns(session_factory):
|
|
||||||
"""Pins down: with no filters, `read` returns every event as a dict keyed by `TIMELINE_COLUMNS`, in the
|
|
||||||
query's order.
|
|
||||||
|
|
||||||
Fails if the keys or their order change, or rows are dropped or reordered.
|
|
||||||
"""
|
|
||||||
rows = TimelineRepository(session_factory, timeline_query).read()
|
|
||||||
assert [tuple(row) for row in rows] == [TIMELINE_COLUMNS] * 3
|
|
||||||
assert [(row["pac_id"], row["tipo"]) for row in rows] == [(1, "citologia"), (1, "biopsia"), (2, "citologia")]
|
|
||||||
|
|
||||||
|
|
||||||
def test_filters_reach_the_query(session_factory):
|
|
||||||
"""Pins down: `patients`, `until` and `known_until` reach the query unchanged (an iterator of patients
|
|
||||||
included).
|
|
||||||
|
|
||||||
Fails if a filter is renamed, dropped or not turned into a list.
|
|
||||||
"""
|
|
||||||
repository = TimelineRepository(session_factory, timeline_query)
|
|
||||||
assert [row["fuente_id"] for row in repository.read(patients=[1])] == ["1", "7"]
|
|
||||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
|
||||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 5, 1))] == ["1", "7"]
|
|
||||||
assert repository.read(patients=iter([2]), until=date(2025, 1, 31)) == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_query_with_other_columns_breaks_the_contract(session_factory):
|
|
||||||
"""Pins down: `read` refuses a query whose columns aren't exactly `TIMELINE_COLUMNS`.
|
|
||||||
|
|
||||||
Fails if the contract check is removed, or `TIMELINE_COLUMNS` changes without the queries.
|
|
||||||
"""
|
|
||||||
def short_query(*, patients, until, known_until):
|
|
||||||
"""Returns only two of the contract's columns."""
|
|
||||||
return select(events.c.pac_id, events.c.fecha)
|
|
||||||
|
|
||||||
with pytest.raises(TimelineContractError, match="expected columns"):
|
|
||||||
TimelineRepository(session_factory, short_query).read()
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_query_runs_on_a_read_only_session(session_factory):
|
|
||||||
"""Pins down: the query runs on a `ReadSession`, so a query that writes is rejected.
|
|
||||||
|
|
||||||
Fails if `read` uses a plain session.
|
|
||||||
"""
|
|
||||||
def writing_query(*, patients, until, known_until):
|
|
||||||
"""Returns an INSERT instead of a SELECT."""
|
|
||||||
return insert(events).values(pac_id=9)
|
|
||||||
|
|
||||||
with pytest.raises(ReadOnly):
|
|
||||||
TimelineRepository(session_factory, writing_query).read()
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_repository_without_a_query_is_bound_with_with_query(session_factory):
|
|
||||||
"""Pins down: a repository created without a query can't read, and `with_query` returns one that can,
|
|
||||||
on the same session factory.
|
|
||||||
|
|
||||||
Fails if reading without a query stops raising `TimelineQueryMissing`, or `with_query` loses the
|
|
||||||
session factory.
|
|
||||||
"""
|
|
||||||
unbound = TimelineRepository(session_factory)
|
|
||||||
with pytest.raises(TimelineQueryMissing):
|
|
||||||
unbound.read()
|
|
||||||
assert len(unbound.with_query(timeline_query).read()) == 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_each_domain_module_reads_its_dbt_view_and_can_be_rebound(session_factory):
|
|
||||||
"""Pins down: `persistance.cacu`, `cama` and `tea` each bind `timeline_repository` to their own dbt view and
|
|
||||||
expose `dbt_query_repository`, and `with_query` still binds another query.
|
|
||||||
|
|
||||||
Fails if a domain module drops either repository, reads another domain's view, or loses `with_query`.
|
|
||||||
"""
|
|
||||||
from persistance import cacu, cama, tea
|
|
||||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
|
||||||
|
|
||||||
for name, domain in (("cacu", cacu), ("cama", cama), ("tea", tea)):
|
|
||||||
assert isinstance(domain.timeline_repository, DbtTimelineRepository)
|
|
||||||
assert domain.timeline_repository.view == f"{name}_linea_de_tiempo"
|
|
||||||
assert isinstance(domain.dbt_query_repository, DbtQueryRepository)
|
|
||||||
rebound = cacu.timeline_repository.with_query(timeline_query)
|
|
||||||
rebound._session_factory = session_factory
|
|
||||||
assert len(rebound.read()) == 3
|
|
||||||
@@ -15,11 +15,10 @@ operación, en [`dist/MANUAL.md`](dist/MANUAL.md).
|
|||||||
| `Core/` | Esquema SQLModel (tablas y vocabularios controlados) de cada padecimiento y de gobernanza. Cada dominio tiene su propio registro de SQLAlchemy. |
|
| `Core/` | Esquema SQLModel (tablas y vocabularios controlados) de cada padecimiento y de gobernanza. Cada dominio tiene su propio registro de SQLAlchemy. |
|
||||||
| `Persistance/` | Conexión, repositorios y migraciones de Alembic (una cadena por base). Cuatro bases independientes: CaCu, CaMa, TEA y gobernanza. |
|
| `Persistance/` | Conexión, repositorios y migraciones de Alembic (una cadena por base). Cuatro bases independientes: CaCu, CaMa, TEA y gobernanza. |
|
||||||
| `Extraction/` | Lectura de documentos clínicos (PDF con texto o escaneado, imágenes) y de EEG (EDF, con MNE): OCR, separación por paciente, extracción de campos y combinación de registros. |
|
| `Extraction/` | Lectura de documentos clínicos (PDF con texto o escaneado, imágenes) y de EEG (EDF, con MNE): OCR, separación por paciente, extracción de campos y combinación de registros. |
|
||||||
| `WebApi/` (submódulo) | API REST en Flask: importación, consulta de datos, indicadores, bitácora y gobernanza. `GET /api` lista las rutas. `webapi/orchestration/` es el ciclo de indicadores de cada dominio (staging → plata → reportes), con Hamilton. |
|
| `WebApi/` (submódulo) | API REST en Flask: importación, consulta de datos, indicadores, bitácora y gobernanza. `GET /api` lista las rutas. `webapi/orquestacion/` es el ciclo de indicadores de cada dominio (staging → plata → reportes), con Hamilton. |
|
||||||
| `WebApp/` (submódulo) | Interfaz en Angular y Angular Material. |
|
| `WebApp/` (submódulo) | Interfaz en Angular y Angular Material. |
|
||||||
| `models/` (submódulo) | Registro de modelos en MLflow, predicciones y trabajos de OCR de reportes. |
|
| `models/` (submódulo) | Registro de modelos en MLflow, predicciones y trabajos de OCR de reportes. |
|
||||||
| `Transformation/` | dbt: los modelos sobre la plata genérica y las definiciones de los indicadores (capa semántica). |
|
| `indicadores_kit/` (submódulo) | Definiciones y cálculo de los indicadores, del equipo clínico. |
|
||||||
| `indicadores_kit/` (submódulo) | Ya sin código: sus indicadores están en `Transformation/`, su carga, referencias y lista de seguimiento en `WebApi/`, y sus cohortes en `models/`. |
|
|
||||||
| `dist/` | Paquete de instalación: `docker-compose.yml`, scripts y manual. |
|
| `dist/` | Paquete de instalación: `docker-compose.yml`, scripts y manual. |
|
||||||
|
|
||||||
Cambiar de motor de base de datos (SQLite, MySQL/MariaDB, PostgreSQL o SQL
|
Cambiar de motor de base de datos (SQLite, MySQL/MariaDB, PostgreSQL o SQL
|
||||||
@@ -49,7 +48,7 @@ uv run python main.py # http://localhost:5050
|
|||||||
cd WebApp && npm install && npm start # http://localhost:4200
|
cd WebApp && npm install && npm start # http://localhost:4200
|
||||||
|
|
||||||
# Indicadores de un dominio, después de importar datos
|
# Indicadores de un dominio, después de importar datos
|
||||||
cd WebApi && uv run python -m webapi.orchestration cycle cacu --from 2021 --to 2026 --allow-undecided
|
cd WebApi && uv run python -m webapi.orquestacion ciclo cacu --desde 2021 --hasta 2026 --permitir-sin-definir
|
||||||
```
|
```
|
||||||
|
|
||||||
Con Docker, `docker compose up --build` levanta la API (puerto 5050), el
|
Con Docker, `docker compose up --build` levanta la API (puerto 5050), el
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
target/
|
|
||||||
dbt_packages/
|
|
||||||
logs/
|
|
||||||
*.duckdb
|
|
||||||
uv.lock
|
|
||||||
.user.yml
|
|
||||||
package-lock.yml
|
|
||||||
.venv/
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
name: isssteleon
|
|
||||||
version: "1.0.0"
|
|
||||||
config-version: 2
|
|
||||||
profile: cacu
|
|
||||||
model-paths: ["models"]
|
|
||||||
test-paths: ["tests"]
|
|
||||||
vars:
|
|
||||||
rec_inicio: "2018-01-01"
|
|
||||||
rec_fin: "2026-12-31"
|
|
||||||
ventana_basal_dias: 90
|
|
||||||
grados_evento: ["LIEAG", "CIS", "CARCINOMA"]
|
|
||||||
# Parámetros de corrida: se sobreescriben con --vars al ejecutar
|
|
||||||
periodo_inicio: "2024-01-01"
|
|
||||||
periodo_fin: "2024-07-01"
|
|
||||||
fecha_corte: "2024-12-31"
|
|
||||||
deteccion_grados: ["LIEAG", "CIS", "CARCINOMA"]
|
|
||||||
# Parámetros de catálogo CaCu (cacu.parametros en indicadores_kit)
|
|
||||||
calidad_insatisfactoria: "INSATISFACTORIO"
|
|
||||||
citologia_anomala: ["ASC-US", "ASC-H", "LIEBG", "LIEAG", "CIS"]
|
|
||||||
citologia_alto_grado: ["ASC-H", "LIEAG", "CIS"]
|
|
||||||
catalogo_biopsia: ["NORMAL", "LIEBG", "LIEAG", "CIS", "CARCINOMA"]
|
|
||||||
especialidades_diagnostico: ["CLINICA_MUJER_COLPOSCOPIA", "CIRUGIA_ONCOLOGICA"]
|
|
||||||
# CIE-10 without the dot, compared exactly (the kit's cacu.diagnostico.cie and .cie_antecedente; provisional).
|
|
||||||
# A medical note with one of these resolves a cytology:
|
|
||||||
cie_diagnostico: ["Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
|
|
||||||
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
|
||||||
# A note with one of these before the cytology leaves it out: the patient is already a case.
|
|
||||||
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
|
||||||
horizonte_toma_reporte_dias: 60
|
|
||||||
horizonte_toma_diagnostico_dias: 180
|
|
||||||
# ASCCP follow-up (the kit's cacu.seguimiento.*; provisional): what counts as a colposcopy and a treatment
|
|
||||||
# (models/cacu/silver/cacu_procedimientos_inferidos.sql).
|
|
||||||
seguimiento:
|
|
||||||
colposcopia_evidencias: ["motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia"]
|
|
||||||
colposcopia_requisito: "valoracion_previa"
|
|
||||||
biopsia_requisito: "mismo_dia_que_colposcopia"
|
|
||||||
colposcopia_motivos: ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
|
|
||||||
colposcopia_especialidades: ["CLINICA_MUJER_COLPOSCOPIA"]
|
|
||||||
colposcopia_cie: ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
|
|
||||||
colposcopia_diagnosticos: ["VIRUS DEL PAPILOMA HUMANO"]
|
|
||||||
tratamiento_cie: ["D06", "D060", "D061", "D067", "D069"]
|
|
||||||
vigilancia_especialidades: ["MEDICINA_FAMILIAR", "CLINICA_MUJER_COLPOSCOPIA"]
|
|
||||||
# The risk estimates a band summary reads (the kit's cacu.riesgos.horizonte_banda; provisional): years from the
|
|
||||||
# index date, 0 is prevalent.
|
|
||||||
riesgos_horizonte_banda: 0
|
|
||||||
# CaMa's rules (the kit's cama.*; provisional). The diagnosis rules: a note with one of `cie_diagnostico` written by
|
|
||||||
# one of `especialidades_diagnostico` resolves a mammogram within `horizonte_toma_diagnostico_dias`; one with one
|
|
||||||
# of `cie_antecedente` before it leaves it out. `birads_gravedad`: BI-RADS from least to most severe.
|
|
||||||
cama:
|
|
||||||
cie_diagnostico: ["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"]
|
|
||||||
cie_antecedente: ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505",
|
|
||||||
"C506", "C508", "C509"]
|
|
||||||
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
|
|
||||||
horizonte_toma_diagnostico_dias: 180
|
|
||||||
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
|
|
||||||
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
|
|
||||||
surveillance_cohort:
|
|
||||||
recruitment_start: "2024-01-01"
|
|
||||||
recruitment_end: "2027-01-01"
|
|
||||||
cutoff: "2026-12-31"
|
|
||||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
|
||||||
# models/<project>/silver: what dbt derives from silver's procedimiento and observacion_clinica, compiled as
|
|
||||||
# CTEs inside the models that use them (no objects in the database), except the timeline, a view.
|
|
||||||
# models/<project>/gold/<family>: one view per indicator, a folder per family as in the kit.
|
|
||||||
# Run one domain at a time against its own database: dbt build --profile cacu --select cacu
|
|
||||||
models:
|
|
||||||
isssteleon:
|
|
||||||
cacu:
|
|
||||||
silver:
|
|
||||||
+materialized: ephemeral
|
|
||||||
+tags: ["silver"]
|
|
||||||
gold:
|
|
||||||
+materialized: view
|
|
||||||
+tags: ["gold"]
|
|
||||||
cama:
|
|
||||||
silver:
|
|
||||||
+materialized: ephemeral
|
|
||||||
+tags: ["silver"]
|
|
||||||
gold:
|
|
||||||
+materialized: view
|
|
||||||
+tags: ["gold"]
|
|
||||||
tea:
|
|
||||||
silver:
|
|
||||||
+materialized: ephemeral
|
|
||||||
+tags: ["silver"]
|
|
||||||
gold:
|
|
||||||
+materialized: view
|
|
||||||
+tags: ["gold"]
|
|
||||||
|
|
||||||
|
|
||||||
# The project's own macros come first for dbt's dispatched macros (`datediff` on SQLite: macros/datediff.sql).
|
|
||||||
dispatch:
|
|
||||||
- macro_namespace: dbt
|
|
||||||
search_order: ["isssteleon", "dbt"]
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
{#
|
|
||||||
Casts for a model's output columns, so every engine returns the same types. dbt's type names work in
|
|
||||||
CAST on SQLite, SQL Server and PostgreSQL; MySQL only casts to CHAR and SIGNED.
|
|
||||||
#}
|
|
||||||
{% macro as_text(expression) -%}
|
|
||||||
{{ return(adapter.dispatch('as_text', 'isssteleon')(expression)) }}
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro default__as_text(expression) -%}
|
|
||||||
cast({{ expression }} as {{ dbt.type_string() }})
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro mysql__as_text(expression) -%}
|
|
||||||
cast({{ expression }} as char)
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro as_integer(expression) -%}
|
|
||||||
{{ return(adapter.dispatch('as_integer', 'isssteleon')(expression)) }}
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro default__as_integer(expression) -%}
|
|
||||||
cast({{ expression }} as {{ dbt.type_int() }})
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro mysql__as_integer(expression) -%}
|
|
||||||
cast({{ expression }} as signed)
|
|
||||||
{%- endmacro %}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
{#
|
|
||||||
A date written in the SQL, from a 'YYYY-MM-DD' value (a variable such as `fecha_corte`).
|
|
||||||
|
|
||||||
Elsewhere it's `cast('…' as date)`. SQLite has no date type: that cast yields the number 2025, so on SQLite
|
|
||||||
the date stays an ISO string, which is what its date functions (`julianday`) read.
|
|
||||||
#}
|
|
||||||
{% macro date_literal(value) -%}
|
|
||||||
{{ return(adapter.dispatch('date_literal', 'isssteleon')(value)) }}
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro default__date_literal(value) -%}
|
|
||||||
cast('{{ value }}' as date)
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{% macro sqlite__date_literal(value) -%}
|
|
||||||
'{{ value }}'
|
|
||||||
{%- endmacro %}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
{#
|
|
||||||
dbt's `datediff` on SQLite, which has no `datediff` function: whole days between two dates, through
|
|
||||||
`julianday`. Only days are needed so far; any other part fails at compile time instead of returning a
|
|
||||||
wrong number. The other engines keep their own `datediff`.
|
|
||||||
#}
|
|
||||||
{% macro sqlite__datediff(first_date, second_date, datepart) -%}
|
|
||||||
{%- if datepart | lower != 'day' -%}
|
|
||||||
{{ exceptions.raise_compiler_error("datediff on SQLite only supports 'day', not '" ~ datepart ~ "'") }}
|
|
||||||
{%- endif -%}
|
|
||||||
cast(julianday({{ second_date }}) - julianday({{ first_date }}) as integer)
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{#
|
|
||||||
On MySQL (dbt-mysql 1.7 has no `datediff` of its own, so dbt would write SQL Server's form): MySQL's
|
|
||||||
`DATEDIFF(a, b)` is the whole days from b to a.
|
|
||||||
#}
|
|
||||||
{% macro mysql__datediff(first_date, second_date, datepart) -%}
|
|
||||||
{%- if datepart | lower != 'day' -%}
|
|
||||||
{{ exceptions.raise_compiler_error("datediff on MySQL only supports 'day', not '" ~ datepart ~ "'") }}
|
|
||||||
{%- endif -%}
|
|
||||||
datediff({{ second_date }}, {{ first_date }})
|
|
||||||
{%- endmacro %}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
{#
|
|
||||||
Each patient's timeline, from silver's procedimiento and observacion_clinica: one UNION ALL branch per source
|
|
||||||
(a domain's `fuentes`, declared in its timeline model's YAML). Columns: pac_id, fecha, conocida_en, clase, tipo,
|
|
||||||
codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id.
|
|
||||||
|
|
||||||
Per source:
|
|
||||||
- the procedures of its `clase` (and `estudio_id`, unless null: an order of any study);
|
|
||||||
- its value: the observation of `resultado_id`, read by the result's type in `cat_resultado` (a code is
|
|
||||||
coalesce(valor_id, valor_fuente)), or a number with `valor: numerico`; without a result, the procedure's
|
|
||||||
`columna`, trimmed;
|
|
||||||
- its date and patient: the procedure's, or its parent's (`del_padre`); an observed date (`fecha_resultado`)
|
|
||||||
goes first; `fecha: nacimiento` takes the person's birth date;
|
|
||||||
- `conocida_en`: the start of the load that wrote the row (the observation's, or else the procedure's);
|
|
||||||
- rows without a date are left out, and so are measurements, diagnoses and history without a value.
|
|
||||||
#}
|
|
||||||
{% macro linea_de_tiempo(fuentes) -%}
|
|
||||||
select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
|
|
||||||
from (
|
|
||||||
{%- for f in fuentes %}
|
|
||||||
{% if not loop.first %}union all{% endif %}
|
|
||||||
{{ linea_de_tiempo_fuente(f) }}
|
|
||||||
{%- endfor %}
|
|
||||||
) linea
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
|
|
||||||
{% macro linea_de_tiempo_fuente(f) -%}
|
|
||||||
{%- set resultado = f.get('resultado_id') -%}
|
|
||||||
{%- set con_fecha = 'padre' if f.get('del_padre') else 'p' -%}
|
|
||||||
{%- set fecha = con_fecha ~ '.fecha' -%}
|
|
||||||
{%- if f.get('fecha_resultado') -%}{%- set fecha = 'coalesce(fecha_observada.valor_fecha, ' ~ fecha ~ ')' -%}{%- endif -%}
|
|
||||||
{%- if f.get('fecha') == 'nacimiento' -%}{%- set fecha = 'persona.fecha_nacimiento' -%}{%- endif -%}
|
|
||||||
{%- if resultado and f.get('valor') == 'numerico' -%}
|
|
||||||
{%- set valor_codigo = as_text('null') -%}
|
|
||||||
{%- set valor_numerico = 'cast(o.valor_numerico as ' ~ dbt.type_float() ~ ')' -%}
|
|
||||||
{%- elif resultado -%}
|
|
||||||
{#- Every branch as text: SQL Server gives a CASE the type of highest precedence among its branches, so a
|
|
||||||
number and a date in one CASE fail there. -#}
|
|
||||||
{%- set valor_codigo =
|
|
||||||
"case r.tipo_valor"
|
|
||||||
~ " when 'codigo' then " ~ as_text('coalesce(o.valor_id, o.valor_fuente)')
|
|
||||||
~ " when 'booleano' then " ~ as_text(as_integer('o.valor_numerico'))
|
|
||||||
~ " when 'numero' then " ~ as_text('o.valor_numerico')
|
|
||||||
~ " when 'fecha' then " ~ as_text('o.valor_fecha')
|
|
||||||
~ " else " ~ as_text('o.valor_texto') ~ " end" -%}
|
|
||||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
|
||||||
{%- elif f.get('columna') -%}
|
|
||||||
{%- set valor_codigo = "nullif(ltrim(rtrim(p." ~ f['columna'] ~ ")), '')" -%}
|
|
||||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
|
||||||
{%- else -%}
|
|
||||||
{%- set valor_codigo = as_text('null') -%}
|
|
||||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
|
||||||
{%- endif %}
|
|
||||||
select
|
|
||||||
{{ con_fecha }}.pac_id as pac_id,
|
|
||||||
{{ fecha }} as fecha,
|
|
||||||
carga.inicio as conocida_en,
|
|
||||||
{{ as_text("'" ~ f['clase_de_linea'] ~ "'") }} as clase,
|
|
||||||
{{ as_text("'" ~ f['tipo'] ~ "'") }} as tipo,
|
|
||||||
{{ as_text("'" ~ (f.get('codigo') or f['tipo']) ~ "'") }} as codigo,
|
|
||||||
{{ valor_codigo }} as valor_codigo,
|
|
||||||
{{ valor_numerico }} as valor_numerico,
|
|
||||||
p.fuente_tabla as fuente_tabla,
|
|
||||||
p.fuente_id as fuente_id
|
|
||||||
from {{ source('silver', 'procedimiento') }} p
|
|
||||||
{%- if resultado %}
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o
|
|
||||||
on o.procedimiento_id = p.procedimiento_id and o.resultado_id = '{{ resultado }}'
|
|
||||||
left join {{ source('silver', 'cat_resultado') }} r
|
|
||||||
on r.resultado_id = '{{ resultado }}'
|
|
||||||
{%- endif %}
|
|
||||||
{%- if f.get('del_padre') %}
|
|
||||||
join {{ source('silver', 'procedimiento') }} padre
|
|
||||||
on padre.procedimiento_id = p.padre_id
|
|
||||||
{%- endif %}
|
|
||||||
{%- if f.get('fecha_resultado') %}
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} fecha_observada
|
|
||||||
on fecha_observada.procedimiento_id = {{ con_fecha }}.procedimiento_id
|
|
||||||
and fecha_observada.resultado_id = '{{ f['fecha_resultado'] }}'
|
|
||||||
{%- endif %}
|
|
||||||
{%- if f.get('fecha') == 'nacimiento' %}
|
|
||||||
join {{ source('silver', 'persona') }} persona
|
|
||||||
on persona.pac_id = {{ con_fecha }}.pac_id
|
|
||||||
{%- endif %}
|
|
||||||
join {{ source('silver', 'carga') }} carga
|
|
||||||
on carga.carga_id = {{ 'coalesce(o.carga_id, p.carga_id)' if resultado else 'p.carga_id' }}
|
|
||||||
where p.clase = '{{ f['clase'] }}'
|
|
||||||
and {{ fecha }} is not null
|
|
||||||
{%- if f.get('estudio_id') %}
|
|
||||||
and p.estudio_id = '{{ f['estudio_id'] }}'
|
|
||||||
{%- endif %}
|
|
||||||
{%- if f['clase_de_linea'] in ['medicion', 'diagnostico', 'antecedente'] %}
|
|
||||||
and ({{ valor_codigo }} is not null or {{ valor_numerico }} is not null)
|
|
||||||
{%- endif %}
|
|
||||||
{%- endmacro %}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
{# A list of strings as an SQL list: ('a', 'b'). For rules from dbt vars, which are compiled in. #}
|
|
||||||
{% macro sql_list(valores) -%}
|
|
||||||
({% for v in valores %}'{{ v | replace("'", "''") }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
|
||||||
{%- endmacro %}
|
|
||||||
|
|
||||||
{# A text column without accents and in upper case, to compare by containment with rules written that way. The
|
|
||||||
accents go first: SQLite's `upper` only knows ASCII. #}
|
|
||||||
{% macro sin_acentos_mayusculas(columna) -%}
|
|
||||||
{%- set pares = [('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),('Ü','U'),
|
|
||||||
('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u')] -%}
|
|
||||||
upper({% for _ in pares %}replace({% endfor %}{{ columna }}{% for con, sin in pares %}, '{{ con }}', '{{ sin }}'){% endfor %})
|
|
||||||
{%- endmacro %}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
# Silver, the same tables in every domain: each domain has its own database, chosen by the profile
|
|
||||||
# (`--profile cacu|cama|tea`). Written by the Python load; dbt only reads them.
|
|
||||||
sources:
|
|
||||||
- name: silver
|
|
||||||
schema: "{{ target.schema }}"
|
|
||||||
tables:
|
|
||||||
- name: procedimiento
|
|
||||||
- name: observacion_clinica
|
|
||||||
- name: persona
|
|
||||||
- name: carga
|
|
||||||
- name: cat_estudio
|
|
||||||
- name: cat_resultado
|
|
||||||
- name: cat_valor
|
|
||||||
- name: dim_fecha
|
|
||||||
|
|
||||||
# Restricted gold the Python cycle writes: the cohort builds and the risk estimates scored on them. dbt only reads
|
|
||||||
# them, like silver.
|
|
||||||
- name: oro
|
|
||||||
schema: "{{ target.schema }}"
|
|
||||||
tables:
|
|
||||||
- name: cohorte_armado
|
|
||||||
- name: cohorte_miembro
|
|
||||||
- name: evaluacion_riesgo_lote
|
|
||||||
- name: evaluacion_riesgo
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
# The surveillance cohort, one query per rule. Each is compiled, not created: `models cohorts build` reads the compiled
|
|
||||||
# SQL from the manifest and chains the rules in `order`. A new exclusion is one query and one entry here; it returns the
|
|
||||||
# `pac_id` of everyone it flags and reads only the index date and the data, never another exclusion, so the study
|
|
||||||
# population doesn't depend on the order. `order` only says which rule is charged for a patient several flag.
|
|
||||||
# Parameters: the `surveillance_cohort` var in dbt_project.yml.
|
|
||||||
models:
|
|
||||||
- name: cacu_surveillance_all_patients
|
|
||||||
description: Every patient of the domain.
|
|
||||||
config:
|
|
||||||
materialized: ephemeral
|
|
||||||
meta:
|
|
||||||
cohort: cacu/cohorte_vigilancia
|
|
||||||
kind: population
|
|
||||||
cutoff: "{{ var('surveillance_cohort')['cutoff'] }}"
|
|
||||||
parameters: "{{ var('surveillance_cohort') | tojson }}"
|
|
||||||
- name: cacu_surveillance_index_date
|
|
||||||
description: First cytology in the patient's history, if it falls in the recruitment window. Sets the index date.
|
|
||||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: index}}
|
|
||||||
- name: cacu_surveillance_excl_prior_event
|
|
||||||
description: Biopsy with the outcome before the index date, so not at risk of a first event.
|
|
||||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: exclusion, name: prior_event, order: 1}}
|
|
||||||
- name: cacu_surveillance_excl_no_index_result
|
|
||||||
description: The index cytology has neither a cytology nor an HPV result, so there are no predictors.
|
|
||||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: exclusion, name: no_index_result, order: 2}}
|
|
||||||
|
|
||||||
unit_tests:
|
|
||||||
- name: prior_event_flags_an_earlier_biopsy_with_the_outcome
|
|
||||||
description: >
|
|
||||||
Pins down: patient 1 has a biopsy with the outcome before the index date. Patient 2's is on the index date, patient
|
|
||||||
3's has no outcome and patient 4's is a cytology, so none of them is flagged. Fails if the date comparison, the
|
|
||||||
grades or the event type change.
|
|
||||||
model: cacu_surveillance_excl_prior_event
|
|
||||||
overrides:
|
|
||||||
vars:
|
|
||||||
surveillance_cohort: {recruitment_start: "2024-01-01", recruitment_end: "2027-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"]}
|
|
||||||
given:
|
|
||||||
- input: ref('cacu_surveillance_index_date')
|
|
||||||
format: sql
|
|
||||||
rows: |
|
|
||||||
select 1 as pac_id, '2025-01-01' as fecha_indice union all select 2, '2025-01-01'
|
|
||||||
union all select 3, '2025-01-01' union all select 4, '2025-01-01'
|
|
||||||
- input: ref('cacu_linea_de_tiempo')
|
|
||||||
format: sql
|
|
||||||
rows: |
|
|
||||||
select 1 as pac_id, '2024-06-01' as fecha, 'biopsia' as tipo, 'LIEAG' as valor_codigo
|
|
||||||
union all select 2, '2025-01-01', 'biopsia', 'LIEAG'
|
|
||||||
union all select 3, '2024-06-01', 'biopsia', 'NORMAL'
|
|
||||||
union all select 4, '2024-06-01', 'bethesda', 'LIEAG'
|
|
||||||
expect:
|
|
||||||
rows:
|
|
||||||
- {pac_id: 1}
|
|
||||||
- name: no_index_result_ignores_results_of_other_cytologies
|
|
||||||
description: >
|
|
||||||
Pins down: patient 1 has a result on its index cytology and patient 2 has an HPV result there, so neither is
|
|
||||||
flagged. Patient 3's only result belongs to another cytology and patient 4's has no value, so both are. Fails if the
|
|
||||||
rule stops matching the index cytology or counts an empty result.
|
|
||||||
model: cacu_surveillance_excl_no_index_result
|
|
||||||
overrides:
|
|
||||||
vars:
|
|
||||||
surveillance_cohort: {recruitment_start: "2024-01-01", recruitment_end: "2027-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"]}
|
|
||||||
given:
|
|
||||||
- input: ref('cacu_surveillance_index_date')
|
|
||||||
format: sql
|
|
||||||
rows: |
|
|
||||||
select 1 as pac_id, 'citologiacervical' as indice_fuente_tabla, 'a' as indice_fuente_id
|
|
||||||
union all select 2, 'citologiacervical', 'b' union all select 3, 'citologiacervical', 'c'
|
|
||||||
union all select 4, 'citologiacervical', 'd'
|
|
||||||
- input: ref('cacu_linea_de_tiempo')
|
|
||||||
format: sql
|
|
||||||
rows: |
|
|
||||||
select 1 as pac_id, 'bethesda' as tipo, 'citologiacervical' as fuente_tabla, 'a' as fuente_id, '2025-01-01' as fecha, 'NORMAL' as valor_codigo
|
|
||||||
union all select 2, 'vph', 'citologiacervical', 'b', '2025-01-01', 'POSITIVO'
|
|
||||||
union all select 3, 'bethesda', 'citologiacervical', 'other', '2025-01-01', 'NORMAL'
|
|
||||||
union all select 4, 'bethesda', 'citologiacervical', 'd', '2025-01-01', null
|
|
||||||
expect:
|
|
||||||
rows:
|
|
||||||
- {pac_id: 3}
|
|
||||||
- {pac_id: 4}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
|
||||||
select pac_id
|
|
||||||
from {{ source('silver', 'persona') }}
|
|
||||||
-14
@@ -1,14 +0,0 @@
|
|||||||
{# Candidates whose index cytology has neither a cytology result nor an HPV result. #}
|
|
||||||
{% set p = var('surveillance_cohort') %}
|
|
||||||
select c.pac_id
|
|
||||||
from {{ ref('cacu_surveillance_index_date') }} as c
|
|
||||||
where not exists (
|
|
||||||
select 1
|
|
||||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
|
||||||
where e.pac_id = c.pac_id
|
|
||||||
and e.tipo in ('bethesda', 'vph')
|
|
||||||
and e.fuente_tabla = c.indice_fuente_tabla
|
|
||||||
and e.fuente_id = c.indice_fuente_id
|
|
||||||
and e.fecha <= '{{ p.cutoff }}'
|
|
||||||
and e.valor_codigo is not null
|
|
||||||
)
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
{# Candidates with a biopsy showing the outcome before their index date. #}
|
|
||||||
{% set p = var('surveillance_cohort') %}
|
|
||||||
select distinct c.pac_id
|
|
||||||
from {{ ref('cacu_surveillance_index_date') }} as c
|
|
||||||
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
|
|
||||||
where e.tipo = 'biopsia'
|
|
||||||
and e.fecha < c.fecha_indice
|
|
||||||
and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
{# The patient's first cytology up to the cut-off, if it falls in the recruitment window. #}
|
|
||||||
{% set p = var('surveillance_cohort') %}
|
|
||||||
with cytologies as (
|
|
||||||
select
|
|
||||||
pac_id, fecha, fuente_tabla, fuente_id,
|
|
||||||
row_number() over (partition by pac_id order by fecha, fuente_id) as position
|
|
||||||
from {{ ref('cacu_linea_de_tiempo') }}
|
|
||||||
where tipo = 'citologia' and fecha <= '{{ p.cutoff }}'
|
|
||||||
)
|
|
||||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
|
|
||||||
from cytologies
|
|
||||||
where position = 1 and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
-- One row per member of the surveillance cohort build that the current batch of risk estimates scored, with her
|
|
||||||
-- index date and the probability of her estimate in force, null if she has none. The current batch is the latest one
|
|
||||||
-- of the cohort with some estimate in force; an estimate is in force when its latest version, at the horizon
|
|
||||||
-- `riesgos_horizonte_banda`, is `final` (a later `entered-in-error` version voids it). When a member and an estimate
|
|
||||||
-- became known: the build's and the estimate's registration.
|
|
||||||
|
|
||||||
with recientes as (
|
|
||||||
select
|
|
||||||
e.lote_id,
|
|
||||||
e.pac_id,
|
|
||||||
e.probabilidad,
|
|
||||||
e.estado,
|
|
||||||
e.registrado_en,
|
|
||||||
row_number() over (partition by e.lote_id, e.pac_id order by e.version desc) as lugar
|
|
||||||
from {{ source('oro', 'evaluacion_riesgo') }} e
|
|
||||||
where e.horizonte_anios = {{ var('riesgos_horizonte_banda') }}
|
|
||||||
),
|
|
||||||
|
|
||||||
vigentes as (
|
|
||||||
select lote_id, pac_id, probabilidad, registrado_en from recientes where lugar = 1 and estado = 'final'
|
|
||||||
),
|
|
||||||
|
|
||||||
lote_vigente as (
|
|
||||||
select max(l.lote_id) as lote_id
|
|
||||||
from {{ source('oro', 'evaluacion_riesgo_lote') }} l
|
|
||||||
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
|
|
||||||
where a.url = 'cacu/cohorte_vigilancia'
|
|
||||||
and l.lote_id in (select lote_id from vigentes)
|
|
||||||
)
|
|
||||||
|
|
||||||
select
|
|
||||||
m.pac_id,
|
|
||||||
m.fecha_indice,
|
|
||||||
a.armado_en as miembro_conocido_en,
|
|
||||||
v.probabilidad,
|
|
||||||
v.registrado_en as evaluacion_conocida_en
|
|
||||||
from lote_vigente lv
|
|
||||||
join {{ source('oro', 'evaluacion_riesgo_lote') }} l on l.lote_id = lv.lote_id
|
|
||||||
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
|
|
||||||
join {{ source('oro', 'cohorte_miembro') }} m on m.armado_id = l.armado_id
|
|
||||||
left join vigentes v on v.lote_id = lv.lote_id and v.pac_id = m.pac_id
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cacu_riesgo_vigilancia
|
|
||||||
description: "Las miembros de la cohorte de vigilancia que puntuó el lote de riesgos vigente, con su probabilidad."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
|
|
||||||
semantic_models:
|
|
||||||
- name: cacu_riesgo_vigilancia
|
|
||||||
description: "Surveillance cohort members scored by the current batch of risk estimates: the band summary's grain."
|
|
||||||
model: ref('cacu_riesgo_vigilancia')
|
|
||||||
defaults:
|
|
||||||
agg_time_dimension: fecha_indice
|
|
||||||
entities:
|
|
||||||
- name: miembro
|
|
||||||
type: primary
|
|
||||||
expr: pac_id
|
|
||||||
dimensions:
|
|
||||||
- name: fecha_indice
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: miembro_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: evaluacion_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: probabilidad
|
|
||||||
type: categorical
|
|
||||||
measures:
|
|
||||||
- name: miembros
|
|
||||||
description: "Distinct members: each patient once."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: pac_id
|
|
||||||
|
|
||||||
metrics:
|
|
||||||
- name: cacu_riesgo_banda
|
|
||||||
label: "Pacientes en vigilancia por banda de riesgo de CIN2+"
|
|
||||||
description: >-
|
|
||||||
Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo
|
|
||||||
estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene
|
|
||||||
evaluación confirmada en ese lote.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: miembros
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/CACU_RIESGO_BANDA
|
|
||||||
version: 0.1.0
|
|
||||||
scoring: composition
|
|
||||||
basis: paciente
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C2
|
|
||||||
tipos_periodo: [semestre]
|
|
||||||
poblaciones_fhir: [measure-observation]
|
|
||||||
conocida_en: [miembro_conocido_en]
|
|
||||||
parametros:
|
|
||||||
corte_intermedio: comun.riesgos.corte_intermedio
|
|
||||||
corte_alto: comun.riesgos.corte_alto
|
|
||||||
# One row per member, so nothing to choose between; the category is her probability's band, by rules of the
|
|
||||||
# question: below `corte_intermedio` BAJO, below `corte_alto` INTERMEDIO, else ALTO.
|
|
||||||
categoria:
|
|
||||||
valor: probabilidad
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: ultimo_valido
|
|
||||||
valido: "{% raw %}{{ Dimension('miembro__probabilidad') }} is not null{% endraw %}"
|
|
||||||
conocida_en: [evaluacion_conocida_en]
|
|
||||||
orden: [fecha_indice]
|
|
||||||
bandas:
|
|
||||||
- {valor: BAJO, menor_que: corte_intermedio}
|
|
||||||
- {valor: INTERMEDIO, menor_que: corte_alto}
|
|
||||||
- {valor: ALTO}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
-- One row per cytology taken and each biopsy report it led to (one row with nulls when it led to none): the event
|
|
||||||
-- grain of the measures that follow a sample to its biopsy. When the sample and the report became known are the
|
|
||||||
-- start of the loads that wrote them. The birth date is the patient's, for strata by age. The sample's own result
|
|
||||||
-- (with its quality and when it was known) lets a measure pick a patient's last valid sample, and `biopsia_gravedad`
|
|
||||||
-- orders her biopsies from least to most severe by `catalogo_biopsia`: 0 for a grade the catalog doesn't know, -1 for
|
|
||||||
-- a report without one.
|
|
||||||
|
|
||||||
select
|
|
||||||
c.procedimiento_id,
|
|
||||||
c.fuente_id,
|
|
||||||
c.pac_id,
|
|
||||||
c.fecha_toma,
|
|
||||||
toma.inicio as toma_conocida_en,
|
|
||||||
c.resultado,
|
|
||||||
c.calidad_muestra,
|
|
||||||
c.fecha_reporte as citologia_fecha_reporte,
|
|
||||||
resultado.inicio as resultado_conocido_en,
|
|
||||||
b.fuente_id as biopsia_fuente_id,
|
|
||||||
b.fecha_reporte as biopsia_fecha_reporte,
|
|
||||||
b.grado as biopsia_grado,
|
|
||||||
case
|
|
||||||
when b.procedimiento_id is null then null
|
|
||||||
when b.grado is null then -1
|
|
||||||
{%- for grado in var('catalogo_biopsia') %}
|
|
||||||
when b.grado = '{{ grado }}' then {{ loop.index }}
|
|
||||||
{%- endfor %}
|
|
||||||
else 0
|
|
||||||
end as biopsia_gravedad,
|
|
||||||
reporte.inicio as biopsia_conocida_en,
|
|
||||||
persona.fecha_nacimiento
|
|
||||||
from {{ ref('cacu_citologias') }} c
|
|
||||||
join {{ source('silver', 'carga') }} toma
|
|
||||||
on toma.carga_id = c.toma_carga_id
|
|
||||||
join {{ source('silver', 'persona') }} persona
|
|
||||||
on persona.pac_id = c.pac_id
|
|
||||||
left join {{ source('silver', 'carga') }} resultado
|
|
||||||
on resultado.carga_id = c.resultado_carga_id and c.resultado is not null
|
|
||||||
left join {{ ref('cacu_biopsias') }} b
|
|
||||||
on b.toma_id = c.procedimiento_id and b.pac_id = c.pac_id
|
|
||||||
left join {{ source('silver', 'carga') }} reporte
|
|
||||||
on reporte.carga_id = b.reporte_carga_id
|
|
||||||
@@ -1,180 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cacu_tomas_biopsia
|
|
||||||
description: "Citologías tomadas y los reportes de biopsia que originaron, con cuándo se supo de cada uno."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
|
|
||||||
semantic_models:
|
|
||||||
- name: cacu_tomas_biopsia
|
|
||||||
description: "Cytologies taken and the biopsy reports they led to: what CaCu's detection measures count over."
|
|
||||||
model: ref('cacu_tomas_biopsia')
|
|
||||||
defaults:
|
|
||||||
agg_time_dimension: fecha_toma
|
|
||||||
entities:
|
|
||||||
- name: toma_biopsia
|
|
||||||
type: primary
|
|
||||||
expr: "procedimiento_id || '-' || coalesce(biopsia_fecha_reporte, '')"
|
|
||||||
- name: paciente
|
|
||||||
type: foreign
|
|
||||||
expr: pac_id
|
|
||||||
dimensions:
|
|
||||||
- name: fecha_toma
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: toma_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: biopsia_fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: biopsia_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: fecha_nacimiento
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: biopsia_grado
|
|
||||||
type: categorical
|
|
||||||
- name: fuente_id
|
|
||||||
type: categorical
|
|
||||||
- name: resultado
|
|
||||||
type: categorical
|
|
||||||
- name: calidad_muestra
|
|
||||||
type: categorical
|
|
||||||
- name: citologia_fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: resultado_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: biopsia_fuente_id
|
|
||||||
type: categorical
|
|
||||||
- name: biopsia_gravedad
|
|
||||||
type: categorical
|
|
||||||
measures:
|
|
||||||
- name: pacientes_tamizadas
|
|
||||||
description: "Distinct patients: each counts once per period, however many samples or biopsies."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: pac_id
|
|
||||||
|
|
||||||
metrics:
|
|
||||||
- name: cacu_eu13_denominador
|
|
||||||
label: "EU13: pacientes tamizadas"
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_tamizadas
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
poblaciones_fhir: [initial-population, denominator]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
- name: cacu_eu13_numerador
|
|
||||||
label: "EU13: de ellas, con lesión confirmada por biopsia"
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_tamizadas
|
|
||||||
filter: "{{ Dimension('toma_biopsia__biopsia_grado') }} in :deteccion_grados"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
poblaciones_fhir: [numerator]
|
|
||||||
# The biopsy counts in its sample's period, if it was reported by the event cut-off.
|
|
||||||
fechada_en: [biopsia_fecha_reporte]
|
|
||||||
conocida_en: [toma_conocida_en, biopsia_conocida_en]
|
|
||||||
- name: cacu_eu13
|
|
||||||
label: "Tasa de detección histopatológica"
|
|
||||||
description: >-
|
|
||||||
De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3),
|
|
||||||
carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.
|
|
||||||
type: ratio
|
|
||||||
type_params:
|
|
||||||
numerator: cacu_eu13_numerador
|
|
||||||
denominator: cacu_eu13_denominador
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/CACU_EU13
|
|
||||||
version: 0.3.2
|
|
||||||
scoring: proportion
|
|
||||||
basis: paciente
|
|
||||||
grupo: principal
|
|
||||||
contrato: C1
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
parametros:
|
|
||||||
deteccion_grados: cacu.deteccion_grados
|
|
||||||
estratos:
|
|
||||||
# Age at the start of the period asked: it depends on the question, so it can't be a column of the model.
|
|
||||||
grupo_edad:
|
|
||||||
tipo: edad_al_inicio_del_periodo
|
|
||||||
nacimiento: fecha_nacimiento
|
|
||||||
# ASCCP follow-up status before the period's start: what the patient's timeline held by then (the
|
|
||||||
# procedures cacu_procedimientos_inferidos adds to it). The first value that holds wins. INFO_INSUFICIENTE,
|
|
||||||
# third in precedence, needs an enrolment date silver doesn't have yet, so today it's only the rest.
|
|
||||||
estatus_seguimiento:
|
|
||||||
tipo: linea_de_tiempo_al_inicio_del_periodo
|
|
||||||
etiqueta: Estatus de seguimiento
|
|
||||||
linea: cacu_linea_de_tiempo
|
|
||||||
valores:
|
|
||||||
- {valor: POST_TRATAMIENTO, si: [{tratamiento: true}]}
|
|
||||||
- {valor: POST_COLPOSCOPIA, si: [{colposcopia: true}]}
|
|
||||||
# Under surveillance, or no cytology yet: every cytology with a known specialty outside surveillance
|
|
||||||
# takes her out.
|
|
||||||
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
|
|
||||||
resto: INFO_INSUFICIENTE
|
|
||||||
- name: cacu_confirmacion_citologia
|
|
||||||
label: "Tasa de confirmación histopatológica"
|
|
||||||
description: >-
|
|
||||||
De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto
|
|
||||||
grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por
|
|
||||||
resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un
|
|
||||||
grado mientras lleguen reportes.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_tamizadas
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/CACU_CONFIRMACION_CITOLOGIA
|
|
||||||
version: 0.1.2
|
|
||||||
scoring: composition
|
|
||||||
basis: paciente
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C2
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [measure-observation]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
parametros:
|
|
||||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
|
||||||
citologia_alto_grado: cacu.citologia_alto_grado
|
|
||||||
# Each patient's last valid sample of the period, as in CACU_EU7; she counts only if its result is high grade,
|
|
||||||
# and her category is the most severe biopsy that sample led to and that was reported by the cut-off (the
|
|
||||||
# latest, then the higher source id, among equals).
|
|
||||||
categoria:
|
|
||||||
valor: biopsia_grado
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: ultimo_valido
|
|
||||||
valido: >-
|
|
||||||
{% raw %}{{ Dimension('toma_biopsia__resultado') }} is not null and
|
|
||||||
({{ Dimension('toma_biopsia__calidad_muestra') }} is null
|
|
||||||
or {{ Dimension('toma_biopsia__calidad_muestra') }} <> :calidad_insatisfactoria){% endraw %}
|
|
||||||
fechada_en: [citologia_fecha_reporte]
|
|
||||||
conocida_en: [resultado_conocido_en]
|
|
||||||
orden: [fecha_toma, fuente_id]
|
|
||||||
admite: "{% raw %}{{ Dimension('toma_biopsia__resultado') }} in :citologia_alto_grado{% endraw %}"
|
|
||||||
seguimiento:
|
|
||||||
existe: biopsia_fecha_reporte
|
|
||||||
fechada_en: [biopsia_fecha_reporte]
|
|
||||||
conocida_en: [biopsia_conocida_en]
|
|
||||||
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
|
|
||||||
sin_seguimiento: SIN_BIOPSIA
|
|
||||||
estratos:
|
|
||||||
# The result of that same sample.
|
|
||||||
citologia_alto_grado:
|
|
||||||
tipo: del_elegido
|
|
||||||
etiqueta: Citología de alto grado
|
|
||||||
valor: resultado
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
-- One row per cytology taken: the event grain the measures are asked over. No period and no cut-off here: they're
|
|
||||||
-- the question's. Two knowledge dates, because the sample and its result arrive in different loads: when the sample
|
|
||||||
-- was known (`toma_conocida_en`) and when its result was (`resultado_conocido_en`, null without a result). The birth
|
|
||||||
-- date is the patient's, for strata by age. From her timeline: the first note that resolves the sample (a
|
|
||||||
-- `diagnostico` after it, within `horizonte_toma_diagnostico_dias`), with its days and when it was known, and whether
|
|
||||||
-- a cervical cancer note (`antecedente`) came before the sample.
|
|
||||||
|
|
||||||
with resuelve as (
|
|
||||||
select c.procedimiento_id, min(l.fecha) as fecha_diagnostico
|
|
||||||
from {{ ref('cacu_citologias') }} c
|
|
||||||
join {{ ref('cacu_linea_de_tiempo') }} l
|
|
||||||
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha > c.fecha_toma
|
|
||||||
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
|
|
||||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
|
|
||||||
where dl.dia_num - dt.dia_num < {{ var('horizonte_toma_diagnostico_dias') }}
|
|
||||||
group by c.procedimiento_id
|
|
||||||
),
|
|
||||||
|
|
||||||
-- When the first resolving note became known: the earliest load among her notes of that day.
|
|
||||||
diagnostico as (
|
|
||||||
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
|
|
||||||
from resuelve r
|
|
||||||
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = r.procedimiento_id
|
|
||||||
join {{ ref('cacu_linea_de_tiempo') }} l
|
|
||||||
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
|
|
||||||
group by r.procedimiento_id, r.fecha_diagnostico
|
|
||||||
),
|
|
||||||
|
|
||||||
primer_antecedente as (
|
|
||||||
select pac_id, min(fecha) as fecha
|
|
||||||
from {{ ref('cacu_linea_de_tiempo') }}
|
|
||||||
where tipo = 'antecedente'
|
|
||||||
group by pac_id
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
select
|
|
||||||
c.procedimiento_id,
|
|
||||||
c.fuente_id,
|
|
||||||
c.pac_id,
|
|
||||||
c.fecha_toma,
|
|
||||||
toma.inicio as toma_conocida_en,
|
|
||||||
c.calidad_muestra,
|
|
||||||
c.resultado,
|
|
||||||
c.fecha_reporte,
|
|
||||||
resultado.inicio as resultado_conocido_en,
|
|
||||||
persona.fecha_nacimiento,
|
|
||||||
dia_toma.dia_num as toma_dia,
|
|
||||||
dia_reporte.dia_num - dia_toma.dia_num as dias_toma_reporte,
|
|
||||||
dx.fecha_diagnostico,
|
|
||||||
dx.diagnostico_conocido_en,
|
|
||||||
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
|
|
||||||
case when antecedente.fecha < c.fecha_toma then 1 else 0 end as con_antecedente
|
|
||||||
from {{ ref('cacu_citologias') }} c
|
|
||||||
join {{ source('silver', 'persona') }} persona
|
|
||||||
on persona.pac_id = c.pac_id
|
|
||||||
join {{ source('silver', 'carga') }} toma
|
|
||||||
on toma.carga_id = c.toma_carga_id
|
|
||||||
left join {{ source('silver', 'carga') }} resultado
|
|
||||||
on resultado.carga_id = c.resultado_carga_id and c.resultado is not null
|
|
||||||
-- Days as differences of `dim_fecha.dia_num`: plain arithmetic, no engine date function.
|
|
||||||
left join {{ source('silver', 'dim_fecha') }} dia_toma
|
|
||||||
on dia_toma.fecha = c.fecha_toma
|
|
||||||
left join {{ source('silver', 'dim_fecha') }} dia_reporte
|
|
||||||
on dia_reporte.fecha = c.fecha_reporte
|
|
||||||
left join diagnostico dx
|
|
||||||
on dx.procedimiento_id = c.procedimiento_id
|
|
||||||
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
|
|
||||||
on dia_diagnostico.fecha = dx.fecha_diagnostico
|
|
||||||
left join primer_antecedente antecedente
|
|
||||||
on antecedente.pac_id = c.pac_id
|
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cacu_tomas_citologia
|
|
||||||
description: "Citologías tomadas, una fila por toma, con cuándo se supo de la toma y de su resultado."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
|
|
||||||
semantic_models:
|
|
||||||
- name: cacu_tomas_citologia
|
|
||||||
description: "Cytologies taken, one row each: what CaCu's cytology measures count over."
|
|
||||||
model: ref('cacu_tomas_citologia')
|
|
||||||
defaults:
|
|
||||||
agg_time_dimension: fecha_toma
|
|
||||||
entities:
|
|
||||||
- name: toma
|
|
||||||
type: primary
|
|
||||||
expr: procedimiento_id
|
|
||||||
- name: paciente
|
|
||||||
type: foreign
|
|
||||||
expr: pac_id
|
|
||||||
dimensions:
|
|
||||||
- name: fecha_toma
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: toma_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: resultado_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: fecha_nacimiento
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: resultado
|
|
||||||
type: categorical
|
|
||||||
- name: calidad_muestra
|
|
||||||
type: categorical
|
|
||||||
- name: fuente_id
|
|
||||||
type: categorical
|
|
||||||
- name: toma_dia
|
|
||||||
type: categorical
|
|
||||||
- name: dias_toma_reporte
|
|
||||||
type: categorical
|
|
||||||
- name: fecha_diagnostico
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: diagnostico_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: dias_toma_diagnostico
|
|
||||||
type: categorical
|
|
||||||
- name: con_antecedente
|
|
||||||
type: categorical
|
|
||||||
measures:
|
|
||||||
- name: citologias
|
|
||||||
description: "Distinct samples (the source's cytology id): the unit of the times from sample to result."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: fuente_id
|
|
||||||
- name: pacientes_con_toma
|
|
||||||
description: "Distinct patients: each counts once per period, however many samples."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: pac_id
|
|
||||||
|
|
||||||
metrics:
|
|
||||||
- name: cacu_ind1_denominador
|
|
||||||
label: "IND1: pacientes con citología tomada"
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_con_toma
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
poblaciones_fhir: [initial-population, denominator]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
- name: cacu_ind1_numerador
|
|
||||||
label: "IND1: de ellas, con algún resultado anómalo"
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_con_toma
|
|
||||||
filter: "{{ Dimension('toma__resultado') }} in :citologia_anomala"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
poblaciones_fhir: [numerator]
|
|
||||||
conocida_en: [toma_conocida_en, resultado_conocido_en]
|
|
||||||
- name: cacu_ind1
|
|
||||||
label: "Pacientes con citología anómala"
|
|
||||||
description: >-
|
|
||||||
Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG,
|
|
||||||
ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.
|
|
||||||
type: ratio
|
|
||||||
type_params:
|
|
||||||
numerator: cacu_ind1_numerador
|
|
||||||
denominator: cacu_ind1_denominador
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/IND1
|
|
||||||
version: 0.3.2
|
|
||||||
scoring: proportion
|
|
||||||
basis: paciente
|
|
||||||
grupo: principal
|
|
||||||
improvement_notation: decrease
|
|
||||||
contrato: C1
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
parametros:
|
|
||||||
citologia_anomala: cacu.citologia_anomala
|
|
||||||
- name: cacu_eu7
|
|
||||||
label: "Distribución de resultados citológicos"
|
|
||||||
description: >-
|
|
||||||
Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con
|
|
||||||
resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen
|
|
||||||
insatisfactoria a la fecha de corte.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_con_toma
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/CACU_EU7
|
|
||||||
version: 0.3.3
|
|
||||||
scoring: composition
|
|
||||||
basis: paciente
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C2
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [measure-observation]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
parametros:
|
|
||||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
|
||||||
# Each patient's category is the result of her last valid sample of the period asked: it depends on the
|
|
||||||
# question (the period, the cut-offs), so it's a rule of the answer, not a column of the model.
|
|
||||||
categoria:
|
|
||||||
valor: resultado
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: ultimo_valido
|
|
||||||
# `raw`: dbt renders Jinja in `meta`; the template is the answer's to render, like a metric's `filter`.
|
|
||||||
valido: >-
|
|
||||||
{% raw %}{{ Dimension('toma__resultado') }} is not null and ({{ Dimension('toma__calidad_muestra') }} is null
|
|
||||||
or {{ Dimension('toma__calidad_muestra') }} <> :calidad_insatisfactoria){% endraw %}
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [resultado_conocido_en]
|
|
||||||
orden: [fecha_toma, fuente_id]
|
|
||||||
estratos:
|
|
||||||
grupo_edad:
|
|
||||||
tipo: edad_al_inicio_del_periodo
|
|
||||||
nacimiento: fecha_nacimiento
|
|
||||||
# ASCCP follow-up status before the period's start: what the patient's timeline held by then (the
|
|
||||||
# procedures cacu_procedimientos_inferidos adds to it). The first value that holds wins. INFO_INSUFICIENTE,
|
|
||||||
# third in precedence, needs an enrolment date silver doesn't have yet, so today it's only the rest.
|
|
||||||
estatus_seguimiento:
|
|
||||||
tipo: linea_de_tiempo_al_inicio_del_periodo
|
|
||||||
etiqueta: Estatus de seguimiento
|
|
||||||
linea: cacu_linea_de_tiempo
|
|
||||||
valores:
|
|
||||||
- {valor: POST_TRATAMIENTO, si: [{tratamiento: true}]}
|
|
||||||
- {valor: POST_COLPOSCOPIA, si: [{colposcopia: true}]}
|
|
||||||
# Under surveillance, or no cytology yet: every cytology with a known specialty outside surveillance
|
|
||||||
# takes her out.
|
|
||||||
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
|
|
||||||
resto: INFO_INSUFICIENTE
|
|
||||||
- name: cacu_eu_tiempo_reporte
|
|
||||||
label: "Días de la toma de la citología a su resultado"
|
|
||||||
description: >-
|
|
||||||
Días naturales de la toma de cada citología del periodo a su resultado, a la fecha de corte. Las que aún no
|
|
||||||
tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los
|
|
||||||
excluidos.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: citologias
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/CACU_EU_TIEMPO_REPORTE
|
|
||||||
version: 0.2.1
|
|
||||||
scoring: continuous-variable
|
|
||||||
basis: examen
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C3r
|
|
||||||
improvement_notation: decrease
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [initial-population]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
parametros:
|
|
||||||
horizonte_dias: cacu.horizontes.toma_reporte_dias
|
|
||||||
# Each sample's number of days, if its result came by the event cut-off; a sample without one whose horizon
|
|
||||||
# hasn't passed by then isn't measured yet (it's left out of the initial population).
|
|
||||||
observacion:
|
|
||||||
valor: dias_toma_reporte
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [resultado_conocido_en]
|
|
||||||
horizonte:
|
|
||||||
regla: horizonte_dias
|
|
||||||
dia_inicio: toma_dia
|
|
||||||
- name: cacu_dias_toma_diagnostico
|
|
||||||
label: "Tiempo de tamizaje a diagnóstico"
|
|
||||||
description: >-
|
|
||||||
Días naturales de la toma de cada citología del periodo a la primera nota médica posterior que la resuelve: un
|
|
||||||
diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que
|
|
||||||
diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se
|
|
||||||
excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: citologias
|
|
||||||
filter: "{{ Dimension('toma__con_antecedente') }} = 0"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cacu/CACU_DIAS_TOMA_DIAGNOSTICO
|
|
||||||
version: 0.2.3
|
|
||||||
scoring: continuous-variable
|
|
||||||
basis: examen
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C3r
|
|
||||||
improvement_notation: decrease
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [initial-population]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
# The first resolving note's days, if it was written by the event cut-off; a sample without one whose
|
|
||||||
# horizon hasn't passed by then isn't measured yet. The horizon is the one the model used to find the note.
|
|
||||||
observacion:
|
|
||||||
valor: dias_toma_diagnostico
|
|
||||||
fechada_en: [fecha_diagnostico]
|
|
||||||
conocida_en: [diagnostico_conocido_en]
|
|
||||||
horizonte:
|
|
||||||
dias: "{{ var('horizonte_toma_diagnostico_dias') }}"
|
|
||||||
dia_inicio: toma_dia
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
/*
|
|
||||||
Una fila por biopsia REPORTE con su grado y el procedimiento_id de la toma
|
|
||||||
de citología que la originó (toma_id).
|
|
||||||
|
|
||||||
Jerarquía: toma_citologia → orden_biopsia → reporte_biopsia
|
|
||||||
- p_rep.padre_id = procedimiento_id de la orden biopsia
|
|
||||||
- p_ord.padre_id = procedimiento_id de la toma citología
|
|
||||||
|
|
||||||
padre_id es el padre_id del procedimiento en silver.
|
|
||||||
Equivalente dbt de plata.py::biopsias().
|
|
||||||
*/
|
|
||||||
|
|
||||||
SELECT
|
|
||||||
p_rep.procedimiento_id,
|
|
||||||
p_rep.fuente_tabla,
|
|
||||||
p_rep.fuente_id,
|
|
||||||
p_rep.pac_id,
|
|
||||||
p_rep.fecha AS fecha_reporte,
|
|
||||||
coalesce(o_grado.valor_id, o_grado.valor_fuente) AS grado,
|
|
||||||
p_ord.fecha AS fecha_solicitud,
|
|
||||||
p_ord.orden_numero,
|
|
||||||
p_toma.procedimiento_id AS toma_id,
|
|
||||||
p_toma.pac_id AS toma_pac_id,
|
|
||||||
p_toma.fecha AS fecha_toma,
|
|
||||||
coalesce(o_grado.carga_id, p_rep.carga_id) AS reporte_carga_id
|
|
||||||
FROM {{ source('silver', 'procedimiento') }} p_rep
|
|
||||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_grado
|
|
||||||
ON o_grado.procedimiento_id = p_rep.procedimiento_id
|
|
||||||
AND o_grado.resultado_id = 'biopsia.grado'
|
|
||||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_ord
|
|
||||||
ON p_ord.procedimiento_id = p_rep.padre_id
|
|
||||||
AND p_ord.estudio_id = 'biopsia'
|
|
||||||
AND p_ord.clase = 'orden'
|
|
||||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_toma
|
|
||||||
ON p_toma.procedimiento_id = p_ord.padre_id
|
|
||||||
AND p_toma.estudio_id = 'citologia'
|
|
||||||
AND p_toma.clase = 'toma'
|
|
||||||
WHERE p_rep.estudio_id = 'biopsia'
|
|
||||||
AND p_rep.clase = 'reporte'
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
/*
|
|
||||||
Una fila por citología TOMA con sus resultados (bethesda, VPH).
|
|
||||||
Los tres procedimientos (toma, reporte-citología, reporte-vph) comparten
|
|
||||||
fuente_id = cit_id porque los tres vienen de la misma fila de citologia_cervical.
|
|
||||||
|
|
||||||
Equivalente dbt de plata.py::citologias(). A code the catalog doesn't know comes as it arrived
|
|
||||||
(`coalesce(valor_id, valor_fuente)`), as the timeline reads it.
|
|
||||||
*/
|
|
||||||
|
|
||||||
SELECT
|
|
||||||
p_toma.procedimiento_id,
|
|
||||||
p_toma.fuente_tabla,
|
|
||||||
p_toma.fuente_id,
|
|
||||||
p_toma.pac_id,
|
|
||||||
p_toma.fecha AS fecha_toma,
|
|
||||||
p_toma.orden_numero,
|
|
||||||
coalesce(o_cal.valor_id, o_cal.valor_fuente) AS calidad_muestra,
|
|
||||||
coalesce(o_beth.valor_id, o_beth.valor_fuente) AS resultado,
|
|
||||||
p_rep.fecha AS fecha_reporte,
|
|
||||||
coalesce(o_vph.valor_id, o_vph.valor_fuente) AS vph,
|
|
||||||
o_vph_g.valor_numerico AS genotipo_16_18,
|
|
||||||
p_toma.carga_id AS toma_carga_id,
|
|
||||||
coalesce(o_beth.carga_id, p_rep.carga_id) AS resultado_carga_id
|
|
||||||
FROM {{ source('silver', 'procedimiento') }} p_toma
|
|
||||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_rep
|
|
||||||
ON p_rep.fuente_tabla = p_toma.fuente_tabla
|
|
||||||
AND p_rep.fuente_id = p_toma.fuente_id
|
|
||||||
AND p_rep.estudio_id = 'citologia'
|
|
||||||
AND p_rep.clase = 'reporte'
|
|
||||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_beth
|
|
||||||
ON o_beth.procedimiento_id = p_rep.procedimiento_id
|
|
||||||
AND o_beth.resultado_id = 'citologia.bethesda'
|
|
||||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_cal
|
|
||||||
ON o_cal.procedimiento_id = p_toma.procedimiento_id
|
|
||||||
AND o_cal.resultado_id = 'citologia.calidad_muestra'
|
|
||||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_vph
|
|
||||||
ON p_vph.fuente_tabla = p_toma.fuente_tabla
|
|
||||||
AND p_vph.fuente_id = p_toma.fuente_id
|
|
||||||
AND p_vph.estudio_id = 'vph'
|
|
||||||
AND p_vph.clase = 'reporte'
|
|
||||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_vph
|
|
||||||
ON o_vph.procedimiento_id = p_vph.procedimiento_id
|
|
||||||
AND o_vph.resultado_id = 'vph.resultado'
|
|
||||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_vph_g
|
|
||||||
ON o_vph_g.procedimiento_id = p_vph.procedimiento_id
|
|
||||||
AND o_vph_g.resultado_id = 'vph.genotipo_16_18'
|
|
||||||
WHERE p_toma.estudio_id = 'citologia'
|
|
||||||
AND p_toma.clase = 'toma'
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cacu_linea_de_tiempo.yml;
|
|
||||||
the procedures silver doesn't hold but its facts imply (colposcopy, treatment): cacu_procedimientos_inferidos. #}
|
|
||||||
{{ config(materialized = 'view') }}
|
|
||||||
|
|
||||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
|
|
||||||
from {{ ref('cacu_procedimientos_inferidos') }}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cacu_linea_de_tiempo
|
|
||||||
description: >
|
|
||||||
Each patient's timeline: every fact of silver (procedimiento ⟕ observacion_clinica) in one shape and
|
|
||||||
in order. One source per kind of fact: study, procedure class and result, with what the timeline calls
|
|
||||||
it (`clase_de_linea`, `tipo`, `codigo`) and where its value and date come from. Adding a kind of
|
|
||||||
observation is adding a source here.
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
# estudio_id (null: any study), clase, resultado_id (null: the value comes from `columna` of the
|
|
||||||
# procedure), clase_de_linea, tipo; optional: codigo (default: tipo), valor (codigo | numerico),
|
|
||||||
# columna, fecha (procedimiento | nacimiento), fecha_resultado (an observed date that goes first),
|
|
||||||
# del_padre (date and patient from the parent procedure).
|
|
||||||
fuentes:
|
|
||||||
- {estudio_id: "citologia", clase: "toma", resultado_id: "citologia.calidad_muestra", clase_de_linea: "procedimiento", tipo: "citologia", codigo: "citologia_cervical"}
|
|
||||||
- {estudio_id: "citologia", clase: "reporte", resultado_id: "citologia.bethesda", clase_de_linea: "medicion", tipo: "bethesda", codigo: "bethesda"}
|
|
||||||
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.resultado", clase_de_linea: "medicion", tipo: "vph", codigo: "vph"}
|
|
||||||
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.genotipo_16_18", clase_de_linea: "medicion", tipo: "vph_genotipo_16_18", valor: "numerico"}
|
|
||||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "cin"}
|
|
||||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
|
||||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
-- Una fila por nota médica (colposcopia / diagnostico / tratamiento) con sus observaciones
|
|
||||||
-- en columnas. Equivalente de cacu_citologias para el dominio de notas.
|
|
||||||
-- Fuente: procedimiento + observacion_clinica (silver); nunca bronze.
|
|
||||||
|
|
||||||
select
|
|
||||||
p.procedimiento_id,
|
|
||||||
p.fuente_id,
|
|
||||||
p.pac_id,
|
|
||||||
p.fecha,
|
|
||||||
p.estudio_id as tipo_nota, -- colposcopia | diagnostico | tratamiento
|
|
||||||
o_cie.valor_id as cie_codigo, -- ya normalizado en staging (sin espacios ni puntos)
|
|
||||||
o_esp.valor_id as especialidad
|
|
||||||
from {{ source('silver', 'procedimiento') }} p
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o_cie
|
|
||||||
on o_cie.procedimiento_id = p.procedimiento_id
|
|
||||||
and o_cie.resultado_id = 'nota_medica.diagnostico'
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o_esp
|
|
||||||
on o_esp.procedimiento_id = p.procedimiento_id
|
|
||||||
and o_esp.resultado_id = 'nota_medica.especialidad'
|
|
||||||
where p.fuente_tabla = 'notamedica'
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
{{ config(materialized = 'view') }}
|
|
||||||
-- The procedures the notes, orders and biopsies imply but silver doesn't hold as such, in the timeline's shape
|
|
||||||
-- (`cacu_linea_de_tiempo` adds them to each patient's timeline):
|
|
||||||
-- colposcopia a colposcopy: a colposcopy note (by its reason, its ICD-10 or its diagnosis text), a
|
|
||||||
-- biopsy order, or a reported biopsy
|
|
||||||
-- tratamiento a note with a treatment ICD-10 after the patient's first colposcopy
|
|
||||||
-- citologia_de_vigilancia a cytology whose order's specialty is unknown or one of the surveillance ones
|
|
||||||
-- diagnostico a note that can resolve a cytology: a diagnosis ICD-10 (`cie_diagnostico`) written by
|
|
||||||
-- a diagnosing specialty (`especialidades_diagnostico`)
|
|
||||||
-- antecedente a note with a cervical cancer ICD-10 (`cie_antecedente`), whoever wrote it
|
|
||||||
-- Every rule is a dbt var (`seguimiento`, and the diagnosis rules shared with CACU_DIAS_TOMA_DIAGNOSTICO), so
|
|
||||||
-- changing one is recompiling, not reloading.
|
|
||||||
{% set s = var('seguimiento') %}
|
|
||||||
|
|
||||||
with nota as (
|
|
||||||
select
|
|
||||||
p.pac_id,
|
|
||||||
p.fecha,
|
|
||||||
p.fuente_tabla,
|
|
||||||
p.fuente_id,
|
|
||||||
c.inicio as conocida_en,
|
|
||||||
max(case when o.resultado_id = 'nota_medica.diagnostico' then o.valor_texto end) as cie_codigo,
|
|
||||||
max(case when o.resultado_id = 'nota_medica.especialidad' then o.valor_id end) as especialidad,
|
|
||||||
max(case when o.resultado_id = 'nota_medica.motivo' then o.valor_texto end) as motivo,
|
|
||||||
max(case when o.resultado_id = 'nota_medica.diagnostico_texto' then o.valor_texto end) as diagnostico_texto
|
|
||||||
from {{ source('silver', 'procedimiento') }} p
|
|
||||||
join {{ source('silver', 'carga') }} c on c.carga_id = p.carga_id
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o on o.procedimiento_id = p.procedimiento_id
|
|
||||||
where p.estudio_id = 'nota_medica' and p.clase = 'encuentro'
|
|
||||||
group by p.procedimiento_id, p.pac_id, p.fecha, p.fuente_tabla, p.fuente_id, c.inicio
|
|
||||||
),
|
|
||||||
|
|
||||||
toma as (
|
|
||||||
select t.pac_id, t.fecha, t.fuente_tabla, t.fuente_id, c.inicio as conocida_en, o.valor_id as especialidad
|
|
||||||
from {{ source('silver', 'procedimiento') }} t
|
|
||||||
join {{ source('silver', 'carga') }} c on c.carga_id = t.carga_id
|
|
||||||
left join {{ source('silver', 'procedimiento') }} orden
|
|
||||||
on orden.procedimiento_id = t.padre_id and orden.estudio_id = 'citologia' and orden.clase = 'orden'
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o
|
|
||||||
on o.procedimiento_id = orden.procedimiento_id and o.resultado_id = 'orden.especialidad'
|
|
||||||
where t.estudio_id = 'citologia' and t.clase = 'toma'
|
|
||||||
),
|
|
||||||
|
|
||||||
diagnostico as (
|
|
||||||
select * from nota
|
|
||||||
where cie_codigo in {{ sql_list(var('cie_diagnostico')) }}
|
|
||||||
and especialidad in {{ sql_list(var('especialidades_diagnostico')) }}
|
|
||||||
),
|
|
||||||
|
|
||||||
-- The valuation visit: the first diagnosis that resolves one of her cytologies, after it and within the horizon,
|
|
||||||
-- as CACU_DIAS_TOMA_DIAGNOSTICO reads it. Days are differences of `dim_fecha.dia_num`.
|
|
||||||
valoracion as (
|
|
||||||
select n.pac_id, min(n.fecha) as primera
|
|
||||||
from diagnostico n
|
|
||||||
join toma t on t.pac_id = n.pac_id
|
|
||||||
join {{ source('silver', 'dim_fecha') }} dn on dn.fecha = n.fecha
|
|
||||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = t.fecha
|
|
||||||
where n.fecha > t.fecha
|
|
||||||
and dn.dia_num - dt.dia_num < {{ var('horizonte_toma_diagnostico_dias') }}
|
|
||||||
group by n.pac_id
|
|
||||||
),
|
|
||||||
|
|
||||||
-- A colposcopy note: of a colposcopy specialty and, by rule, after the first valuation visit.
|
|
||||||
nota_de_colposcopia as (
|
|
||||||
select n.*
|
|
||||||
from nota n
|
|
||||||
{% if s['colposcopia_requisito'] == 'valoracion_previa' %}
|
|
||||||
join valoracion v on v.pac_id = n.pac_id and n.fecha > v.primera
|
|
||||||
{% endif %}
|
|
||||||
where n.especialidad in {{ sql_list(s['colposcopia_especialidades']) }}
|
|
||||||
),
|
|
||||||
|
|
||||||
-- What counts as a colposcopy. A biopsy order, and a reported biopsy's request, count by rule only on the day of a
|
|
||||||
-- colposcopy note: the colposcopy is the biopsy's parent.
|
|
||||||
colposcopia as (
|
|
||||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia where 1 = 0
|
|
||||||
{% if 'motivo' in s['colposcopia_evidencias'] %}{% for m in s['colposcopia_motivos'] %}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia where {{ sin_acentos_mayusculas('motivo') }} like '%{{ m }}%'
|
|
||||||
{% endfor %}{% endif %}
|
|
||||||
{% if 'cie' in s['colposcopia_evidencias'] %}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia where cie_codigo in {{ sql_list(s['colposcopia_cie']) }}
|
|
||||||
{% endif %}
|
|
||||||
{% if 'diagnostico_texto' in s['colposcopia_evidencias'] %}{% for d in s['colposcopia_diagnosticos'] %}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia
|
|
||||||
where {{ sin_acentos_mayusculas('diagnostico_texto') }} like '%{{ d }}%'
|
|
||||||
{% endfor %}{% endif %}
|
|
||||||
{% if 'orden_biopsia' in s['colposcopia_evidencias'] %}
|
|
||||||
union all
|
|
||||||
select o.pac_id, o.fecha, c.inicio, o.fuente_tabla, o.fuente_id
|
|
||||||
from {{ source('silver', 'procedimiento') }} o
|
|
||||||
join {{ source('silver', 'carga') }} c on c.carga_id = o.carga_id
|
|
||||||
where o.estudio_id = 'biopsia' and o.clase = 'orden'
|
|
||||||
{% if s['biopsia_requisito'] == 'mismo_dia_que_colposcopia' %}
|
|
||||||
and exists (select 1 from nota_de_colposcopia v where v.pac_id = o.pac_id and v.fecha = o.fecha)
|
|
||||||
{% endif %}
|
|
||||||
{% endif %}
|
|
||||||
{% if 'biopsia' in s['colposcopia_evidencias'] %}
|
|
||||||
union all
|
|
||||||
select b.pac_id, b.fecha_reporte, c.inicio, b.fuente_tabla, b.fuente_id
|
|
||||||
from {{ ref('cacu_biopsias') }} b
|
|
||||||
join {{ source('silver', 'carga') }} c on c.carga_id = b.reporte_carga_id
|
|
||||||
where 1 = 1
|
|
||||||
{% if s['biopsia_requisito'] == 'mismo_dia_que_colposcopia' %}
|
|
||||||
and exists (select 1 from nota_de_colposcopia v where v.pac_id = b.pac_id and v.fecha = b.fecha_solicitud)
|
|
||||||
{% endif %}
|
|
||||||
{% endif %}
|
|
||||||
),
|
|
||||||
|
|
||||||
primera_colposcopia as (
|
|
||||||
select pac_id, min(fecha) as primera from colposcopia group by pac_id
|
|
||||||
),
|
|
||||||
|
|
||||||
inferidos as (
|
|
||||||
select pac_id, fecha, conocida_en, 'colposcopia' as tipo, fuente_tabla, fuente_id from colposcopia
|
|
||||||
union all
|
|
||||||
select n.pac_id, n.fecha, n.conocida_en, 'tratamiento', n.fuente_tabla, n.fuente_id
|
|
||||||
from nota n
|
|
||||||
join primera_colposcopia pc on pc.pac_id = n.pac_id and n.fecha > pc.primera
|
|
||||||
where n.cie_codigo in {{ sql_list(s['tratamiento_cie']) }}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, 'diagnostico', fuente_tabla, fuente_id from diagnostico
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, 'antecedente', fuente_tabla, fuente_id from nota
|
|
||||||
where cie_codigo in {{ sql_list(var('cie_antecedente')) }}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, 'citologia_de_vigilancia', fuente_tabla, fuente_id from toma
|
|
||||||
where especialidad is null or especialidad in {{ sql_list(s['vigilancia_especialidades']) }}
|
|
||||||
)
|
|
||||||
|
|
||||||
select
|
|
||||||
pac_id,
|
|
||||||
fecha,
|
|
||||||
conocida_en,
|
|
||||||
{{ as_text("'procedimiento'") }} as clase,
|
|
||||||
{{ as_text('tipo') }} as tipo,
|
|
||||||
{{ as_text('tipo') }} as codigo,
|
|
||||||
{{ as_text('null') }} as valor_codigo,
|
|
||||||
cast(null as {{ dbt.type_float() }}) as valor_numerico,
|
|
||||||
fuente_tabla,
|
|
||||||
fuente_id
|
|
||||||
from inferidos
|
|
||||||
where fecha is not null
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
-- One row per biopsy report, dated by the report: what CaMa's biopsy distribution counts. Its grade as it arrived;
|
|
||||||
-- when it became known, the start of the load that wrote it.
|
|
||||||
|
|
||||||
select
|
|
||||||
b.procedimiento_id,
|
|
||||||
b.fuente_id,
|
|
||||||
b.pac_id,
|
|
||||||
b.fecha_reporte,
|
|
||||||
b.grado,
|
|
||||||
c.inicio as reporte_conocido_en
|
|
||||||
from {{ ref('cama_biopsias') }} b
|
|
||||||
join {{ source('silver', 'carga') }} c
|
|
||||||
on c.carga_id = b.reporte_carga_id
|
|
||||||
where b.fecha_reporte is not null
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cama_reportes_biopsia
|
|
||||||
description: "Reportes de biopsia de mama, uno por fila, fechados por el reporte."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
|
|
||||||
semantic_models:
|
|
||||||
- name: cama_reportes_biopsia
|
|
||||||
description: "Breast biopsy reports, dated by the report: what CaMa's biopsy distribution counts."
|
|
||||||
model: ref('cama_reportes_biopsia')
|
|
||||||
defaults:
|
|
||||||
agg_time_dimension: fecha_reporte
|
|
||||||
entities:
|
|
||||||
- name: biopsia
|
|
||||||
type: primary
|
|
||||||
expr: procedimiento_id
|
|
||||||
- name: paciente
|
|
||||||
type: foreign
|
|
||||||
expr: pac_id
|
|
||||||
dimensions:
|
|
||||||
- name: fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: reporte_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: grado
|
|
||||||
type: categorical
|
|
||||||
- name: fuente_id
|
|
||||||
type: categorical
|
|
||||||
measures:
|
|
||||||
- name: biopsias
|
|
||||||
description: "Distinct biopsy reports: each biopsy counts, not each patient."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: fuente_id
|
|
||||||
|
|
||||||
metrics:
|
|
||||||
- name: cama_biopsias
|
|
||||||
label: "Distribución de resultados de biopsia"
|
|
||||||
description: >-
|
|
||||||
Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada
|
|
||||||
paciente. «Sin dato»: el reporte no trae grado.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: biopsias
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cama/CAMA_BIOPSIAS
|
|
||||||
version: 0.2.0
|
|
||||||
scoring: composition
|
|
||||||
basis: examen
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C2
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [measure-observation]
|
|
||||||
conocida_en: [reporte_conocido_en]
|
|
||||||
# One row per report: its grade.
|
|
||||||
categoria:
|
|
||||||
valor: grado
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: ultimo_valido
|
|
||||||
valido: "{% raw %}{{ Dimension('biopsia__grado') }} is not null{% endraw %}"
|
|
||||||
orden: [fecha_reporte]
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
-- One row per mammogram's report and each biopsy report it led to (one row with nulls when it led to none): the grain
|
|
||||||
-- of the measures that follow a suspicious mammogram to its biopsy. A biopsy counts for the mammogram that led to it,
|
|
||||||
-- of the same patient. When each became known: the start of the loads that wrote them.
|
|
||||||
|
|
||||||
select
|
|
||||||
m.procedimiento_id,
|
|
||||||
m.fuente_id,
|
|
||||||
m.pac_id,
|
|
||||||
m.fecha_toma,
|
|
||||||
toma.inicio as toma_conocida_en,
|
|
||||||
m.fecha_reporte,
|
|
||||||
m.birads,
|
|
||||||
reporte.inicio as reporte_conocido_en,
|
|
||||||
b.fecha_reporte as biopsia_fecha_reporte,
|
|
||||||
biopsia.inicio as biopsia_conocida_en
|
|
||||||
from {{ ref('cama_mastografias') }} m
|
|
||||||
join {{ source('silver', 'carga') }} toma
|
|
||||||
on toma.carga_id = m.toma_carga_id
|
|
||||||
left join {{ source('silver', 'carga') }} reporte
|
|
||||||
on reporte.carga_id = m.reporte_carga_id and m.reporte_id is not null
|
|
||||||
left join {{ ref('cama_biopsias') }} b
|
|
||||||
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
|
|
||||||
left join {{ source('silver', 'carga') }} biopsia
|
|
||||||
on biopsia.carga_id = b.reporte_carga_id
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cama_tomas_biopsia
|
|
||||||
description: "Mastografías con su reporte y los reportes de biopsia que originaron, con cuándo se supo de cada uno."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
|
|
||||||
semantic_models:
|
|
||||||
- name: cama_tomas_biopsia
|
|
||||||
description: "Mammograms and the biopsy reports they led to: the episode a suspicious mammogram opens."
|
|
||||||
model: ref('cama_tomas_biopsia')
|
|
||||||
defaults:
|
|
||||||
agg_time_dimension: fecha_toma
|
|
||||||
entities:
|
|
||||||
- name: episodio
|
|
||||||
type: primary
|
|
||||||
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '') || '-' || coalesce(biopsia_fecha_reporte, '')"
|
|
||||||
- name: paciente
|
|
||||||
type: foreign
|
|
||||||
expr: pac_id
|
|
||||||
dimensions:
|
|
||||||
- name: fecha_toma
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: toma_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: reporte_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: biopsia_fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: biopsia_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: birads
|
|
||||||
type: categorical
|
|
||||||
measures:
|
|
||||||
- name: episodios
|
|
||||||
description: "Distinct mammograms: an episode counts once, however many biopsies."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: fuente_id
|
|
||||||
|
|
||||||
metrics:
|
|
||||||
- name: cama_confirmacion_birads45_denominador
|
|
||||||
label: "Mastografías de sospecha"
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: episodios
|
|
||||||
filter: "{{ Dimension('episodio__birads') }} in :birads_sospecha"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
poblaciones_fhir: [initial-population, denominator]
|
|
||||||
# A BI-RADS reported after the cut-off doesn't exist yet.
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [toma_conocida_en, reporte_conocido_en]
|
|
||||||
- name: cama_confirmacion_birads45_numerador
|
|
||||||
label: "De ellas, con biopsia reportada"
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: episodios
|
|
||||||
filter: "{{ Dimension('episodio__birads') }} in :birads_sospecha"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
poblaciones_fhir: [numerator]
|
|
||||||
fechada_en: [fecha_reporte, biopsia_fecha_reporte]
|
|
||||||
conocida_en: [toma_conocida_en, reporte_conocido_en, biopsia_conocida_en]
|
|
||||||
- name: cama_confirmacion_birads45
|
|
||||||
# dbt wants labels unique in the project; the title on screen is `meta.titulo`.
|
|
||||||
label: "CaMa: tasa de confirmación histopatológica"
|
|
||||||
description: >-
|
|
||||||
De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa
|
|
||||||
mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si
|
|
||||||
la biopsia confirmó cáncer.
|
|
||||||
type: ratio
|
|
||||||
type_params:
|
|
||||||
numerator: cama_confirmacion_birads45_numerador
|
|
||||||
denominator: cama_confirmacion_birads45_denominador
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cama/CAMA_CONFIRMACION_BIRADS45
|
|
||||||
titulo: "Tasa de confirmación histopatológica"
|
|
||||||
version: 0.2.0
|
|
||||||
scoring: proportion
|
|
||||||
basis: episodio
|
|
||||||
grupo: principal
|
|
||||||
contrato: C1
|
|
||||||
improvement_notation: increase
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
parametros:
|
|
||||||
birads_sospecha: cama.birads_sospecha
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
-- One row per mammogram taken and each report that hangs from it: the event grain CaMa's mammography measures are
|
|
||||||
-- asked over. No period and no cut-off here: they're the question's. When the sample and its report became known are
|
|
||||||
-- the start of the loads that wrote them. `birads_gravedad` orders BI-RADS from least to most severe by
|
|
||||||
-- `cama.birads_gravedad` (0 for one the catalog doesn't know). From the patient's timeline: the first note that
|
|
||||||
-- resolves the mammogram (a `diagnostico` after it, within the horizon), with its days and when it was known, and
|
|
||||||
-- whether a breast cancer note (`antecedente`) came before it. Days are differences of `dim_fecha.dia_num`.
|
|
||||||
{% set r = var('cama') %}
|
|
||||||
|
|
||||||
with resuelve as (
|
|
||||||
select m.procedimiento_id, min(l.fecha) as fecha_diagnostico
|
|
||||||
from (select distinct procedimiento_id, pac_id, fecha_toma from {{ ref('cama_mastografias') }}) m
|
|
||||||
join {{ ref('cama_linea_de_tiempo') }} l
|
|
||||||
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha > m.fecha_toma
|
|
||||||
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
|
|
||||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = m.fecha_toma
|
|
||||||
where dl.dia_num - dt.dia_num < {{ r['horizonte_toma_diagnostico_dias'] }}
|
|
||||||
group by m.procedimiento_id
|
|
||||||
),
|
|
||||||
|
|
||||||
diagnostico as (
|
|
||||||
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
|
|
||||||
from resuelve r
|
|
||||||
join (select distinct procedimiento_id, pac_id from {{ ref('cama_mastografias') }}) m
|
|
||||||
on m.procedimiento_id = r.procedimiento_id
|
|
||||||
join {{ ref('cama_linea_de_tiempo') }} l
|
|
||||||
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
|
|
||||||
group by r.procedimiento_id, r.fecha_diagnostico
|
|
||||||
),
|
|
||||||
|
|
||||||
primer_antecedente as (
|
|
||||||
select pac_id, min(fecha) as fecha
|
|
||||||
from {{ ref('cama_linea_de_tiempo') }}
|
|
||||||
where tipo = 'antecedente'
|
|
||||||
group by pac_id
|
|
||||||
)
|
|
||||||
|
|
||||||
select
|
|
||||||
m.procedimiento_id,
|
|
||||||
m.fuente_id,
|
|
||||||
m.pac_id,
|
|
||||||
m.fecha_toma,
|
|
||||||
toma.inicio as toma_conocida_en,
|
|
||||||
m.calidad_imagen,
|
|
||||||
m.fecha_reporte,
|
|
||||||
m.birads,
|
|
||||||
case
|
|
||||||
{%- for b in r['birads_gravedad'] %}
|
|
||||||
when m.birads = '{{ b }}' then {{ loop.index }}
|
|
||||||
{%- endfor %}
|
|
||||||
else 0
|
|
||||||
end as birads_gravedad,
|
|
||||||
reporte.inicio as reporte_conocido_en,
|
|
||||||
dia_toma.dia_num as toma_dia,
|
|
||||||
dia_reporte.dia_num - dia_toma.dia_num as dias_toma_reporte,
|
|
||||||
dx.fecha_diagnostico,
|
|
||||||
dx.diagnostico_conocido_en,
|
|
||||||
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
|
|
||||||
case when antecedente.fecha < m.fecha_toma then 1 else 0 end as con_antecedente
|
|
||||||
from {{ ref('cama_mastografias') }} m
|
|
||||||
join {{ source('silver', 'carga') }} toma
|
|
||||||
on toma.carga_id = m.toma_carga_id
|
|
||||||
left join {{ source('silver', 'carga') }} reporte
|
|
||||||
on reporte.carga_id = m.reporte_carga_id and m.reporte_id is not null
|
|
||||||
left join {{ source('silver', 'dim_fecha') }} dia_toma
|
|
||||||
on dia_toma.fecha = m.fecha_toma
|
|
||||||
left join {{ source('silver', 'dim_fecha') }} dia_reporte
|
|
||||||
on dia_reporte.fecha = m.fecha_reporte
|
|
||||||
left join diagnostico dx
|
|
||||||
on dx.procedimiento_id = m.procedimiento_id
|
|
||||||
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
|
|
||||||
on dia_diagnostico.fecha = dx.fecha_diagnostico
|
|
||||||
left join primer_antecedente antecedente
|
|
||||||
on antecedente.pac_id = m.pac_id
|
|
||||||
@@ -1,215 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cama_tomas_mastografia
|
|
||||||
description: "Mastografías tomadas, una fila por toma y reporte, con cuándo se supo de cada uno."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
|
|
||||||
semantic_models:
|
|
||||||
- name: cama_tomas_mastografia
|
|
||||||
description: "Mammograms taken, with their reports: what CaMa's mammography measures count over."
|
|
||||||
model: ref('cama_tomas_mastografia')
|
|
||||||
defaults:
|
|
||||||
agg_time_dimension: fecha_toma
|
|
||||||
entities:
|
|
||||||
- name: mastografia
|
|
||||||
type: primary
|
|
||||||
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '')"
|
|
||||||
- name: paciente
|
|
||||||
type: foreign
|
|
||||||
expr: pac_id
|
|
||||||
dimensions:
|
|
||||||
- name: fecha_toma
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: toma_conocida_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: fecha_reporte
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: reporte_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: fecha_diagnostico
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: diagnostico_conocido_en
|
|
||||||
type: time
|
|
||||||
type_params:
|
|
||||||
time_granularity: day
|
|
||||||
- name: birads
|
|
||||||
type: categorical
|
|
||||||
- name: birads_gravedad
|
|
||||||
type: categorical
|
|
||||||
- name: calidad_imagen
|
|
||||||
type: categorical
|
|
||||||
- name: fuente_id
|
|
||||||
type: categorical
|
|
||||||
- name: toma_dia
|
|
||||||
type: categorical
|
|
||||||
- name: dias_toma_reporte
|
|
||||||
type: categorical
|
|
||||||
- name: dias_toma_diagnostico
|
|
||||||
type: categorical
|
|
||||||
- name: con_antecedente
|
|
||||||
type: categorical
|
|
||||||
measures:
|
|
||||||
- name: mastografias
|
|
||||||
description: "Distinct mammograms (the source's id): the unit of the exam-based measures."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: fuente_id
|
|
||||||
- name: pacientes_con_mastografia
|
|
||||||
description: "Distinct patients: each counts once per period, however many mammograms."
|
|
||||||
agg: count_distinct
|
|
||||||
expr: pac_id
|
|
||||||
|
|
||||||
metrics:
|
|
||||||
- name: cama_birads
|
|
||||||
label: "Distribución de BI-RADS"
|
|
||||||
description: >-
|
|
||||||
Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías.
|
|
||||||
«Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_con_mastografia
|
|
||||||
config:
|
|
||||||
meta: &birads_por_paciente
|
|
||||||
measure_url: cama/CAMA_BIRADS
|
|
||||||
version: 0.2.0
|
|
||||||
scoring: composition
|
|
||||||
basis: paciente
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C2
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [measure-observation]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
# Each patient's most severe BI-RADS among her mammograms of the period reported by the cut-off; one without a
|
|
||||||
# report doesn't count against one with it.
|
|
||||||
categoria:
|
|
||||||
valor: birads
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: mas_grave
|
|
||||||
valido: "{% raw %}{{ Dimension('mastografia__birads') }} is not null{% endraw %}"
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [reporte_conocido_en]
|
|
||||||
orden: [birads_gravedad, fuente_id]
|
|
||||||
- name: cama_birads_456_paciente
|
|
||||||
label: "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6"
|
|
||||||
description: >-
|
|
||||||
Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus
|
|
||||||
mastografías.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: pacientes_con_mastografia
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
<<: *birads_por_paciente
|
|
||||||
measure_url: cama/CAMA_BIRADS456_PACIENTE
|
|
||||||
parametros:
|
|
||||||
birads_4_a_6: cama.birads_4_a_6
|
|
||||||
categoria:
|
|
||||||
valor: birads
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: mas_grave
|
|
||||||
valido: "{% raw %}{{ Dimension('mastografia__birads') }} is not null{% endraw %}"
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [reporte_conocido_en]
|
|
||||||
orden: [birads_gravedad, fuente_id]
|
|
||||||
# After choosing the most severe: a patient with B6 and B4 counts in B6.
|
|
||||||
admite: "{% raw %}{{ Dimension('mastografia__birads') }} in :birads_4_a_6{% endraw %}"
|
|
||||||
- name: cama_birads_456_mastografia
|
|
||||||
label: "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6"
|
|
||||||
description: "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría."
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: mastografias
|
|
||||||
filter: "{{ Dimension('mastografia__birads') }} in :birads_4_a_6"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cama/CAMA_BIRADS456_MASTOGRAFIA
|
|
||||||
version: 0.2.0
|
|
||||||
scoring: composition
|
|
||||||
basis: examen
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C2
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [measure-observation]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
parametros:
|
|
||||||
birads_4_a_6: cama.birads_4_a_6
|
|
||||||
categoria:
|
|
||||||
valor: birads
|
|
||||||
sin_dato: SIN_DATO
|
|
||||||
elige: ultimo_valido
|
|
||||||
valido: "{% raw %}{{ Dimension('mastografia__birads') }} is not null{% endraw %}"
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [reporte_conocido_en]
|
|
||||||
orden: [birads_gravedad]
|
|
||||||
- name: cama_eu38a
|
|
||||||
label: "Días de la toma de la mastografía a su resultado"
|
|
||||||
description: >-
|
|
||||||
Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no
|
|
||||||
tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los
|
|
||||||
excluidos.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: mastografias
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cama/CAMA_EU38A
|
|
||||||
version: 0.2.1
|
|
||||||
scoring: continuous-variable
|
|
||||||
basis: examen
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C3r
|
|
||||||
improvement_notation: decrease
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [initial-population]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
parametros:
|
|
||||||
horizonte_dias: cama.horizontes.toma_reporte_dias
|
|
||||||
observacion:
|
|
||||||
valor: dias_toma_reporte
|
|
||||||
fechada_en: [fecha_reporte]
|
|
||||||
conocida_en: [reporte_conocido_en]
|
|
||||||
horizonte:
|
|
||||||
regla: horizonte_dias
|
|
||||||
dia_inicio: toma_dia
|
|
||||||
- name: cama_dias_toma_diagnostico
|
|
||||||
label: "CaMa: tiempo de tamizaje a diagnóstico"
|
|
||||||
description: >-
|
|
||||||
Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un
|
|
||||||
diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que
|
|
||||||
diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no;
|
|
||||||
se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.
|
|
||||||
type: simple
|
|
||||||
type_params:
|
|
||||||
measure: mastografias
|
|
||||||
filter: "{{ Dimension('mastografia__con_antecedente') }} = 0"
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
measure_url: cama/CAMA_DIAS_TOMA_DIAGNOSTICO
|
|
||||||
titulo: "Tiempo de tamizaje a diagnóstico"
|
|
||||||
version: 0.2.2
|
|
||||||
scoring: continuous-variable
|
|
||||||
basis: examen
|
|
||||||
grupo: TOTAL
|
|
||||||
contrato: C3r
|
|
||||||
improvement_notation: decrease
|
|
||||||
tipos_periodo: [semestre, mes]
|
|
||||||
poblaciones_fhir: [initial-population]
|
|
||||||
conocida_en: [toma_conocida_en]
|
|
||||||
observacion:
|
|
||||||
valor: dias_toma_diagnostico
|
|
||||||
fechada_en: [fecha_diagnostico]
|
|
||||||
conocida_en: [diagnostico_conocido_en]
|
|
||||||
horizonte:
|
|
||||||
dias: "{{ var('cama')['horizonte_toma_diagnostico_dias'] }}"
|
|
||||||
dia_inicio: toma_dia
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
/*
|
|
||||||
One row per biopsy report with its grade, its order and the mammogram that led to it, if found:
|
|
||||||
mammogram (toma) -> biopsy order -> biopsy report, by `padre_id`.
|
|
||||||
*/
|
|
||||||
|
|
||||||
select
|
|
||||||
r.procedimiento_id,
|
|
||||||
r.fuente_tabla,
|
|
||||||
r.fuente_id,
|
|
||||||
r.pac_id,
|
|
||||||
r.fecha as fecha_reporte,
|
|
||||||
coalesce(o_gr.valor_id, o_gr.valor_fuente) as grado,
|
|
||||||
orden.fecha as fecha_solicitud,
|
|
||||||
t.procedimiento_id as toma_id,
|
|
||||||
coalesce(o_gr.carga_id, r.carga_id) as reporte_carga_id
|
|
||||||
from {{ source('silver', 'procedimiento') }} r
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o_gr
|
|
||||||
on o_gr.procedimiento_id = r.procedimiento_id and o_gr.resultado_id = 'biopsia.grado'
|
|
||||||
left join {{ source('silver', 'procedimiento') }} orden
|
|
||||||
on orden.procedimiento_id = r.padre_id and orden.estudio_id = 'biopsia' and orden.clase = 'orden'
|
|
||||||
left join {{ source('silver', 'procedimiento') }} t
|
|
||||||
on t.procedimiento_id = orden.padre_id and t.estudio_id = 'mastografia' and t.clase = 'toma'
|
|
||||||
where r.estudio_id = 'biopsia' and r.clase = 'reporte'
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cama_linea_de_tiempo.yml;
|
|
||||||
the procedures silver doesn't hold but its notes imply (diagnosis, antecedent): cama_procedimientos_inferidos. #}
|
|
||||||
{{ config(materialized = 'view') }}
|
|
||||||
|
|
||||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
|
|
||||||
from {{ ref('cama_procedimientos_inferidos') }}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: cama_linea_de_tiempo
|
|
||||||
description: >
|
|
||||||
Each patient's timeline: every fact of silver (procedimiento ⟕ observacion_clinica) in one shape and
|
|
||||||
in order. One source per kind of fact: study, procedure class and result, with what the timeline calls
|
|
||||||
it (`clase_de_linea`, `tipo`, `codigo`) and where its value and date come from. Adding a kind of
|
|
||||||
observation is adding a source here.
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
# estudio_id (null: any study), clase, resultado_id (null: the value comes from `columna` of the
|
|
||||||
# procedure), clase_de_linea, tipo; optional: codigo (default: tipo), valor (codigo | numerico),
|
|
||||||
# columna, fecha (procedimiento | nacimiento), fecha_resultado (an observed date that goes first),
|
|
||||||
# del_padre (date and patient from the parent procedure).
|
|
||||||
fuentes:
|
|
||||||
- {estudio_id: "mastografia", clase: "toma", resultado_id: "mastografia.calidad_imagen", clase_de_linea: "procedimiento", tipo: "mastografia", codigo: "mastografia"}
|
|
||||||
- {estudio_id: "mastografia", clase: "reporte", resultado_id: "mastografia.birads", clase_de_linea: "medicion", tipo: "birads", codigo: "birads"}
|
|
||||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "grado_histologico"}
|
|
||||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
|
||||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
/*
|
|
||||||
One row per mammogram taken and each report that hangs from it (`padre_id`; one row with nulls when it has none),
|
|
||||||
with its image quality and BI-RADS. A code the catalog doesn't know comes as it arrived
|
|
||||||
(`coalesce(valor_id, valor_fuente)`), as the timeline reads it.
|
|
||||||
*/
|
|
||||||
|
|
||||||
select
|
|
||||||
t.procedimiento_id,
|
|
||||||
t.fuente_tabla,
|
|
||||||
t.fuente_id,
|
|
||||||
t.pac_id,
|
|
||||||
t.fecha as fecha_toma,
|
|
||||||
coalesce(o_cal.valor_id, o_cal.valor_fuente) as calidad_imagen,
|
|
||||||
r.procedimiento_id as reporte_id,
|
|
||||||
r.fecha as fecha_reporte,
|
|
||||||
coalesce(o_bi.valor_id, o_bi.valor_fuente) as birads,
|
|
||||||
t.carga_id as toma_carga_id,
|
|
||||||
coalesce(o_bi.carga_id, r.carga_id) as reporte_carga_id
|
|
||||||
from {{ source('silver', 'procedimiento') }} t
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o_cal
|
|
||||||
on o_cal.procedimiento_id = t.procedimiento_id and o_cal.resultado_id = 'mastografia.calidad_imagen'
|
|
||||||
left join {{ source('silver', 'procedimiento') }} r
|
|
||||||
on r.padre_id = t.procedimiento_id and r.estudio_id = 'mastografia' and r.clase = 'reporte'
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o_bi
|
|
||||||
on o_bi.procedimiento_id = r.procedimiento_id and o_bi.resultado_id = 'mastografia.birads'
|
|
||||||
where t.estudio_id = 'mastografia' and t.clase = 'toma'
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
{{ config(materialized = 'view') }}
|
|
||||||
-- The procedures CaMa's notes imply, in the timeline's shape (`cama_linea_de_tiempo` adds them to each patient's
|
|
||||||
-- timeline):
|
|
||||||
-- diagnostico a note that can resolve a mammogram: a diagnosis ICD-10 (`cama.cie_diagnostico`) written by a
|
|
||||||
-- diagnosing specialty (`cama.especialidades_diagnostico`)
|
|
||||||
-- antecedente a note with a breast cancer ICD-10 (`cama.cie_antecedente`), whoever wrote it
|
|
||||||
{% set r = var('cama') %}
|
|
||||||
|
|
||||||
with nota as (
|
|
||||||
select
|
|
||||||
p.pac_id,
|
|
||||||
p.fecha,
|
|
||||||
p.fuente_tabla,
|
|
||||||
p.fuente_id,
|
|
||||||
c.inicio as conocida_en,
|
|
||||||
max(case when o.resultado_id = 'nota_medica.diagnostico' then o.valor_texto end) as cie_codigo,
|
|
||||||
max(case when o.resultado_id = 'nota_medica.especialidad' then o.valor_id end) as especialidad
|
|
||||||
from {{ source('silver', 'procedimiento') }} p
|
|
||||||
join {{ source('silver', 'carga') }} c on c.carga_id = p.carga_id
|
|
||||||
left join {{ source('silver', 'observacion_clinica') }} o on o.procedimiento_id = p.procedimiento_id
|
|
||||||
where p.estudio_id = 'nota_medica' and p.clase = 'encuentro'
|
|
||||||
group by p.procedimiento_id, p.pac_id, p.fecha, p.fuente_tabla, p.fuente_id, c.inicio
|
|
||||||
),
|
|
||||||
|
|
||||||
inferidos as (
|
|
||||||
select pac_id, fecha, conocida_en, 'diagnostico' as tipo, fuente_tabla, fuente_id from nota
|
|
||||||
where cie_codigo in {{ sql_list(r['cie_diagnostico']) }}
|
|
||||||
and especialidad in {{ sql_list(r['especialidades_diagnostico']) }}
|
|
||||||
union all
|
|
||||||
select pac_id, fecha, conocida_en, 'antecedente', fuente_tabla, fuente_id from nota
|
|
||||||
where cie_codigo in {{ sql_list(r['cie_antecedente']) }}
|
|
||||||
)
|
|
||||||
|
|
||||||
select
|
|
||||||
pac_id,
|
|
||||||
fecha,
|
|
||||||
conocida_en,
|
|
||||||
{{ as_text("'procedimiento'") }} as clase,
|
|
||||||
{{ as_text('tipo') }} as tipo,
|
|
||||||
{{ as_text('tipo') }} as codigo,
|
|
||||||
{{ as_text('null') }} as valor_codigo,
|
|
||||||
cast(null as {{ dbt.type_float() }}) as valor_numerico,
|
|
||||||
fuente_tabla,
|
|
||||||
fuente_id
|
|
||||||
from inferidos
|
|
||||||
where fecha is not null
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
-- The semantic layer's calendar: one row per day, from the `dim_fecha` each domain's cycle loads.
|
|
||||||
select fecha as date_day from {{ source('silver', 'dim_fecha') }}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: metricflow_time_spine
|
|
||||||
description: "The calendar the semantic layer requires; dbt only validates against it."
|
|
||||||
config:
|
|
||||||
materialized: view
|
|
||||||
time_spine:
|
|
||||||
standard_granularity_column: date_day
|
|
||||||
columns:
|
|
||||||
- name: date_day
|
|
||||||
granularity: day
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: tea_linea_de_tiempo.yml. #}
|
|
||||||
{{ config(materialized = 'view') }}
|
|
||||||
|
|
||||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
models:
|
|
||||||
- name: tea_linea_de_tiempo
|
|
||||||
description: >
|
|
||||||
Each patient's timeline: every fact of silver (procedimiento ⟕ observacion_clinica) in one shape and
|
|
||||||
in order. One source per kind of fact: study, procedure class and result, with what the timeline calls
|
|
||||||
it (`clase_de_linea`, `tipo`, `codigo`) and where its value and date come from. Adding a kind of
|
|
||||||
observation is adding a source here.
|
|
||||||
config:
|
|
||||||
meta:
|
|
||||||
# estudio_id (null: any study), clase, resultado_id (null: the value comes from `columna` of the
|
|
||||||
# procedure), clase_de_linea, tipo; optional: codigo (default: tipo), valor (codigo | numerico),
|
|
||||||
# columna, fecha (procedimiento | nacimiento), fecha_resultado (an observed date that goes first),
|
|
||||||
# del_padre (date and patient from the parent procedure).
|
|
||||||
fuentes:
|
|
||||||
- {estudio_id: "evaluacion_psicologica", clase: "encuentro", resultado_id: "evaluacion_psicologica.instrumento_tamizaje", clase_de_linea: "procedimiento", tipo: "evaluacion_psicologica", fecha_resultado: "evaluacion_psicologica.fecha_evaluacion"}
|
|
||||||
- {estudio_id: "mchat", clase: "toma", resultado_id: "mchat.interpretacion", clase_de_linea: "medicion", tipo: "instrumento", codigo: "M_CHAT_R_F", fecha_resultado: "evaluacion_psicologica.fecha_evaluacion", del_padre: true}
|
|
||||||
- {estudio_id: "ramos", clase: "toma", resultado_id: "ramos.interpretacion", clase_de_linea: "medicion", tipo: "instrumento", codigo: "RAMOS", fecha_resultado: "evaluacion_psicologica.fecha_evaluacion", del_padre: true}
|
|
||||||
- {estudio_id: "eeg", clase: "toma", resultado_id: "eeg.utilizable", clase_de_linea: "procedimiento", tipo: "eeg", codigo: "electroencefalograma", valor: "numerico"}
|
|
||||||
- {estudio_id: "pea", clase: "toma", resultado_id: "pea.grado_hipoacusia", clase_de_linea: "medicion", tipo: "pea"}
|
|
||||||
- {estudio_id: "parto", clase: "encuentro", resultado_id: "parto.apgar_5min", clase_de_linea: "antecedente", tipo: "apgar_5min", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "parto", clase: "encuentro", resultado_id: "parto.ingreso_ucin", clase_de_linea: "antecedente", tipo: "ingreso_ucin", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.antecedente_aborto", clase_de_linea: "antecedente", tipo: "antecedente_aborto", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.asma", clase_de_linea: "antecedente", tipo: "asma", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.crisis_convulsivas", clase_de_linea: "antecedente", tipo: "crisis_convulsivas", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.diabetes_gestacional", clase_de_linea: "antecedente", tipo: "diabetes_gestacional", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.embarazo_multiple", clase_de_linea: "antecedente", tipo: "embarazo_multiple", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.enfermedad_autoinmune", clase_de_linea: "antecedente", tipo: "enfermedad_autoinmune", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.estres_agudo", clase_de_linea: "antecedente", tipo: "estres_agudo", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.farmaco_riesgo_neurodesarrollo", clase_de_linea: "antecedente", tipo: "farmaco_riesgo_neurodesarrollo", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipertension_preeclampsia", clase_de_linea: "antecedente", tipo: "hipertension_preeclampsia", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipertiroidismo", clase_de_linea: "antecedente", tipo: "hipertiroidismo", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipotiroidismo", clase_de_linea: "antecedente", tipo: "hipotiroidismo", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipoxia_materna", clase_de_linea: "antecedente", tipo: "hipoxia_materna", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.incompatibilidad_rh", clase_de_linea: "antecedente", tipo: "incompatibilidad_rh", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.infeccion_gestacion", clase_de_linea: "antecedente", tipo: "infeccion_gestacion", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.liquido_amniotico", clase_de_linea: "antecedente", tipo: "liquido_amniotico", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.migrana", clase_de_linea: "antecedente", tipo: "migrana", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.proceso_proinflamatorio", clase_de_linea: "antecedente", tipo: "proceso_proinflamatorio", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.tabaquismo_gestacion", clase_de_linea: "antecedente", tipo: "tabaquismo_gestacion", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.trastorno_neurologico", clase_de_linea: "antecedente", tipo: "trastorno_neurologico", valor: "numerico", fecha: "nacimiento"}
|
|
||||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
|
||||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
# One profile per domain (`--profile cacu|cama|tea`; `cacu` by default) and one target per engine
|
|
||||||
# (`--target sqlite|sqlserver|postgres|mysql`; `sqlite` by default). Every value comes from the environment;
|
|
||||||
# nothing secret is written here.
|
|
||||||
#
|
|
||||||
# sqlite <DOMAIN>_DB_PATH: the domain's .db file. DBT_SCHEMA_DIR: where dbt-sqlite keeps any other
|
|
||||||
# schema as its own .db file. dbt-sqlite attaches every .db it finds there, so it must never be
|
|
||||||
# the folder of the domains' databases (a domain's views would then be opened under another
|
|
||||||
# name and break).
|
|
||||||
# others DBT_HOST, DBT_PORT, DBT_USER, DBT_PASSWORD, and <DOMAIN>_DBT_DATABASE (the domain's
|
|
||||||
# database; by default, the domain's name).
|
|
||||||
#
|
|
||||||
# `mysql` runs with the `mysql` dependency group (dbt-core 1.7): `uv run --only-group mysql dbt ...`.
|
|
||||||
|
|
||||||
cacu:
|
|
||||||
target: sqlite
|
|
||||||
outputs:
|
|
||||||
sqlite: &sqlite
|
|
||||||
type: sqlite
|
|
||||||
threads: 1
|
|
||||||
database: main
|
|
||||||
schema: main
|
|
||||||
schemas_and_paths:
|
|
||||||
main: "{{ env_var('CACU_DB_PATH', 'cacu.db') }}"
|
|
||||||
schema_directory: "{{ env_var('DBT_SCHEMA_DIR', 'target/schemas') }}"
|
|
||||||
sqlserver: &sqlserver
|
|
||||||
type: sqlserver
|
|
||||||
backend: mssql-python # Microsoft's driver: no system ODBC libraries needed
|
|
||||||
server: "{{ env_var('DBT_HOST', 'localhost') }}"
|
|
||||||
port: "{{ env_var('DBT_PORT', '1433') | as_number }}"
|
|
||||||
database: "{{ env_var('CACU_DBT_DATABASE', 'cacu') }}"
|
|
||||||
schema: dbo
|
|
||||||
user: "{{ env_var('DBT_USER', '') }}"
|
|
||||||
password: "{{ env_var('DBT_PASSWORD', '') }}"
|
|
||||||
encrypt: true
|
|
||||||
trust_cert: true
|
|
||||||
threads: 4
|
|
||||||
postgres: &postgres
|
|
||||||
type: postgres
|
|
||||||
host: "{{ env_var('DBT_HOST', 'localhost') }}"
|
|
||||||
port: "{{ env_var('DBT_PORT', '5432') | as_number }}"
|
|
||||||
dbname: "{{ env_var('CACU_DBT_DATABASE', 'cacu') }}"
|
|
||||||
schema: public
|
|
||||||
user: "{{ env_var('DBT_USER', '') }}"
|
|
||||||
password: "{{ env_var('DBT_PASSWORD', '') }}"
|
|
||||||
threads: 4
|
|
||||||
mysql: &mysql
|
|
||||||
type: mysql
|
|
||||||
server: "{{ env_var('DBT_HOST', 'localhost') }}"
|
|
||||||
port: "{{ env_var('DBT_PORT', '3306') | as_number }}"
|
|
||||||
schema: "{{ env_var('CACU_DBT_DATABASE', 'cacu') }}"
|
|
||||||
username: "{{ env_var('DBT_USER', '') }}"
|
|
||||||
password: "{{ env_var('DBT_PASSWORD', '') }}"
|
|
||||||
threads: 4
|
|
||||||
|
|
||||||
cama:
|
|
||||||
target: sqlite
|
|
||||||
outputs:
|
|
||||||
sqlite:
|
|
||||||
<<: *sqlite
|
|
||||||
schemas_and_paths:
|
|
||||||
main: "{{ env_var('CAMA_DB_PATH', 'cama.db') }}"
|
|
||||||
sqlserver:
|
|
||||||
<<: *sqlserver
|
|
||||||
database: "{{ env_var('CAMA_DBT_DATABASE', 'cama') }}"
|
|
||||||
postgres:
|
|
||||||
<<: *postgres
|
|
||||||
dbname: "{{ env_var('CAMA_DBT_DATABASE', 'cama') }}"
|
|
||||||
mysql:
|
|
||||||
<<: *mysql
|
|
||||||
schema: "{{ env_var('CAMA_DBT_DATABASE', 'cama') }}"
|
|
||||||
|
|
||||||
tea:
|
|
||||||
target: sqlite
|
|
||||||
outputs:
|
|
||||||
sqlite:
|
|
||||||
<<: *sqlite
|
|
||||||
schemas_and_paths:
|
|
||||||
main: "{{ env_var('TEA_DB_PATH', 'tea.db') }}"
|
|
||||||
sqlserver:
|
|
||||||
<<: *sqlserver
|
|
||||||
database: "{{ env_var('TEA_DBT_DATABASE', 'tea') }}"
|
|
||||||
postgres:
|
|
||||||
<<: *postgres
|
|
||||||
dbname: "{{ env_var('TEA_DBT_DATABASE', 'tea') }}"
|
|
||||||
mysql:
|
|
||||||
<<: *mysql
|
|
||||||
schema: "{{ env_var('TEA_DBT_DATABASE', 'tea') }}"
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
[project]
|
|
||||||
name = "transformation"
|
|
||||||
version = "0.1.0"
|
|
||||||
description = "dbt transformation layer: bronze → silver (observacion/procedimiento) → gold (cohorts, indicators)."
|
|
||||||
requires-python = ">=3.12,<3.14"
|
|
||||||
dependencies = []
|
|
||||||
|
|
||||||
# dbt-core lives in the groups, one per engine: dbt-mysql still requires dbt-core 1.7, while the others run on
|
|
||||||
# 1.12, so `mysql` is installed on its own (`uv sync --only-group mysql`). What must run on MySQL stays within
|
|
||||||
# dbt 1.7: its `unit_tests` are ignored there.
|
|
||||||
[dependency-groups]
|
|
||||||
sqlite = ["dbt-core>=1.12,<1.13", "dbt-sqlite>=1.10"]
|
|
||||||
sqlserver = ["dbt-core>=1.12,<1.13", "dbt-sqlserver[mssql]>=1.12.2"]
|
|
||||||
postgres = ["dbt-core>=1.12,<1.13", "dbt-postgres>=1.10"]
|
|
||||||
mysql = ["dbt-core>=1.7,<1.8", "dbt-mysql>=1.7,<1.8"]
|
|
||||||
|
|
||||||
[tool.uv]
|
|
||||||
package = false
|
|
||||||
default-groups = ["sqlite"]
|
|
||||||
# dbt-sqlite 1.10 asks for an older dbt-adapters than dbt-core 1.12 needs; it runs on the newer one.
|
|
||||||
override-dependencies = ["dbt-adapters>=1.24.5,<2"]
|
|
||||||
conflicts = [
|
|
||||||
[{ group = "mysql" }, { group = "sqlite" }],
|
|
||||||
[{ group = "mysql" }, { group = "sqlserver" }],
|
|
||||||
[{ group = "mysql" }, { group = "postgres" }],
|
|
||||||
]
|
|
||||||
+1
-1
Submodule WebApi updated: c430a5bd11...fce6ccd40a
+1
-1
Submodule WebApp updated: 62cdb252ca...f4d2a3e85f
+1
-1
Submodule indicadores_kit updated: a20b4ed13c...5142e57ce7
+1
-1
Submodule models updated: a4ddad5c8e...f9d3b8f67e
Reference in New Issue
Block a user