Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 589b0bd688 | |||
| 2f473bbff5 | |||
| a04d48d058 | |||
| c28a7859d8 | |||
| 5593c6645d | |||
| 4835816ebf | |||
| d586ec20e0 | |||
| 7fb9ed007a | |||
| f195b7159a | |||
| d0af444a62 |
@@ -32,7 +32,10 @@ def _paciente(h: Historia, pac_id: int) -> Pacientes:
|
||||
|
||||
|
||||
def _ordenes(h: Historia, pac_id: int) -> list[OrdenesEstudio]:
|
||||
"""La orden de EEG y la de evaluación, cada una si la historia trae su fecha."""
|
||||
"""La orden de EEG, la de evaluación y la de PEA, cada una si la historia trae su fecha.
|
||||
|
||||
La de PEA (T-22g) lleva la fecha del estudio: la historia no trae otra.
|
||||
"""
|
||||
lista = []
|
||||
if h.orden_eeg_fecha is not None:
|
||||
lista.append(
|
||||
@@ -49,15 +52,24 @@ def _ordenes(h: Historia, pac_id: int) -> list[OrdenesEstudio]:
|
||||
ord_tipo_estudio=TipoEstudio.EVALUACION_PSICOLOGICA_TEA.value,
|
||||
)
|
||||
)
|
||||
if h.pea_fecha is not None:
|
||||
lista.append(
|
||||
OrdenesEstudio(
|
||||
ord_id=f"ord-pea-{h.clave}", ord_pac_id=pac_id, ord_fecha=h.pea_fecha,
|
||||
ord_tipo_estudio=TipoEstudio.POTENCIALES_EVOCADOS_AUDITIVOS.value,
|
||||
ord_fecha_realizacion=h.pea_fecha,
|
||||
)
|
||||
)
|
||||
return lista
|
||||
|
||||
|
||||
def _evaluacion(h: Historia, pac_id: int) -> EvaluacionPsicologica | None:
|
||||
"""La evaluación psicológica, si hay fecha de ADOS-2."""
|
||||
"""La evaluación psicológica, si hay fecha de ADOS-2, con su orden de evaluación si la hay (T-22g)."""
|
||||
if h.ados2_fecha is None:
|
||||
return None
|
||||
return EvaluacionPsicologica(
|
||||
psi_id=f"psi-{h.clave}", psi_pac_id=pac_id,
|
||||
psi_ord_id=f"ord-eval-{h.clave}" if h.orden_evaluacion_fecha is not None else None,
|
||||
psi_fecha_entrevista_inicial=h.entrevista_inicial, psi_fecha_ados2=h.ados2_fecha,
|
||||
psi_ados2_css=h.ados2_css, psi_ados2_clasificacion=h.ados2_clasificacion,
|
||||
psi_ados2_modulo=h.ados2_modulo,
|
||||
@@ -79,12 +91,17 @@ def _instrumentos(h: Historia) -> list[InstrumentoAplicado]:
|
||||
]
|
||||
|
||||
|
||||
def _eeg(h: Historia) -> EegEstudio | None:
|
||||
"""El EEG, sin `pac_id` (I-D2): lleva nacimiento y sexo del archivo."""
|
||||
def _eeg(h: Historia, pac_id: int) -> EegEstudio | None:
|
||||
"""El EEG con su niño y su orden de EEG, si la hay (T-22f: el responsable de TEA pidió ligarlo por llaves).
|
||||
|
||||
Sigue llevando el nacimiento y el sexo del archivo, como llegan en el .edf.
|
||||
"""
|
||||
if h.eeg_fecha is None:
|
||||
return None
|
||||
return EegEstudio(
|
||||
eeg_id=f"eeg-{h.clave}", eeg_fecha_estudio=h.eeg_fecha,
|
||||
eeg_id=f"eeg-{h.clave}", eeg_pac_id=pac_id,
|
||||
eeg_ord_id=f"ord-eeg-{h.clave}" if h.orden_eeg_fecha is not None else None,
|
||||
eeg_fecha_estudio=h.eeg_fecha,
|
||||
eeg_fecha_nacimiento_archivo=h.nacimiento, eeg_sexo_archivo=h.sexo,
|
||||
eeg_duracion_min=h.eeg_duracion_min, eeg_utilizable=h.eeg_utilizable,
|
||||
)
|
||||
@@ -104,11 +121,13 @@ def _segmentos(h: Historia) -> list[EegSegmento]:
|
||||
|
||||
|
||||
def _pea(h: Historia, pac_id: int) -> PotencialesEvocadosAuditivos | None:
|
||||
"""El PEA, si la historia trae fecha o grado."""
|
||||
"""El PEA, si la historia trae fecha o grado, con su orden de PEA si trae fecha (T-22g)."""
|
||||
if h.pea_fecha is None and h.pea_grado_hipoacusia is None:
|
||||
return None
|
||||
return PotencialesEvocadosAuditivos(
|
||||
pea_id=f"pea-{h.clave}", pea_pac_id=pac_id, pea_fecha_estudio=h.pea_fecha,
|
||||
pea_id=f"pea-{h.clave}", pea_pac_id=pac_id,
|
||||
pea_ord_id=f"ord-pea-{h.clave}" if h.pea_fecha is not None else None,
|
||||
pea_fecha_estudio=h.pea_fecha,
|
||||
pea_grado_hipoacusia=h.pea_grado_hipoacusia,
|
||||
)
|
||||
|
||||
@@ -147,7 +166,7 @@ def a_filas(historias: list[Historia]) -> dict[str, list]:
|
||||
filas["instrumentos"] += _instrumentos(h)
|
||||
filas["segmentos"] += _segmentos(h)
|
||||
for tabla, fila in (
|
||||
("evaluaciones", _evaluacion(h, pac_id)), ("eegs", _eeg(h)), ("peas", _pea(h, pac_id)),
|
||||
("evaluaciones", _evaluacion(h, pac_id)), ("eegs", _eeg(h, pac_id)), ("peas", _pea(h, pac_id)),
|
||||
("partos", _parto(h, pac_id)), ("antecedentes", _antecedentes(h, pac_id)),
|
||||
("notas", _nota_medica(h, pac_id)),
|
||||
):
|
||||
|
||||
+1
-1
@@ -151,7 +151,7 @@ def test_cada_biopsia_sale_de_una_citologia_anomala_y_va_despues_de_su_reporte(m
|
||||
|
||||
|
||||
def test_agregar_resultados_no_cambio_las_fechas_ni_las_calidades(mujeres):
|
||||
# Lo que ya comparaba `cacu_eu8`: sale de azares derivados que no dependen de los nuevos.
|
||||
# Las fechas de toma salen de azares derivados que no dependen de los resultados nuevos.
|
||||
primera = next(h for h in mujeres if h.citologias)
|
||||
assert (primera.clave, primera.citologias[0].fecha_toma) == (
|
||||
primera.clave,
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ from dev_data.cama.historias import EDAD_MAXIMA, EDAD_MINIMA, edad_en, historias
|
||||
REFERENCIA = date(2026, 1, 1)
|
||||
N = 300
|
||||
SEMILLA = 7
|
||||
INDICADOR = "cama_eu8"
|
||||
INDICADOR = "cama_confirmacion_birads45"
|
||||
SEMESTRES = [f"{a}-S{s}" for a in (2024, 2025, 2026) for s in (1, 2)]
|
||||
|
||||
|
||||
|
||||
+51
-18
@@ -4,13 +4,12 @@ import re
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from indicadores_kit.tea.etl import STAGING, lote_de_estudios
|
||||
from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging
|
||||
from indicadores_kit.tea.lecturas import AREA_TOTAL, MCHAT, RAMOS
|
||||
from indicadores_kit.tea.mapeo import LIGADO, ligar_eegs
|
||||
|
||||
from dev_data.azar import Azar
|
||||
from dev_data.tea.aspectos import Instrumento
|
||||
from dev_data.tea.filas import a_filas
|
||||
from dev_data.tea.filas import TABLAS, a_filas
|
||||
from dev_data.tea.historias import Historia, historias
|
||||
|
||||
HS = historias(200, Azar(7, date(2026, 1, 1)))
|
||||
@@ -26,9 +25,18 @@ def _columna(filas: list, nombre: str) -> list:
|
||||
return [getattr(f, nombre) for f in filas]
|
||||
|
||||
|
||||
# Cada tabla de `a_filas`, con el modelo de staging que lee la carga del kit (`plata.carga.tablas_de_staging`, T-20c).
|
||||
MODELOS = dict(zip(TABLAS, (
|
||||
"pacientes", "ordenes_estudio", "evaluacion_psicologica", "instrumento_aplicado", "eeg_estudio",
|
||||
"eeg_segmento", "potenciales_evocados_auditivos", "parto_neonatal", "antecedentes_maternos_gestacion", "nota_medica",
|
||||
)))
|
||||
STAGING = {clave: {m.__tablename__: m for m in tablas_de_staging("tea")}[tabla] for clave, tabla in MODELOS.items()}
|
||||
|
||||
|
||||
def test_las_claves_y_los_modelos_son_los_de_staging_del_kit():
|
||||
filas = a_filas(HS)
|
||||
assert list(filas) == list(STAGING)
|
||||
assert set(STAGING.values()) == set(tablas_de_staging("tea")) # todas las que lee la carga
|
||||
for clave, modelo in STAGING.items():
|
||||
assert all(isinstance(f, modelo) for f in filas[clave])
|
||||
|
||||
@@ -45,7 +53,8 @@ def test_los_conteos_coinciden_con_las_historias():
|
||||
"partos": sum(h.parto_apgar_5min is not None or h.parto_ingreso_ucin is not None for h in HS),
|
||||
"antecedentes": sum(h.antecedentes is not None for h in HS),
|
||||
"ordenes": sum(h.orden_eeg_fecha is not None for h in HS)
|
||||
+ sum(h.orden_evaluacion_fecha is not None for h in HS),
|
||||
+ sum(h.orden_evaluacion_fecha is not None for h in HS)
|
||||
+ sum(h.pea_fecha is not None for h in HS),
|
||||
"notas": sum(h.nota_fecha is not None for h in HS),
|
||||
}
|
||||
assert {k: len(v) for k, v in filas.items()} == esperado
|
||||
@@ -85,32 +94,56 @@ def test_dos_corridas_dan_las_mismas_filas_y_ninguna_llave_es_uuid():
|
||||
assert not any(UUID.fullmatch(str(v)) for v in _columna(a[tabla], llave)), llave
|
||||
|
||||
|
||||
def test_el_eeg_no_lleva_pac_id_y_trae_nacimiento_y_sexo_del_niño():
|
||||
assert "eeg_pac_id" not in STAGING["eegs"].model_fields
|
||||
def test_el_eeg_lleva_su_niño_y_su_orden_y_trae_nacimiento_y_sexo_del_archivo():
|
||||
"""T-22f: el responsable de TEA pidió ligar el EEG por llaves (`eeg_pac_id`, `eeg_ord_id`), como las demás tomas."""
|
||||
por_clave = {h.clave: h for h in HS}
|
||||
for eeg in a_filas(HS)["eegs"]:
|
||||
filas = a_filas(HS)
|
||||
pac_de = {p.pac_id_hospital: p.pac_id for p in filas["pacientes"]}
|
||||
ordenes = {o.ord_id: o for o in filas["ordenes"]}
|
||||
for eeg in filas["eegs"]:
|
||||
h = por_clave[eeg.eeg_id.removeprefix("eeg-")]
|
||||
assert eeg.eeg_pac_id == pac_de[h.clave]
|
||||
if h.orden_eeg_fecha is None:
|
||||
assert eeg.eeg_ord_id is None
|
||||
else:
|
||||
assert ordenes[eeg.eeg_ord_id].ord_pac_id == eeg.eeg_pac_id
|
||||
assert (eeg.eeg_fecha_nacimiento_archivo, eeg.eeg_sexo_archivo) == (h.nacimiento, h.sexo)
|
||||
assert (eeg.eeg_fecha_estudio, eeg.eeg_duracion_min, eeg.eeg_utilizable) == (
|
||||
h.eeg_fecha, h.eeg_duracion_min, h.eeg_utilizable)
|
||||
|
||||
|
||||
def test_ligar_eegs_liga_todos_con_el_niño_de_su_clave():
|
||||
def test_la_pea_y_la_evaluacion_llevan_su_orden():
|
||||
"""T-22g: una orden de PEA por cada PEA con fecha, con esa fecha; la evaluación apunta a la orden de evaluación."""
|
||||
por_clave = {h.clave: h for h in HS}
|
||||
filas = a_filas(HS)
|
||||
enlaces = ligar_eegs(filas["eegs"], filas["pacientes"], filas["ordenes"])
|
||||
pac_de = {p.pac_id_hospital: p.pac_id for p in filas["pacientes"]}
|
||||
assert len(enlaces) == len(filas["eegs"]) > 0
|
||||
for eeg_id, enlace in enlaces.items():
|
||||
assert enlace.estado == LIGADO
|
||||
assert enlace.pac_id == pac_de[eeg_id.removeprefix("eeg-")]
|
||||
ordenes = {o.ord_id: o for o in filas["ordenes"]}
|
||||
for pea in filas["peas"]:
|
||||
h = por_clave[pea.pea_id.removeprefix("pea-")]
|
||||
if h.pea_fecha is None:
|
||||
assert pea.pea_ord_id is None
|
||||
else:
|
||||
orden = ordenes[pea.pea_ord_id]
|
||||
assert (orden.ord_pac_id, orden.ord_fecha, orden.ord_tipo_estudio) == (
|
||||
pea.pea_pac_id, pea.pea_fecha_estudio, "POTENCIALES_EVOCADOS_AUDITIVOS")
|
||||
for psi in filas["evaluaciones"]:
|
||||
h = por_clave[psi.psi_id.removeprefix("psi-")]
|
||||
if h.orden_evaluacion_fecha is None:
|
||||
assert psi.psi_ord_id is None
|
||||
else:
|
||||
orden = ordenes[psi.psi_ord_id]
|
||||
assert (orden.ord_pac_id, orden.ord_tipo_estudio) == (psi.psi_pac_id, "EVALUACION_PSICOLOGICA_TEA")
|
||||
assert any(p.pea_ord_id for p in filas["peas"]) and any(p.psi_ord_id for p in filas["evaluaciones"])
|
||||
|
||||
|
||||
def test_el_kit_acepta_las_filas_sin_descartar_ni_fallar():
|
||||
"""Por la carga del staging directo (T-20c): cada fila (salvo los pacientes) da su procedimiento."""
|
||||
filas = a_filas(HS)
|
||||
lote = lote_de_estudios(**filas)
|
||||
assert lote.descartes == {}
|
||||
assert len(lote.hechos) == sum(len(v) for k, v in filas.items() if k != "pacientes")
|
||||
assert len(lote.personas) == len(filas["pacientes"])
|
||||
carga = carga_desde_staging({STAGING[k].__tablename__: v for k, v in filas.items()}, proyecto="tea")
|
||||
assert carga.plata.descartes == {}
|
||||
assert len(carga.personas) == len(filas["pacientes"])
|
||||
llaves = {(p["llave"][0], p["llave"][1]) for p in carga.plata.procedimientos}
|
||||
esperadas = {(STAGING[k].__tablename__, str(getattr(f, LLAVES[k]))) for k, v in filas.items() if k != "pacientes" for f in v}
|
||||
assert llaves == esperadas
|
||||
|
||||
|
||||
def test_una_historia_con_instrumentos_y_sin_evaluacion_es_un_error():
|
||||
|
||||
@@ -13,7 +13,7 @@ from core.tea.enums import (
|
||||
)
|
||||
from indicadores_kit.registry.parametros import valores_del_archivo
|
||||
from indicadores_kit.tea.lecturas import AREA_TOTAL, MCHAT, RAMOS
|
||||
from indicadores_kit.tea.mapeo import ANTECEDENTES_TAL_CUAL
|
||||
from indicadores_kit.tea.plata import ANTECEDENTES_TAL_CUAL
|
||||
|
||||
from dev_data.azar import Azar
|
||||
from dev_data.tea.aspectos import Antecedentes
|
||||
|
||||
+2
-61
@@ -1,9 +1,7 @@
|
||||
"""Liga de EEG con su niño: la orden de EEG de la historia resuelve las fechas de nacimiento repetidas (D-7, I-D2)."""
|
||||
"""El EEG y su orden en las historias (D-7). Desde T-22f el EEG lleva su niño y su orden (`eeg_pac_id`, `eeg_ord_id`)
|
||||
y el kit lo liga por esas llaves; la ligadura por fecha de nacimiento (I-D2) se retiró, y con ella sus pruebas."""
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from indicadores_kit.tea.mapeo import AMBIGUO, LIGADO, ligar_eegs
|
||||
|
||||
from dev_data.azar import Azar
|
||||
from dev_data.tea.historias import Historia, colisiones, historias
|
||||
@@ -24,30 +22,6 @@ def _historia(clave: str, nacimiento: date, eeg: date | None) -> Historia:
|
||||
)
|
||||
|
||||
|
||||
def _ligar(hs: list[Historia], con_ordenes: bool = True) -> dict:
|
||||
"""Arma pacientes, EEG y órdenes mínimos desde las historias y los liga con el kit."""
|
||||
pacientes = [SimpleNamespace(pac_id=i, pac_fecha_nacimiento=h.nacimiento) for i, h in enumerate(hs, start=1)]
|
||||
eegs = [
|
||||
SimpleNamespace(eeg_id=f"EEG-{i}", eeg_fecha_nacimiento_archivo=h.nacimiento, eeg_fecha_estudio=h.eeg_fecha)
|
||||
for i, h in enumerate(hs, start=1)
|
||||
if h.eeg_fecha is not None
|
||||
]
|
||||
ordenes = (
|
||||
[
|
||||
SimpleNamespace(
|
||||
ord_pac_id=i,
|
||||
ord_fecha_realizacion=h.orden_eeg_fecha,
|
||||
ord_tipo_estudio="ELECTROENCEFALOGRAMA",
|
||||
)
|
||||
for i, h in enumerate(hs, start=1)
|
||||
if h.orden_eeg_fecha is not None
|
||||
]
|
||||
if con_ordenes
|
||||
else []
|
||||
)
|
||||
return ligar_eegs(eegs, pacientes, ordenes)
|
||||
|
||||
|
||||
def test_el_orden_de_eeg_es_la_fecha_del_eeg_y_sin_eeg_no_hay_orden():
|
||||
hs = historias(200, Azar(7, REFERENCIA))
|
||||
assert any(h.eeg_fecha is not None for h in hs)
|
||||
@@ -74,36 +48,3 @@ def test_colisiones_es_cero_sin_nacimientos_repetidos():
|
||||
_historia("C", date(2024, 3, 1), None),
|
||||
]
|
||||
assert colisiones(hs) == 0
|
||||
|
||||
|
||||
def test_dos_ninos_con_mismo_nacimiento_y_eeg_en_fechas_distintas_quedan_ligados():
|
||||
hs = [
|
||||
_historia("A", NACIMIENTO_REPETIDO, date(2025, 3, 1)),
|
||||
_historia("B", NACIMIENTO_REPETIDO, date(2025, 4, 1)),
|
||||
]
|
||||
enlaces = _ligar(hs)
|
||||
assert enlaces["EEG-1"].estado == LIGADO
|
||||
assert enlaces["EEG-1"].pac_id == 1
|
||||
assert enlaces["EEG-2"].estado == LIGADO
|
||||
assert enlaces["EEG-2"].pac_id == 2
|
||||
|
||||
|
||||
def test_sin_ordenes_dos_ninos_con_mismo_nacimiento_quedan_ambiguos():
|
||||
hs = [
|
||||
_historia("A", NACIMIENTO_REPETIDO, date(2025, 3, 1)),
|
||||
_historia("B", NACIMIENTO_REPETIDO, date(2025, 4, 1)),
|
||||
]
|
||||
enlaces = _ligar(hs, con_ordenes=False)
|
||||
assert enlaces["EEG-1"].estado == AMBIGUO
|
||||
assert enlaces["EEG-2"].estado == AMBIGUO
|
||||
|
||||
|
||||
def test_dos_eeg_el_mismo_dia_con_nacimiento_repetido_siguen_ambiguos_aunque_haya_orden():
|
||||
# La orden desempata por (niño, fecha del estudio); si ambos niños tienen orden ese día, no desempata.
|
||||
hs = [
|
||||
_historia("A", NACIMIENTO_REPETIDO, date(2025, 3, 1)),
|
||||
_historia("B", NACIMIENTO_REPETIDO, date(2025, 3, 1)),
|
||||
]
|
||||
enlaces = _ligar(hs)
|
||||
assert enlaces["EEG-1"].estado == AMBIGUO
|
||||
assert enlaces["EEG-2"].estado == AMBIGUO
|
||||
|
||||
@@ -14,8 +14,7 @@ from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS as ALIAS_CAMA
|
||||
from core.cama.nota_medica.enums import Especialidad as EspecialidadCaMa
|
||||
from indicadores_kit.cacu.tablas import TABLAS as TABLAS_CACU
|
||||
from indicadores_kit.cama.tablas import TABLAS as TABLAS_CAMA
|
||||
from indicadores_kit.cdm.notas import cie
|
||||
from indicadores_kit.cdm.ordenes import codigo_de_especialidad
|
||||
from indicadores_kit.plata.valores import cie, codigo_de_especialidad
|
||||
from indicadores_kit.registry.parametros import valores_del_archivo
|
||||
from persistance.db import get_cacu_session, get_cama_session
|
||||
|
||||
|
||||
Reference in New Issue
Block a user