TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary
This commit is contained in:
@@ -14,6 +14,7 @@ llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`,
|
||||
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from typing import NamedTuple
|
||||
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
@@ -59,6 +60,16 @@ class Hija:
|
||||
resultados: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Junta:
|
||||
"""Another staging row whose columns the row's content takes: the row of `staging` whose `llave` equals the
|
||||
row's column `columna` (an electrode value takes its metric's code and EEG). Without a match, they're null."""
|
||||
|
||||
staging: type
|
||||
llave: str
|
||||
columna: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeStaging:
|
||||
"""Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c).
|
||||
@@ -72,6 +83,10 @@ class DeStaging:
|
||||
no es un reporte); no es un descarte.
|
||||
- `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en
|
||||
`descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging.
|
||||
- `juntas`: rows of other staging tables whose columns join the content before the derived ones.
|
||||
- `observa_en`: the row gives no procedure of its own; its observations go on the procedure this parent key
|
||||
names (a metric of an EEG is a result of the EEG's recording). `clase` is unused then.
|
||||
A result's template can name the content's columns (`eeg.{metrica}`) besides `{estudio}`.
|
||||
|
||||
Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada.
|
||||
Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17).
|
||||
@@ -92,6 +107,8 @@ class DeStaging:
|
||||
paciente: str | None = "pac_id"
|
||||
solo_si: Callable | None = None
|
||||
descartar: Callable | None = None
|
||||
juntas: tuple[Junta, ...] = ()
|
||||
observa_en: Padre | None = None
|
||||
|
||||
|
||||
class LotePlata(NamedTuple):
|
||||
@@ -124,6 +141,7 @@ def plata_desde_staging(
|
||||
pacientes = set(pacientes)
|
||||
tipos, vigentes = _tipos_y_vigentes(catalogo)
|
||||
procedimientos, observaciones, descartes = [], [], {}
|
||||
indices: dict[tuple[str, str], dict] = {}
|
||||
for c in correspondencias:
|
||||
tabla = c.staging.__tablename__
|
||||
for fila in filas.get(tabla, ()):
|
||||
@@ -133,7 +151,13 @@ def plata_desde_staging(
|
||||
continue
|
||||
if c.solo_si is not None and not c.solo_si(fila):
|
||||
continue
|
||||
contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido = fila.model_dump()
|
||||
if c.juntas:
|
||||
for junta in c.juntas:
|
||||
unida = _junta(junta, filas, indices).get(contenido.get(junta.columna))
|
||||
contenido = {**(unida or dict.fromkeys(junta.staging.model_fields)), **contenido}
|
||||
fila = SimpleNamespace(**contenido)
|
||||
contenido = {**contenido, **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente)
|
||||
contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()})
|
||||
_repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital,
|
||||
@@ -168,6 +192,14 @@ def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]:
|
||||
return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3])))
|
||||
|
||||
|
||||
def _junta(junta: Junta, filas: Mapping[str, Iterable], indices: dict) -> dict:
|
||||
"""The rows of the joined table by their key, as dictionaries; built once per batch."""
|
||||
clave = (junta.staging.__tablename__, junta.llave)
|
||||
if clave not in indices:
|
||||
indices[clave] = {getattr(f, junta.llave): f.model_dump() for f in filas.get(clave[0], ())}
|
||||
return indices[clave]
|
||||
|
||||
|
||||
def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]:
|
||||
tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados}
|
||||
vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
@@ -183,6 +215,11 @@ def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, col
|
||||
motivo = f"{nombre}: {c.estudio_de} fuera de catálogo"
|
||||
descartes[motivo] = descartes.get(motivo, 0) + 1
|
||||
return
|
||||
if c.observa_en is not None:
|
||||
dueno = _parent(c.observa_en, contenido)
|
||||
if dueno is not None:
|
||||
observaciones += _observaciones(dueno, contenido, c.resultados, c.fuentes, tipos, vigentes)
|
||||
return
|
||||
llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase)
|
||||
procedimientos.append({
|
||||
"llave": llave,
|
||||
@@ -225,7 +262,9 @@ def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str],
|
||||
tipos: dict, vigentes: set) -> list[dict]:
|
||||
filas = []
|
||||
for columna, plantilla in resultados.items():
|
||||
resultado_id = plantilla.format(estudio=llave[2])
|
||||
resultado_id = plantilla.format_map({**contenido, "estudio": llave[2]})
|
||||
if resultado_id not in tipos and "{" in plantilla.replace("{estudio}", ""):
|
||||
continue # a value of the row names a result the catalog doesn't have (an unknown metric)
|
||||
filas.append({
|
||||
"procedimiento": llave,
|
||||
"pac_id": contenido.get("pac_id"),
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""TEA in the two-table silver: what each staging row gives, as `DESDE_STAGING` (read by `carga_desde_staging`).
|
||||
|
||||
- an order is an `orden` of the study it asks for (`ord_tipo_estudio`, in Core's code or one of its aliases);
|
||||
- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each
|
||||
hangs from its order when it has one;
|
||||
- an EEG metric is a result of its EEG's recording, not a procedure; a metric's electrode value is a `parte` of the
|
||||
EEG (`codigo_fuente` the electrode) with the metric's result. Both find their EEG through the metric's row.
|
||||
"""
|
||||
|
||||
from core.tea.enums import (
|
||||
CLASIFICACION_ADOS2_ALIAS,
|
||||
TIPO_ESTUDIO_ALIAS,
|
||||
ClasificacionAdos2,
|
||||
ModuloAdos2,
|
||||
TipoEstudio,
|
||||
)
|
||||
from core.tea.models import (
|
||||
ADOS2_ITEMS,
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
)
|
||||
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Junta, Padre
|
||||
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
|
||||
|
||||
PACIENTES = Pacientes # where persons come from
|
||||
ORDENES = OrdenesEstudio.__tablename__
|
||||
EEG = Eeg.__tablename__
|
||||
|
||||
|
||||
def _codigo(columna: str, enum, alias: dict | None = None):
|
||||
codigos = {e.value for e in enum}
|
||||
return lambda f: codigo_de_especialidad(getattr(f, columna), alias or {}, codigos)
|
||||
|
||||
|
||||
def _su_orden(estudio_id: str, columna: str) -> Padre:
|
||||
"""The order a study row names by its `*_ord_id`."""
|
||||
return Padre(estudio_id=estudio_id, clase="orden", fuente_id=columna, tabla=ORDENES)
|
||||
|
||||
|
||||
def _metrica(f) -> str | None:
|
||||
"""A metric's result in the catalog: its code in lower case (`RITMO_POSTERIOR` -> `ritmo_posterior`)."""
|
||||
codigo = texto_limpio(f.met_codigo)
|
||||
return None if codigo is None else codigo.lower()
|
||||
|
||||
|
||||
SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG)
|
||||
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
OrdenesEstudio, "ord_id", "orden", estudio_de="tipo_estudio", fecha="ord_fecha", paciente="ord_pac_id",
|
||||
derivadas={
|
||||
"tipo_estudio": _codigo("ord_tipo_estudio", TipoEstudio, TIPO_ESTUDIO_ALIAS),
|
||||
"intencion": lambda f: INTENCION,
|
||||
},
|
||||
columnas={"id_hospital": "ord_id_hospital", "codigo_fuente": "ord_tipo_estudio"},
|
||||
resultados={"intencion": "orden.intencion"},
|
||||
),
|
||||
DeStaging(
|
||||
Mchat, "mch_id", "toma", estudio_id="mchat", fecha="mch_fecha", paciente="mch_pac_id",
|
||||
padres=(_su_orden("mchat", "mch_ord_id"),),
|
||||
resultados={"mch_puntaje": "mchat.puntaje"},
|
||||
),
|
||||
DeStaging(
|
||||
Ados2, "ado_id", "encuentro", estudio_id="ados2", fecha="ado_fecha", paciente="ado_pac_id",
|
||||
padres=(_su_orden("ados2", "ado_ord_id"),),
|
||||
derivadas={
|
||||
"modulo": _codigo("ado_modulo", ModuloAdos2),
|
||||
"clasificacion": _codigo("ado_clasificacion", ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS),
|
||||
"algoritmo": lambda f: texto_limpio(f.ado_algoritmo),
|
||||
},
|
||||
resultados={
|
||||
"modulo": "ados2.modulo",
|
||||
"algoritmo": "ados2.algoritmo",
|
||||
"clasificacion": "ados2.clasificacion",
|
||||
"ado_css": "ados2.css",
|
||||
**{f"ado_{item}": f"ados2.{item}" for item in ADOS2_ITEMS},
|
||||
},
|
||||
fuentes={"modulo": "ado_modulo", "clasificacion": "ado_clasificacion"},
|
||||
),
|
||||
DeStaging(
|
||||
EvaluacionNeuropediatrica, "neu_id", "encuentro", estudio_id="evaluacion_neuropediatrica",
|
||||
fecha="neu_fecha", paciente="neu_pac_id", padres=(_su_orden("evaluacion_neuropediatrica", "neu_ord_id"),),
|
||||
derivadas={"cie_codigo": lambda f: cie(f.neu_cie_codigo)},
|
||||
resultados={"cie_codigo": "evaluacion_neuropediatrica.diagnostico"},
|
||||
),
|
||||
DeStaging(
|
||||
Eeg, "eeg_id", "toma", estudio_id="eeg", fecha="eeg_fecha_estudio", paciente="eeg_pac_id",
|
||||
padres=(_su_orden("eeg", "eeg_ord_id"),), columnas={"id_hospital": "eeg_id_registro_laboratorio"},
|
||||
resultados={
|
||||
"eeg_con_sueno": "eeg.con_sueno",
|
||||
"eeg_canales": "eeg.canales",
|
||||
"eeg_duracion_min": "eeg.duracion_min",
|
||||
"eeg_canales_amplitud": "eeg.calidad_amplitud",
|
||||
"eeg_canales_alta_frecuencia": "eeg.calidad_alta_frecuencia",
|
||||
"eeg_canales_correlacion": "eeg.calidad_correlacion",
|
||||
"eeg_canales_sin_senal": "eeg.calidad_sin_senal",
|
||||
"eeg_ruido_linea_db": "eeg.calidad_linea",
|
||||
},
|
||||
),
|
||||
DeStaging(
|
||||
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
|
||||
derivadas={"metrica": _metrica},
|
||||
resultados={"met_valor": "eeg.{metrica}"},
|
||||
),
|
||||
DeStaging(
|
||||
EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,
|
||||
juntas=(Junta(EegMetrica, "met_id", "mel_met_id"),), padres=(SU_EEG,),
|
||||
derivadas={"metrica": _metrica},
|
||||
columnas={"codigo_fuente": "mel_electrodo"},
|
||||
resultados={"mel_valor": "eeg.{metrica}"},
|
||||
),
|
||||
)
|
||||
Reference in New Issue
Block a user