Compare commits

..

7 Commits

48 changed files with 581 additions and 2863 deletions
-1
View File
@@ -70,7 +70,6 @@ Los errores de la solicitud se responden con `{"error": "..."}` y código 400
| `INDICADORES_DESDE`, `INDICADORES_HASTA` | hace 5 años, este año | Años que recalcula el servicio |
| `INDICADORES_INTERVALO_S` | `20` | Cada cuánto revisa la cola |
| `INDICADORES_AL_INICIAR` | `1` | Recalcular los tres dominios al arrancar |
| `EEG_ANALYSIS_CLUSTER` | `auto` | Where TEA's cycle analyses the stored EDFs before loading silver: `auto` (`DASK_SCHEDULER_ADDRESS` if set, otherwise a local Dask cluster), `local`, `remote`, `sync` (in the service's own process) or `off` (only `python -m models tea analyze` and `POST /governance/eeg/run` analyse) |
| `PORT`, `WEBAPI_WORKERS`, `WEBAPI_TIMEOUT` | `5000`, `2`, `600` | gunicorn en el contenedor |
| `NOTEBOOK_JOBS_DIR` | sin carpeta | Carpeta compartida con el servicio `notebooks`; con ella los notebooks corren aislados en ese contenedor |
| `NOTEBOOK_EXECUTOR` | `contenedor` con `NOTEBOOK_JOBS_DIR`, si no `local` | Dónde corren los notebooks; `local` es en el propio proceso, sin aislar (desarrollo) |
+1 -5
View File
@@ -21,10 +21,6 @@ dependencies = [
"sqlglot>=25.0",
"rapidfuzz>=3.9",
"watchdog>=6.0",
# Every FHIR answer is validated against R4B's models before it leaves (`webapi.fhir.common`).
"fhir-resources>=8.3",
# The EEG quality checks' code system and interpretations in TEA's FHIR answers (`webapi.fhir.tea`, `webapi.fhir.terminology`).
"tea",
]
[project.optional-dependencies]
@@ -38,7 +34,6 @@ sql-drivers = [
persistance = { path = "../Persistance", editable = true }
models = { path = "../models", editable = true }
extraction = { path = "../Extraction", editable = true }
tea = { path = "../models/libs/tea", editable = true }
[build-system]
requires = ["hatchling"]
@@ -49,6 +44,7 @@ packages = ["webapi"]
[dependency-groups]
dev = [
"fhir-resources>=8",
"pytest>=8.0.0",
"reportlab>=4.0",
]
+26 -47
View File
@@ -17,8 +17,7 @@ with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first
step is dated by the note, so it reaches EEG on 2 Jun and leaves after June.
- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else.
Every EEG's verdict and quality checks are written as its analysis would: a good EEG has its study-wide checks
within their limits; a bad one has too few clean windows and a dead channel (T3).
Every EEG's quality criteria are written as its analysis would; a bad EEG has one criterion out of its threshold.
Test support: writes in the session it's given, never in the domain's database.
"""
@@ -28,7 +27,6 @@ from datetime import date
from core.tea.models import (
Ados2,
Eeg,
EegCriterio,
EegMetrica,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
@@ -77,22 +75,10 @@ NOTAS = (
(6, date(2025, 6, 2), "F84.0"),
)
# The analysis's verdict, triage level, clean fraction, bad channels and line noise, and its checks:
# (code, electrode, value, text, unit, low, high, decisive, abnormal).
GOOD = {"valido": 1, "nivel": "completo", "limpia": 0.95, "malos": 0, "linea": 3.5, "criterios": (
("clean-windows", None, 95.0, None, "%", 60.0, None, 1, 0),
("usable-scalp", None, 19.0, None, "electrodes", 12.0, None, 1, 0),
("triage-level", None, None, "completo", None, None, None, 1, 0),
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
)}
BAD = {"valido": 0, "nivel": "parcial", "limpia": 0.4, "malos": 1, "linea": 3.5, "criterios": (
("dead-channel", "T3", None, "dead channel", None, None, None, 0, 1),
("clean-windows", None, 40.0, None, "%", 60.0, None, 1, 1),
("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, 1, 0),
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
)}
GOOD = {"amplitud": 0, "alta_frecuencia": 1, "correlacion": 0, "sin_senal": 0, "linea": 3.5}
BAD = {**GOOD, "sin_senal": 5}
# (eeg id, pac_id, date, laboratory id, analysis, with sleep)
# (eeg id, pac_id, date, laboratory id, criteria, with sleep)
EEGS = (
("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0),
("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1),
@@ -101,32 +87,30 @@ EEGS = (
("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1),
)
# (metric id, eeg id, code, value, deviation): a null value can't be evaluated. The deviation is the analysis's
# against the metric's age baseline: (z, -1/0/+1, p5, median, p95). Child 1's slow posterior rhythm is below p5.
# (metric id, eeg id, code, value): a null value can't be evaluated.
METRICAS = (
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2, (-4.08, -1, 4.5, 5.75, 7.0)),
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0, (-0.5, 0, 2.5, 4.5, 6.5)),
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4, (-0.4, 0, 0.0, 0.5, 1.0)),
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0, (-6.0, -1, 4.5, 5.75, 7.0)),
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5, (0.4, 0, 5.0, 6.25, 7.5)),
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None, (None, None, None, None, None)),
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6, (0.27, 0, 1.75, 2.5, 3.25)),
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2),
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0),
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4),
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0),
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5),
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None),
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6),
)
# (electrode value id, metric id, electrode, value, z-score)
# (electrode value id, metric id, electrode, z-score)
ELECTRODOS = (
("mel-1", "met-1b-rp", "O1", 3.0, -2.8),
("mel-2", "met-1b-rp", "O2", 3.1, -2.4),
("mel-3", "met-1b-rp", "Pz", 3.6, -1.1),
("mel-1", "met-1b-rp", "O1", -2.8),
("mel-2", "met-1b-rp", "O2", -2.4),
("mel-3", "met-1b-rp", "Pz", -1.1),
)
# The EEG of child 1 that completes the chain hangs from an order.
ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),)
ORDEN_DE = {"eeg-1b": "ord-1b"}
# What the load gives (`test_orquestacion_plata`): a bad channel is a part of its EEG, as an electrode value is.
CANALES_MALOS = sum(1 for *_, analisis, _ in EEGS for c in analisis["criterios"] if c[1] is not None)
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS) + CANALES_MALOS
# What the load gives (`test_orquestacion_plata`).
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS)
def insertar(sesion: Session) -> None:
@@ -142,19 +126,14 @@ def insertar(sesion: Session) -> None:
ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items))
sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c)
for k, (p, f, c) in enumerate(NOTAS, 1))
for i, p, f, lab, analisis, sueno in EEGS:
for i, p, f, lab, criterios, sueno in EEGS:
sesion.add(Eeg(
eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i),
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=analisis["valido"],
eeg_nivel=analisis["nivel"], eeg_fraccion_limpia=analisis["limpia"], eeg_canales_malos=analisis["malos"],
eeg_ruido_linea_db=analisis["linea"],
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0,
eeg_canales_amplitud=criterios["amplitud"], eeg_canales_alta_frecuencia=criterios["alta_frecuencia"],
eeg_canales_correlacion=criterios["correlacion"], eeg_canales_sin_senal=criterios["sin_senal"],
eeg_ruido_linea_db=criterios["linea"],
))
sesion.add_all(EegCriterio(cri_id=f"cri-{i}-{k}", cri_eeg_id=i, cri_codigo=c, cri_electrodo=e, cri_valor=v,
cri_valor_texto=t, cri_unidad=u, cri_bajo=lo, cri_alto=hi, cri_decisivo=d,
cri_anormal=a)
for k, (c, e, v, t, u, lo, hi, d, a) in enumerate(analisis["criterios"], 1))
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v, met_z=z, met_fuera=fuera, met_p5=p5,
met_mediana=mediana, met_p95=p95)
for i, e, c, v, (z, fuera, p5, mediana, p95) in METRICAS)
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v, mel_z=z)
for i, m, e, v, z in ELECTRODOS)
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v) for i, e, c, v in METRICAS)
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v)
for i, m, e, v in ELECTRODOS)
-213
View File
@@ -1,213 +0,0 @@
"""What this module covers: the publication metadata of CaCu's FHIR `Measure`s (figures, category captions and the
optional category groups) read from dbt's manifest alone, and the checks that keep a composition's groups consistent.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
reference parameters, whose CaCu catalogs and lists hold the captions, colours and memberships the dbt definitions
repeat; Transformation's `dbt_project.yml` next to the manifest, whose variables repeat the same lists.
"""
import os
import tomllib
from datetime import date, datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import pytest
from fhir.resources.R4B import get_fhir_model_class
from webapi.compositions import CompositionAnswer, InvalidCategoryGroups, category_groups
from webapi.fhir.measures import CATEGORY_GROUP, CATEGORY_LABEL, FIGURES, labels, measure_report, measure_resource
from webapi.kpis import definitions_of
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
GROUPED = {"CACU-EU7": "citologia_anomala", "CACU-CONFIRMACION-CITOLOGIA": "deteccion_grados"}
@pytest.fixture(scope="module")
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
def _measures(domain: str, manifest: Path) -> dict[str, dict]:
titles = labels(manifest)
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
for d in definitions_of(domain, manifest).values()}
@pytest.fixture(scope="module")
def measures(manifest):
"""Each CaCu measure as the API serves it, by its FHIR id."""
return _measures("cacu", manifest)
def reference(*keys: str):
with REFERENCE.open("rb") as f:
node = tomllib.load(f)
for key in keys:
node = node[key]
return node["valor"]
def figures(measure: dict) -> list[str]:
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
def categories(measure: dict) -> dict[str, dict[str, str]]:
"""The measure's declared categories, in order: code -> its parts (etiqueta, color and, if any, grupo)."""
return {part["codigo"]: part for part in (
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
for e in measure["extension"] if e["url"] == CATEGORY_LABEL)}
def groups(measure: dict) -> dict[str, str]:
"""The measure's category groups, in order: code -> caption."""
return {part["codigo"]: part["etiqueta"] for part in (
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
for e in measure["extension"] if e["url"] == CATEGORY_GROUP)}
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
"""Pins down: the two distributions offer the donut and the bars and the two durations their box plot; the C1
proportions and the risk bands none, because no figure is approved for them yet. Fails if a figure is declared
that the page has no builder for, or one is dropped."""
assert {i: figures(m) for i, m in measures.items()} == {
"CACU-EU7": ["fig_c2_donas", "fig_c2_barras"], "CACU-CONFIRMACION-CITOLOGIA": ["fig_c2_donas", "fig_c2_barras"],
"CACU-EU-TIEMPO-REPORTE": ["fig_c3r_caja"], "CACU-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-EU13": [], "IND1": [], "CACU-RIESGO-BANDA": []}
def test_the_category_captions_are_the_reference_catalogs(measures):
"""Pins down: the captions, colours and order of the cytology distribution equal `cacu.catalogos.citologia` plus
`cacu.catalogos.sin_dato`, and the confirmation's grades `cacu.catalogos.biopsia`. Fails if either side is edited
without the other."""
sin_dato = reference("cacu", "catalogos", "sin_dato")
citologia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "citologia")}
eu7 = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-EU7"]).items()}
assert eu7 == {**citologia, "SIN_DATO": (sin_dato["etiqueta"], sin_dato["color"])}
biopsia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "biopsia")}
confirmacion = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-CONFIRMACION-CITOLOGIA"]).items()}
assert list(confirmacion)[:len(biopsia)] == list(biopsia)
assert {c: confirmacion[c] for c in biopsia} == biopsia
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
def test_the_anomalous_group_is_the_reference_list(measures, manifest, fhir_id):
"""Pins down: a grouped composition's ANORMAL members are exactly the parameter list the grouping is defined by
(`cacu.citologia_anomala` for EU7, `cacu.deteccion_grados` for the confirmation) and the dbt variable of the same
name; the other declared categories are NO_ANORMAL, «Sin dato» its own group and «Sin biopsia aún» none. Fails if
a membership drifts from the lists the measures count with."""
yaml = pytest.importorskip("yaml")
lista = GROUPED[fhir_id]
project = manifest.parent.parent / "dbt_project.yml"
dbt_vars = yaml.safe_load(project.read_text(encoding="utf-8"))["vars"] if project.exists() else None
parts = categories(measures[fhir_id])
anomalous = sorted(c for c, p in parts.items() if p.get("grupo") == "ANORMAL")
assert anomalous == sorted(reference("cacu", lista))
if dbt_vars is not None:
assert anomalous == sorted(dbt_vars[lista])
assert all(p.get("grupo") == "NO_ANORMAL" for c, p in parts.items()
if c not in anomalous and c not in ("SIN_DATO", "SIN_BIOPSIA"))
assert parts["SIN_DATO"]["grupo"] == "SIN_DATO"
assert "grupo" not in parts.get("SIN_BIOPSIA", {})
def test_the_group_captions_are_the_reference_ones(measures):
"""Pins down: EU7's groups are `cacu.catalogos.resultado_anormal` plus «Sin dato», and the confirmation's
«Menor que LIEAG» / «LIEAG o más» plus its no-data category's caption, in that order. Fails if a caption drifts."""
resultado = {e["clave"]: e["etiqueta"] for e in reference("cacu", "catalogos", "resultado_anormal")}
assert groups(measures["CACU-EU7"]) == {**resultado, "SIN_DATO": "Sin dato"}
assert groups(measures["CACU-CONFIRMACION-CITOLOGIA"]) == {
"NO_ANORMAL": "Menor que LIEAG", "ANORMAL": "LIEAG o más", "SIN_DATO": "Biopsia sin grado"}
def test_measures_without_groups_publish_none(manifest, measures):
"""Pins down: groups are opt-in. CaCu's other measures and every CaMa and TEA measure publish neither a
`categoria-grupo` nor a `grupo` inside a category. Fails if the new extensions leak onto measures that don't
declare them (their clients see exactly what they see without groups)."""
others = {**{i: m for i, m in measures.items() if i not in GROUPED},
**_measures("cama", manifest), **_measures("tea", manifest)}
for fhir_id, measure in others.items():
assert not groups(measure), fhir_id
assert all("grupo" not in part for part in categories(measure).values()), fhir_id
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
def test_a_grouped_measure_is_valid_fhir_r4b(measures, fhir_id):
"""Pins down: the nested `grupo` and the `categoria-grupo` extensions keep the Measure valid FHIR R4B. Fails if
the extensions are shaped in a way FHIR's models reject."""
get_fhir_model_class("Measure").model_validate(measures[fhir_id])
def test_a_composite_stratum_carries_its_caption(manifest):
"""Pins down: in a composition's report, a stratum value of a crossed stratifier (status by result) carries the
caption of `meta.etiquetas_estrato` as its display, and a value without one (an age group) keeps the code alone.
Fails if the captions stop reaching the report or start replacing codes."""
definition = next(d for d in definitions_of("cacu", manifest).values() if d.measure_id == "CACU_EU7")
result = CompositionAnswer(report_id=1, categories={"NORMAL": 2, "ASC-US": 1}, stored_before=True, strata={
"estatus_seguimiento": {"PRE_COLPOSCOPIA": {"NORMAL": 2}, "POST_COLPOSCOPIA": {"ASC-US": 1}},
"grupo_edad": {"25-34": {"NORMAL": 2, "ASC-US": 1}}})
question = SimpleNamespace(event_cutoff=None, knowledge_cutoff=None)
period = SimpleNamespace(inicio=date(2025, 7, 1), fin=date(2026, 1, 1))
report = measure_report(definition, question, result, period, datetime(2026, 1, 2, tzinfo=timezone.utc))
shown = {}
for stratifier in report["group"][0]["stratifier"][1:]:
for stratum in stratifier["stratum"]:
value = stratum["component"][0]["value"]["coding"][0]
shown[value["code"]] = value.get("display")
assert shown == {"PRE_COLPOSCOPIA": "Pre colposcopia", "POST_COLPOSCOPIA": "Post colposcopia", "25-34": None}
get_fhir_model_class("MeasureReport").model_validate(report)
RULE = {"sin_dato": "SIN_DATO", "etiquetas": {
"A": {"etiqueta": "A", "color": "#000000", "grupo": "G1"}, "B": {"etiqueta": "B", "color": "#000000", "grupo": "G2"},
"APARTE": {"etiqueta": "Aparte", "color": "#000000"},
"SIN_DATO": {"etiqueta": "Sin dato", "color": "#000000", "grupo": "SIN_DATO"}},
"grupos": {"G1": "Uno", "G2": "Dos", "SIN_DATO": "Sin dato"}}
def _with(**changes) -> dict:
rule = {**RULE, "etiquetas": {k: dict(v) for k, v in RULE["etiquetas"].items()}, "grupos": dict(RULE["grupos"])}
for path, value in changes.items():
*parents, last = path.split("__")
node = rule
for p in parents:
node = node[p]
if value is None:
node.pop(last, None)
else:
node[last] = value
return rule
def test_valid_groups_are_returned_in_order_and_a_category_may_stay_apart():
"""Pins down: declared and used groups come back in their declared order, and a category without `grupo` (one kept
apart) is allowed. Fails if a valid declaration is rejected or reordered."""
assert list(category_groups("x", RULE).items()) == [("G1", "Uno"), ("G2", "Dos"), ("SIN_DATO", "Sin dato")]
def test_a_composition_without_groups_has_none():
"""Pins down: groups are optional; neither `grupos` nor any `grupo` means none. Fails if declaring groups becomes
mandatory (CaMa's and TEA's compositions declare none)."""
rule = {k: v for k, v in RULE.items() if k != "grupos"}
rule["etiquetas"] = {c: {k: v for k, v in s.items() if k != "grupo"} for c, s in RULE["etiquetas"].items()}
assert category_groups("x", rule) == {}
@pytest.mark.parametrize("rule, message", [
(_with(grupos=None), "`grupos` is missing"),
(_with(etiquetas__A__grupo="G9"), "undeclared groups"),
(_with(grupos__G3="Tres"), "groups without categories"),
(_with(grupos__G1=" "), "non-empty caption"),
(_with(etiquetas__SIN_DATO__grupo="G1", grupos__SIN_DATO=None), "goes alone"),
(_with(etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "goes alone"),
(_with(etiquetas__SIN_DATO__grupo=None, etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "no-data category's own"),
])
def test_invalid_groups_fail_the_load(rule, message):
"""Pins down: each way a declaration can't be read as a partition fails with its reason (a group named but
missing, one declared but unused, an empty caption, the no-data category mixed with others or without its own
group). Fails if one of them is accepted, because the page would draw a wrong or incomplete grouping."""
with pytest.raises(InvalidCategoryGroups, match=message):
category_groups("x", rule)
+55 -4
View File
@@ -8,6 +8,7 @@ invented patients with the cases below; their names (`P01`...) are the source id
Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6):
BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day.
P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it.
No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some.
"""
import json
@@ -151,14 +152,16 @@ def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app):
"""Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data
doesn't support is added, or the hospital's identifier leaks."""
date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body.
Fails if a column the data doesn't support is added, or the hospital's identifier leaks."""
respuesta = get(app, page_size=200)
cuerpo = respuesta.get_json()
assert cuerpo["simulado"] is True
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"])
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
"escenario_clinico"} for i in cuerpo["items"])
assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"}
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"]
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
assert respuesta.headers["Cache-Control"] == "no-store"
@@ -368,3 +371,51 @@ def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_
with Session(base.motor) as sesion:
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")]
@pytest.fixture
def con_postratamiento(tmp_path):
"""The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on
2025-11-01 and P06 on 2026-01-15, after the cut-off."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
from sqlalchemy import text
base = base_de("cama", tmp_path, datos=insertar)
base.run(*UNTIL_MODELS, allow_undecided=True)
hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"}
with base.motor.begin() as c:
for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"):
try:
with c.begin_nested():
c.execute(text(drop))
except Exception:
pass
c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)"))
for hospital, fecha in hechos.items():
c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente "
"where pac_id_hospital = :h"), {"f": fecha, "h": hospital})
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
yield base, flask.test_client()
base.motor.dispose()
def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento):
"""Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the
cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it
and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from
something other than the timeline, or if the filter stops being offered."""
base, app = con_postratamiento
nombres = hospital_de(base)
escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"]
for i in get(app, corte=corte, page_size=200).get_json()["items"]}
al_corte = escenario(CORTE)
assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"}
assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"}
assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO"
filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200)
assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"}
filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico")
assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"},
{"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}]
+78
View File
@@ -0,0 +1,78 @@
"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`,
rules in `cama.escenarios`): post-treatment from a discharge note after a malignant breast tumour's diagnosis, carried by
her timeline as an `escenario_postratamiento` fact with the evidence that started it; every other patient is under
observation ("en observación"), which has no fact.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30,
H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30),
H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a
type: the tests that need a discharge write `nota_medica.tipo_nota` themselves.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture
def base(tmp_path, manifest):
base = base_de("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
yield base
base.motor.dispose()
def scenarios(base) -> dict[str, set[tuple[str, date, str]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence)."""
with base.motor.connect() as con:
rows = con.execute(text(
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l "
"join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all()
found: dict[str, set[tuple[str, date, str]]] = {}
for r in rows:
found.setdefault(r.pac_id_hospital, set()).add((r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo))
return found
def discharge(base, hospital_id: str) -> None:
"""Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would."""
with base.motor.begin() as con:
con.execute(text(
"insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) "
"select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' "
"from procedimiento p join paciente x on x.pac_id = p.pac_id "
"where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id})
def test_without_a_discharge_every_patient_is_under_observation(base):
"""Pins down: a mammogram, a malignant ICD-10 note (H-003, H-102, H-103) or an invasive biopsy (H-003) alone start
no scenario: with no discharge note nobody is in post-treatment and the timeline has no scenario fact, which reads as
under observation. Fails if screening or a diagnosis go back to being scenarios of their own."""
assert scenarios(base) == {}
def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base):
"""Pins down: a discharge note that carries a malignant tumour's ICD-10 puts H-003 in post-treatment from its date,
and only her. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops reading the note's type."""
discharge(base, "H-003")
assert scenarios(base) == {"H-003": {("escenario_postratamiento", date(2025, 8, 4), "egreso")}}
def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base):
"""Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her
under observation: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it."""
discharge(base, "H-101")
assert scenarios(base) == {}
+31 -60
View File
@@ -1,13 +1,13 @@
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
labels a timeline stratum's values carry into FHIR.
"""What this module covers: CaMa's tumour characteristics read from reports. dbt's `cama_estratificadores` (stage
group, early or advanced stage, T by size) as timeline facts; that no measure is served by clinical stage or tumour
size; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into FHIR.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
2025-07-28 from her BI-RADS 4A mammogram (14 mm), and a note of 2025-08-04 with stage IIA.
"""
import json
import os
from dataclasses import replace
from datetime import date
@@ -20,7 +20,7 @@ from webapi.compositions import answer_composition, composition_definitions
from webapi.fhir.measures import _label
from webapi.metrics import Question
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
BIRADS = "cama/CAMA_BIRADS_CANCER_INVASOR"
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
@@ -40,72 +40,43 @@ def base(tmp_path, sin_supresion, manifest):
base.motor.dispose()
def answered(base, manifest, period: str, event_cutoff: date | None = None):
def answered(base, manifest, url: str, period: str, event_cutoff: date | None = None):
d = base.dominio
definition = composition_definitions(manifest)[URL]
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
definition = composition_definitions(manifest)[url]
return answer_composition("cama", definition, Question(url, period, event_cutoff=event_cutoff),
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
def stratifiers(base) -> set[str]:
def stratifiers(base, manifest) -> set[str]:
"""The stratifiers' `tipo`s, from the view built here: no served measure reads it, so the cycle doesn't."""
node = next(n for n in json.loads(manifest.read_text(encoding="utf-8"))["nodes"].values()
if n["resource_type"] == "model" and n["name"] == "cama_estratificadores")
with base.motor.connect() as con:
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
return set(con.execute(text(f"select tipo from ({node['compiled_code']}) e")).scalars())
def test_the_stratifiers_come_from_h003_s_reports(base):
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
def test_the_stratifiers_come_from_h003_s_reports(base, manifest):
"""Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and
nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads
changes, or a subtype comes back."""
assert stratifiers(base, manifest) == {"estadio_ii", "etapa_temprana", "tamano_t1"}
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
category or a stratum's values drift."""
assert answered(base, manifest, "2025-S1").categories == {}
result = answered(base, manifest, "2025-S2")
assert result.categories == {"B4A": 1}
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
"tamano": {"T1": {"B4A": 1}}}
def test_no_measure_is_served_by_stage_or_tumour_size(manifest):
"""Pins down: clinical stage and tumour size aren't served as measures; they come from reports read by text, not
yet validated. Fails if a measure on them is published again."""
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
urls = {m["config"].get("meta", {}).get("measure_url") for m in metrics} - {None}
assert BIRADS in urls and BIRADS in composition_definitions(manifest)
assert not {u for u in urls if "ESTADIO" in u or "TAMANO" in u}
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
SUBTIPOS = [
({"her2": "H3"}, "subtipo_her2"),
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
({"her2": "H0", "ki67_pct": None}, None),
({"her2": "H2"}, None),
]
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
valores = {"receptor_progesterona": "POSITIVO", **cambios}
with base.motor.begin() as con:
for nombre, valor in valores.items():
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
{"v": valor, "r": f"biopsia.{nombre}"})
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest):
"""Pins down: the BI-RADS of the mammogram before an invasive cancer isn't broken down by the tumour's
characteristics, which describe the cancer and not that mammogram. Fails if tumour strata come back."""
result = answered(base, manifest, BIRADS, "2025-S2")
assert (result.categories, result.strata) == ({"B4A": 1}, {})
def test_a_timeline_stratum_s_values_carry_their_labels():
+62
View File
@@ -0,0 +1,62 @@
"""What this module covers: a patient's date of death, from staging (`paciente.pac_fecha_defuncion`) to silver's
`persona.fecha_defuncion` in CaCu and CaMa, and in CaMa onto her timeline as a `defuncion` fact next to her birth.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base_con_defuncion`, the domain's
fixture database (`staging/<domain>.py`) with one patient given a date of death before it's loaded.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
DEATH = date(2026, 2, 1)
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
def with_death(domain: str, tmp_path):
"""The domain's fixture database with its first patient (lowest `pac_id`) dead on `DEATH`, loaded to silver."""
base = base_de(domain, tmp_path)
with base.motor.begin() as con:
con.execute(text("update paciente set pac_fecha_defuncion = :d where pac_id = (select min(pac_id) from paciente)"),
{"d": DEATH})
return base
@pytest.mark.parametrize("domain", ["cacu", "cama"])
def test_silver_persona_carries_the_date_of_death(domain, tmp_path, manifest):
"""Pins down: the dead patient's `persona` has her date of death and everyone else's is null. Fails if the
staging-to-silver copy (`persons.de_derechohabiente`) stops carrying `pac_fecha_defuncion`."""
base = with_death(domain, tmp_path)
base.run("catalogs", "load")
with base.motor.connect() as con:
rows = con.execute(text("select pac_id, fecha_defuncion from persona order by pac_id")).all()
base.motor.dispose()
assert [date.fromisoformat(str(rows[0].fecha_defuncion)[:10])] + [r.fecha_defuncion for r in rows[1:]] \
== [DEATH] + [None] * (len(rows) - 1)
def test_cama_timeline_has_birth_for_everyone_and_death_for_the_dead(tmp_path, manifest):
"""Pins down: every CaMa patient has a `nacimiento` fact and only the dead one a `defuncion` fact, on her date of
death, with class `persona`. Fails if the timeline stops reading `persona` or reads a null date as a death."""
base = with_death("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
with base.motor.connect() as con:
people = con.execute(text("select count(*) from persona")).scalar_one()
facts = con.execute(text(
"select tipo, pac_id, fecha, clase from cama_linea_de_tiempo where tipo in ('nacimiento', 'defuncion')")).all()
first = con.execute(text("select min(pac_id) from persona")).scalar_one()
base.motor.dispose()
assert sum(f.tipo == "nacimiento" for f in facts) == people
assert [(f.pac_id, date.fromisoformat(str(f.fecha)[:10]), f.clase) for f in facts if f.tipo == "defuncion"] \
== [(first, DEATH, "persona")]
-118
View File
@@ -1,118 +0,0 @@
"""What this module covers: the cycle's `analyze_eeg` step (TEA's EEG analysis before the silver load) and how the
cycle gets its analysis (`webapi.orchestration.eeg`).
Fixtures: `tea_base`, a migrated TEA database (`base_de`) holding one patient (`pac_id` 1, born 2024-01-01) and one
EEG `e-1` with an EDF and no analysis; `fake_analysis`, an analysis that writes sleep and 21 channels on `e-1`, as
the real one would, and notes whether a silver load existed when it ran.
"""
from datetime import date
import pytest
from hamilton import driver
from sqlmodel import Session, select
from models.eeg_analysis import Summary
from webapi.orchestration import cycle, run, steps_of
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import CLUSTER_ENV, live_eeg_analysis
def _rows(sesion):
from core.tea.models import Eeg, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2024, 1, 1)))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_id_registro_laboratorio="LAB-1", eeg_fecha_estudio=date(2025, 6, 1),
eeg_estudio=b"edf"))
@pytest.fixture
def tea_base(tmp_path):
"""Patient 1 and EEG `e-1` (an EDF, nothing analysed) in a migrated TEA database."""
from conftest import base_de
base = base_de("tea", tmp_path, datos=_rows)
yield base
base.motor.dispose()
@pytest.fixture
def fake_analysis(tea_base):
"""Writes `eeg_con_sueno` 1 and `eeg_canales` 21 on `e-1`; `calls` records the loads that existed at each call."""
from core.tea.indicadores.models import Carga
from core.tea.models import Eeg
calls = []
def analysis():
with Session(tea_base.motor) as sesion:
calls.append(len(sesion.exec(select(Carga)).all()))
eeg = sesion.get(Eeg, "e-1")
eeg.eeg_con_sueno, eeg.eeg_canales = 1, 21
sesion.add(eeg)
sesion.commit()
return Summary(pending=1, valid=1, not_valid=0, failed=0)
analysis.calls = calls
return analysis
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_the_eeg_analysis_runs_before_the_silver_load(proyecto):
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema.
Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up
only on the next cycle), or the analysis starts waiting for steps it doesn't need.
"""
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
assert "analyze_eeg" in deps["load"]
assert deps["analyze_eeg"] == {"migrate"}
order = steps_of(proyecto)
assert order.index("analyze_eeg") < order.index("load")
def test_without_an_analysis_the_step_does_nothing():
"""Pins down: a context without `eeg_analysis` (CaCu, CaMa, the tests' cycles) makes the step a no-op.
Fails if the step starts running an analysis nobody configured.
"""
pasos = run(Context("cacu", 2025, 2025), only=["analyze_eeg"])
assert [(p.name, p.summary) for p in pasos] == [("analyze_eeg", {})]
def test_what_the_analysis_writes_is_loaded_by_the_same_cycle(tea_base, fake_analysis):
"""Pins down: the cycle runs the analysis once, before any silver load, and `load` then carries what it wrote
into the EEG's silver observations.
Fails if the analysis runs after `load` or more than once, or its summary stops being the step's.
"""
from core.tea.indicadores.models import Observacion, Procedimiento
pasos = tea_base.run("analyze_eeg", "catalogs", "load", eeg_analysis=fake_analysis)
assert pasos["analyze_eeg"] == {"pending": 1, "valid": 1, "not_valid": 0, "failed": 0}
assert fake_analysis.calls == [0]
with Session(tea_base.motor) as sesion:
toma = sesion.exec(select(Procedimiento).where(Procedimiento.estudio_id == "eeg",
Procedimiento.clase == "toma")).one()
valores = {o.resultado_id: o.valor_numerico for o in sesion.exec(
select(Observacion).where(Observacion.procedimiento_id == toma.procedimiento_id))}
assert valores["eeg.canales"] == 21
def test_only_tea_has_an_analysis_and_it_can_be_turned_off(monkeypatch):
"""Pins down: TEA's cycle gets the analysis, with the cluster `EEG_ANALYSIS_CLUSTER` names; the other domains
get none, `off` leaves it out, and an unknown value is refused.
Fails if another domain starts analysing EEGs, `off` stops leaving the analysis out, or a mistyped cluster is
silently taken as the default.
"""
monkeypatch.delenv(CLUSTER_ENV, raising=False)
assert live_eeg_analysis("tea").keywords == {"cluster": "auto"}
assert live_eeg_analysis("cacu") is None
monkeypatch.setenv(CLUSTER_ENV, "sync")
assert live_eeg_analysis("tea").keywords == {"cluster": "sync"}
monkeypatch.setenv(CLUSTER_ENV, "off")
assert live_eeg_analysis("tea") is None
monkeypatch.setenv(CLUSTER_ENV, "everywhere")
with pytest.raises(ValueError, match=CLUSTER_ENV):
live_eeg_analysis("tea")
+1 -1
View File
@@ -125,7 +125,7 @@ def test_a_pathology_pdf_s_text_layer_gives_its_results():
going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor."""
leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1])))
assert {r: v for r, (v, _) in leido.items()} == {
"biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2",
"biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2",
"biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0,
"biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0,
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0,
-291
View File
@@ -1,291 +0,0 @@
"""What this module covers: the EEG metrics' age-norm curves in TEA's FHIR answers — how `BaselineCurves`
(`webapi.fhir.eeg_curves`) resolves the baseline label the analysis pinned (`eeg_metrica.met_modelo`,
`tea-<scenario>/<version>`, carried by `tea_paciente_eeg_metricas` as `modelo`) to its registered artifact's centile
curve, caching per label and omitting the curve on any failure; and how `webapi.fhir.tea` serves it: the curve as a
nested extension on each metric observation (`fuente`, `estado` tied to `TEA_ALTERACIONES_VALIDADAS`, then the
series) and the analysis's age (`eeg.eeg_edad_meses`) as an extension on the EEG's `DiagnosticReport`.
Fixtures: fakes for the registry, the module loader and the curve loader (no model registry is touched); `loaded`,
a TEA database (`base_de`) with one child and one analysed EEG whose posterior rhythm names a baseline, loaded
through the cycle up to `event_models`; needs `DBT_MANIFEST`.
"""
import os
from datetime import date
from types import SimpleNamespace
import pandas as pd
import pytest
from fhir.resources.R4B import get_fhir_model_class
from webapi.fhir import tea
from webapi.fhir.eeg_curves import BaselineCurves
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
CURVE = {"edad_meses": [16.0, 24.0, 36.0], "p5": [4.0, 5.0, 6.0], "p25": [4.5, 5.5, 6.5],
"mediana": [5.0, 6.0, 7.0], "p75": [5.5, 6.5, 7.5], "p95": [6.0, 7.0, 8.0]}
LABEL = "tea-eeg-posterior-rhythm/3"
class FakeRegistry:
"""Stands in for `models.io.registry.registry`: records the resolutions and answers or fails them."""
def __init__(self, error: Exception | None = None):
self.calls: list[tuple[str, str, str]] = []
self._error = error
def resolve(self, domain: str, scenario: str, version: str):
self.calls.append((domain, scenario, version))
if self._error is not None:
raise self._error
return SimpleNamespace(model_uri=f"models:/{domain}-{scenario}/{version}")
def module_with(curva: pd.DataFrame | None):
"""A loaded biomarker module as `models.tea.eeg.baselines` reads it: one baseline, maybe with a curve."""
return SimpleNamespace(baseline=SimpleNamespace(curva=curva))
class FakeCurves:
"""Stands in for `BaselineCurves` at the FHIR layer: answers per (label, metric), records what was asked."""
def __init__(self, curves: dict):
self._curves = curves
self.calls: list[tuple[str, str]] = []
def curve(self, label: str, metric: str):
self.calls.append((label, metric))
return self._curves.get((label, metric))
def test_the_label_resolves_to_the_pinned_version_s_curve():
"""Pins down: `curve(label, metric)` resolves the label to (domain, scenario, version), loads that version's
module and returns its baseline's centiles with the ages and the five percentiles. Fails if the label parsing,
the resolution arguments or the series extraction drift from `eeg_metrica.met_modelo`'s shape."""
registry = FakeRegistry()
loads: list[str] = []
curves = BaselineCurves(registry=registry, loader=lambda uri: loads.append(uri) or module_with(pd.DataFrame({
"edad_meses": CURVE["edad_meses"], "n_efectivo": [50.0, 60.0, 40.0],
**{p: CURVE[p] for p in ("p5", "p25", "mediana", "p75", "p95")}})))
assert curves.curve(LABEL, "ritmo_posterior") == CURVE
assert registry.calls == [("tea", "eeg-posterior-rhythm", "3")]
assert loads == ["models:/tea-eeg-posterior-rhythm/3"]
def test_the_module_loads_once_per_label():
"""Pins down: repeated asks of one curve reuse the module loaded for its label instead of reloading it, and a
second label loads its own. Fails if the caching moves from per label to per call."""
registry = FakeRegistry()
loads: list[str] = []
frame = pd.DataFrame(CURVE)
curves = BaselineCurves(registry=registry, loader=lambda uri: loads.append(uri) or module_with(frame))
n2 = "tea-eeg-spindles-n2/2"
first = curves.curve(n2, "husos_sueno_n2")
assert curves.curve(n2, "husos_sueno_n2") is first
assert curves.curve("tea-eeg-spindles-n3/1", "husos_sueno_n3") == CURVE
assert loads == ["models:/tea-eeg-spindles-n2/2", "models:/tea-eeg-spindles-n3/1"]
assert registry.calls == [("tea", "eeg-spindles-n2", "2"), ("tea", "eeg-spindles-n3", "1")]
def test_a_multi_scenario_label_uses_the_metric_s_own_scenario():
"""Pins down: a label that joined the electrode baseline's name (`;`-separated, as the analysis writes when it
also scored electrodes) resolves the metric's own scenario. Fails if the split or the scenario match breaks."""
registry = FakeRegistry()
curves = BaselineCurves(registry=registry, loader=lambda uri: module_with(pd.DataFrame(CURVE)))
label = "tea-eeg-spindles-n2/2;tea-eeg-spindle-topography-n2/5"
assert curves.curve(label, "husos_sueno_n2") == CURVE
assert registry.calls == [("tea", "eeg-spindles-n2", "2")]
def test_a_label_that_doesnt_name_the_metric_s_baseline_draws_no_curve():
"""Pins down: a label without the metric's scenario (another metric's baseline) and a metric the analysis
doesn't map both give None without touching the registry. Fails if the lookup starts resolving the wrong
scenario."""
registry = FakeRegistry()
curves = BaselineCurves(registry=registry, loader=lambda uri: module_with(pd.DataFrame(CURVE)))
assert curves.curve(LABEL, "husos_sueno_n2") is None
assert curves.curve(LABEL, "ritmo_inexistente") is None
assert registry.calls == []
def test_an_unresolvable_label_or_an_unloadable_module_omits_the_curve():
"""Pins down: a registry that can't resolve the version, and a loader that fails, both give None, so answers
keep working without a reachable registry. Fails if a failure starts propagating instead of omitting."""
failing = BaselineCurves(registry=FakeRegistry(LookupError("no version 3")), loader=lambda uri: None)
assert failing.curve(LABEL, "ritmo_posterior") is None
broken = BaselineCurves(registry=FakeRegistry(), loader=lambda uri: (_ for _ in ()).throw(RuntimeError("x")))
assert broken.curve(LABEL, "ritmo_posterior") is None
def test_a_baseline_without_a_curve_or_with_too_few_points_draws_none():
"""Pins down: age-block baselines (no `curva`) and curves with fewer than two complete points give None, and
rows missing a percentile are dropped. Fails if an undrawable curve starts being served."""
registry = FakeRegistry()
no_curve = BaselineCurves(registry=registry, loader=lambda uri: module_with(None))
assert no_curve.curve(LABEL, "ritmo_posterior") is None
sparse = pd.DataFrame({"edad_meses": [16.0, 24.0], "p5": [4.0, None], "p25": [4.5, None], "mediana": [5.0, None],
"p75": [5.5, None], "p95": [6.0, None]})
one_point = BaselineCurves(registry=registry, loader=lambda uri: module_with(sparse))
assert one_point.curve(LABEL, "ritmo_posterior") is None
partial = pd.DataFrame({"edad_meses": [16.0, 24.0, 36.0], "p5": [4.0, None, 6.0], "p25": [4.5, None, 6.5],
"mediana": [5.0, None, 7.0], "p75": [5.5, None, 7.5], "p95": [6.0, None, 8.0]})
dropped = BaselineCurves(registry=registry, loader=lambda uri: module_with(partial))
assert dropped.curve(LABEL, "ritmo_posterior") == {"edad_meses": [16.0, 36.0], "p5": [4.0, 6.0],
"p25": [4.5, 6.5], "mediana": [5.0, 7.0],
"p75": [5.5, 7.5], "p95": [6.0, 8.0]}
def metric_row(**cambios) -> dict:
"""One `tea_paciente_eeg_metricas` row of a scored posterior rhythm, with the analysis's baseline label."""
row = {"procedimiento_id": 7, "pac_id": 1, "metrica": "ritmo_posterior", "valor": 6.8, "valor_z": -4.08,
"grupo_edad_eeg": "16_23", "ref_min": 4.5, "ref_mediana": 5.75, "ref_max": 8.0,
"estado": "disminuido", "modelo": LABEL}
return {**row, **cambios}
def eeg_row(**cambios) -> dict:
"""One `tea_paciente_eegs` row: the study's valid EEG, with the age its analysis compared references at."""
row = {"procedimiento_id": 7, "pac_id": 1, "fecha_eeg": date(2025, 5, 20), "con_sueno": 1, "canales": 19,
"duracion_min": 25.0, "edad_meses": 23.6, "nivel": "completo", "fraccion_limpia": 0.95,
"canales_malos": 0, "ruido_linea_db": -30.0, "calidad": "BUENO", "valido": 1}
return {**row, **cambios}
def sub_series(extension: dict) -> dict:
"""A curve extension's sub-extensions back as series: each name's values in order."""
out: dict[str, list] = {}
for e in extension["extension"]:
out.setdefault(e["url"].rsplit("/", 1)[1], []).append(e.get("valueDecimal", e.get("valueString")))
return out
def test_a_metric_observation_carries_its_curve_as_a_nested_extension(monkeypatch):
"""Pins down: with the alterations validated, a metric row with a baseline label gets one `curva-referencia`
extension whose `fuente` is the label, whose `estado` reads `validada`, and whose series come back as ordered
sub-extensions (`edad-meses`, then p5 to p95). Fails if the extension's shape or the gate tie changes."""
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False,
curves=FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
(curve,) = observation["extension"]
assert curve["url"] == f"{tea.STRUCTURE}/curva-referencia"
series = sub_series(curve)
assert series["fuente"] == [LABEL] and series["estado"] == ["validada"]
expected = {"edad-meses": CURVE["edad_meses"], **{p: CURVE[p] for p in ("p5", "p25", "mediana", "p75", "p95")}}
for name, values in expected.items():
assert series[name] == values
get_fhir_model_class("Observation").model_validate(observation)
def test_the_curve_estado_follows_the_validation_gate(monkeypatch):
"""Pins down: without `TEA_ALTERACIONES_VALIDADAS` the same observation's `estado` reads `pendiente`, the
state the summary's other endpoints report while the references await validation. Fails if `estado` stops
reflecting the gate."""
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False,
curves=FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
(curve,) = observation["extension"]
assert sub_series(curve)["estado"] == ["pendiente"]
def test_an_undrawable_curve_is_omitted():
"""Pins down: a loader that can't resolve the label, and a metric row without a label, both give an
observation with no extension, and the loader isn't even asked without a label. Fails if a failed resolution
starts leaking an empty or partial curve."""
loader = FakeCurves({})
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False, curves=loader)
assert "extension" not in observation and loader.calls == [(LABEL, "ritmo_posterior")]
(unlabeled,) = tea.metric_observations(eeg_row(), [metric_row(modelo=None)], [], "P-X", False, curves=loader)
assert "extension" not in unlabeled and loader.calls == [(LABEL, "ritmo_posterior")]
def test_the_eeg_report_carries_the_analysis_age_as_an_extension():
"""Pins down: the `DiagnosticReport` carries `edad-meses` next to `duracion-min` and `canales`, and drops it
with them when null. Fails if the age stops reaching the report or leaves the extension block the others share."""
(procedure, report, *_) = tea.eeg_resources(eeg_row(), "P-X", [], [], False)
extensions = {e["url"].rsplit("/", 1)[-1]: e for e in report["extension"]}
assert extensions["edad-meses"]["valueDecimal"] == 23.6
assert extensions["duracion-min"]["valueDecimal"] == 25.0 and extensions["canales"]["valueInteger"] == 19
(_, bare, *_) = tea.eeg_resources(eeg_row(edad_meses=None, duracion_min=None, canales=None), "P-X", [], [],
False)
assert "extension" not in bare
for resource in (procedure, report):
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
def _rows(sesion):
from core.tea.models import Eeg, EegMetrica, Mchat, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1,
eeg_nivel="completo", eeg_fraccion_limpia=0.95, eeg_edad_meses=23.6, eeg_con_sueno=1,
eeg_canales=19, eeg_duracion_min=25.0))
sesion.add(EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=-4.08,
met_fuera=-1, met_p5=4.5, met_mediana=5.75, met_p95=8.0, met_modelo=LABEL))
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models: one child whose analysed EEG's rhythm names a baseline."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_curvas"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
@pytest.fixture()
def queries():
"""The domain's dbt query repository, aimed at the `loaded` database by `base_de`'s `point_to`."""
from persistance import tea as dominio
return dominio.dbt_query_repository
def test_the_analysis_age_reaches_the_eegs_view(loaded, queries):
"""Pins down: `eeg.eeg_edad_meses` flows through the silver mapping and `tea_paciente_eegs` as `edad_meses`.
Fails if the silver mapping or the views drop the age again."""
from sqlalchemy import select
from webapi.fhir.tea import EEGS
(row,) = tea._rows(queries, select(EEGS.c.edad_meses))
assert row["edad_meses"] == 23.6
def test_the_metric_view_carries_the_baseline_label(loaded, queries):
"""Pins down: `eeg_metrica.met_modelo` flows through the silver mapping and `tea_paciente_eeg_metricas` as
`modelo`, the only label the FHIR layer reads. Fails if the silver mapping or the views drop the label again."""
from sqlalchemy import select
from webapi.fhir.tea import METRICS
(row,) = tea._rows(queries, select(METRICS).where(METRICS.c.metrica == "ritmo_posterior"))
assert row["modelo"] == LABEL
def test_the_patient_summary_draws_the_curve_and_the_age(loaded, queries, monkeypatch):
"""Pins down `$resumen-tea`: with the alterations validated and a resolvable baseline, the metric observation
carries the curve (`fuente` the stored label) and the report the `edad-meses` extension; with an unresolvable
baseline the same summary answers with no curve. Fails if the summary stops wiring the label, the loader or
the age."""
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
monkeypatch.setattr("webapi.fhir.tea.baseline_curves",
lambda: FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
bundle = tea.patient_summary(queries, 1, date(2025, 12, 31), False)
resources = [e["resource"] for e in bundle["entry"]]
(observation,) = [r for r in resources if r["id"].startswith("ritmo-posterior-")]
(curve,) = observation["extension"]
assert sub_series(curve)["fuente"] == [LABEL]
(report,) = [r for r in resources if r["resourceType"] == "DiagnosticReport"]
assert any(e["url"].endswith("/edad-meses") and e["valueDecimal"] == 23.6 for e in report["extension"])
for resource in resources:
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
monkeypatch.setattr("webapi.fhir.tea.baseline_curves",
lambda: BaselineCurves(registry=FakeRegistry(LookupError("sin registry"))))
bare = tea.patient_summary(queries, 1, date(2025, 12, 31), False)
assert all("extension" not in e["resource"] for e in bare["entry"]
if e["resource"]["resourceType"] == "Observation"
and e["resource"]["id"].startswith("ritmo-posterior-"))
-140
View File
@@ -1,140 +0,0 @@
"""What this module covers: `$resumen-tea`'s `RiskAssessment`, the ADOS-2 association model as idiomatic FHIR:
one resource per patient with a prediction per association row of the latest model version that scored the study's
EEG (the clearest cohort association, lowest q, first), the model's metadata on the resource, the outcome as the
ADOS-2 item or domain with its label from the code systems, the observed outcome read from the patient's ADOS-2,
and the resource omitted entirely when no model row scored the patient's study EEG. Every resource is checked
against FHIR's models.
Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`) over TEA's fixture database (`staging.tea`) plus model and
patient rows for child 1's study EEG (`eeg-1b`); needs `DBT_MANIFEST`.
"""
import os
from datetime import date
import pytest
from test_fhir_tea import get, resources
from conftest import base_de
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
def _rows(sesion):
"""The kit's seven children, plus a fitted model: one item row (sa_b2) and one domain row (SA) of version
0.2.0, both scored for child 1's study EEG (eeg-1b, 20 May). Child 1's ADOS-2 (ado-1) scores sa_b2 2 and its
SA domain total is 6; no other child gets model rows."""
from importlib import import_module
import_module("staging.tea").insertar(sesion)
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
sesion.add_all([
RelacionAdos2(rel_id="rel-2a", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
rel_resultado="sa_b2", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7,
rel_q=0.02),
RelacionAdos2(rel_id="rel-2b", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio",
rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6,
rel_q=0.3),
])
sesion.add_all([
RelacionAdos2Paciente(rap_id="rap-2a", rap_rel_id="rel-2a", rap_eeg_id="eeg-1b", rap_valor_z=-4.08,
rap_probabilidad=0.81, rap_probabilidad_referencia=0.22),
RelacionAdos2Paciente(rap_id="rap-2b", rap_rel_id="rel-2b", rap_eeg_id="eeg-1b", rap_valor_z=-4.08,
rap_probabilidad=0.35, rap_probabilidad_referencia=0.4),
])
@pytest.fixture(scope="module")
def client(tmp_path_factory):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
mp = pytest.MonkeyPatch()
mp.setenv("DEV_REVISION", "pruebas")
mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
base = base_de("tea", tmp_path_factory.mktemp("tea_fhir_relacion"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
base.motor.dispose()
mp.undo()
def _extension(resource: dict) -> dict:
return {e["url"].rsplit("/", 1)[-1]: e for e in resource["extension"]}
def test_the_summary_emits_the_model_as_one_risk_assessment(client):
"""Pins down: child 1's summary carries one `RiskAssessment` (tagged simulated) with the model's metadata on
the resource (version, expert validation, level, cohort size), dated at the study's EEG (20 May), based on the
EEG's DiagnosticReport and the ADOS-2 Observation, and with one prediction per association row, the clearest
cohort association (lowest q) first. Fails if the resource loses a metadata extension, changes order, or stops
referencing what it was scored from."""
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
(child_1,) = episodes
bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea")
(riesgo,) = resources(bundle, "RiskAssessment")
assert riesgo["id"] == f"relacion-ados2-{child_1['id']}"
assert riesgo["occurrenceDateTime"] == "2025-05-20"
assert riesgo["meta"]["tag"][0]["code"] == "simulado"
extension = _extension(riesgo)
assert extension["modelo-version"]["valueString"] == "0.2.0"
assert extension["modelo-validado"]["valueBoolean"] is False
assert extension["modelo-nivel"]["valueString"] == "item"
assert extension["modelo-n-cohorte"]["valueInteger"] == 60
(report,) = resources(bundle, "DiagnosticReport")
ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-"))
assert riesgo["basis"] == [{"reference": f"DiagnosticReport/{report['id']}"},
{"reference": f"Observation/{ados2['id']}"}]
assert len(riesgo["prediction"]) == 2
assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2.sa_b2", "SA"]
def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_outcome(client):
"""Pins down: a prediction has the outcome as the ADOS-2 item or domain with its label from the code systems
(not from the row), the model's probability for the patient, and as extensions the EEG metric and scalp zone
(with labels), the patient's z, the cohort's odds ratio with its interval and q, the event as stored, the
reference probability (z = 0) and the outcome observed in the patient's ADOS-2 (the item's score 2, the SA
domain's algorithm total 6). Fails if a label starts coming from the stored row, or a value stops reaching the
prediction."""
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
(child_1,) = episodes
bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea")
(riesgo,) = resources(bundle, "RiskAssessment")
item, dominio = riesgo["prediction"]
assert item["outcome"]["coding"][0] == {
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo", "code": "ados2.sa_b2",
"display": "Sonrisa social en respuesta"}
assert dominio["outcome"]["coding"][0] == {
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio", "code": "SA",
"display": "Afecto social"}
assert (item["probabilityDecimal"], dominio["probabilityDecimal"]) == (0.81, 0.35)
extension = _extension(item)
assert extension["biomarcador"]["valueCoding"] == {
"system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-metrica", "code": "RITMO_POSTERIOR",
"display": "Ritmo posterior"}
assert extension["zona"]["valueCoding"] == {
"system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-zona", "code": "occipital",
"display": "Occipital"}
assert (extension["tipo"]["valueString"], extension["evento"]["valueString"]) == ("item", ">=1")
assert extension["valor-z"]["valueDecimal"] == -4.08
assert (extension["odds-ratio"]["valueDecimal"], extension["ic-inf"]["valueDecimal"],
extension["ic-sup"]["valueDecimal"], extension["q"]["valueDecimal"]) == (3.5, 1.4, 8.7, 0.02)
assert extension["probabilidad-referencia"]["valueDecimal"] == 0.22
assert extension["observado"]["valueInteger"] == 2
assert _extension(dominio)["observado"]["valueInteger"] == 6
def test_the_summary_omits_the_model_without_rows(client):
"""Pins down: a child whose study EEG no model row scored gets no `RiskAssessment` at all (not an empty one):
child 2, in neuropediatrics without an EEG. Fails if the emission stops keying on the view's rows."""
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&etapa=NEUROPEDIATRIA"))
(child_2,) = episodes
bundle = get(client, f"/tea/fhir/Patient/{child_2['id']}/$resumen-tea")
assert not resources(bundle, "RiskAssessment")
+6 -100
View File
@@ -9,7 +9,6 @@ Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes ex
shows the alterations (`TEA_ALTERACIONES_VALIDADAS`).
"""
import json
import os
import pytest
@@ -169,9 +168,8 @@ def test_the_follow_up_filters(client, query, n):
def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
"""Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT,
ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality
observations, one per check of its analysis (clean windows, usable scalp, triage level, line noise) as the
analysis's own report writes them; no metric observation while the alterations are hidden. Fails if an included
resource drops out, a check stops reaching the report or changes shape, or the alterations leak."""
observations; no metric observation while the alterations are hidden. Fails if an included resource drops out or
the alterations leak."""
body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*")
included = resources(body, mode="include")
kinds = {r["resourceType"] for r in included}
@@ -179,49 +177,11 @@ def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient")
reports = [r for r in included if r["resourceType"] == "DiagnosticReport"]
assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"}
assert all(len(r["result"]) == 4 for r in reports)
assert all(r["conclusionCode"][1]["coding"][0] == {"system": "urn:tea:validation", "code": "valid"} for r in reports)
quality = [r for r in included if r["resourceType"] == "Observation" and r["id"].startswith("calidad-")]
assert {r["code"]["coding"][0]["system"] for r in quality} == {"urn:tea:validation"}
clean = next(r for r in quality if r["code"]["coding"][0]["code"] == "clean-windows")
assert (clean["valueQuantity"]["value"], clean["referenceRange"][0]["low"]["value"]) == (95.0, 60.0)
assert clean["interpretation"][0]["coding"][0]["code"] == "N"
assert clean["component"] == [{"code": {"text": "decisive"}, "valueBoolean": True}]
triage = next(r for r in quality if r["code"]["coding"][0]["code"] == "triage-level")
assert triage["valueString"] == "completo"
assert all(len(r["result"]) == 5 for r in reports)
ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"]
assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2)
def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client):
"""Pins down, on a bad EEG's rows as dbt's views give them (too few clean windows, a dead channel at T3): the report
says MALO and the analysis's not-valid with the triage level; the clean windows are abnormal and decisive; the
dead channel is an abnormal observation with its electrode as a component; every resource conforms to FHIR.
Fails if a failed check or a bad channel stops reaching FHIR, or loses its electrode or decisive flag."""
from webapi.fhir import tea
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial",
"duracion_min": 25.0, "edad_meses": None, "canales": 19}
checks = [
{"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None,
"bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"},
{"procedimiento_id": 9, "criterio": "dead_channel", "electrodo": "T3", "valor": None,
"valor_texto": "dead channel", "bajo": None, "alto": None, "anormal": 1, "decisivo": 0,
"etiqueta": "Canal muerto", "unidad": None},
]
resources = tea.eeg_resources(eeg, "P-X", [], [], False, checks)
report = next(r for r in resources if r["resourceType"] == "DiagnosticReport")
assert [c["coding"][0]["code"] for c in report["conclusionCode"]] == ["MALO", "not-valid"]
assert report["conclusion"].endswith("(nivel de triaje: parcial).")
clean, dead = (r for r in resources if r["resourceType"] == "Observation")
assert (clean["interpretation"][0]["coding"][0]["code"], clean["component"][-1]["valueBoolean"]) == ("A", True)
assert dead["id"] == "calidad-dead-channel-T3-9" and dead["valueString"] == "dead channel"
assert dead["component"] == [{"code": {"text": "electrode"}, "valueString": "T3"},
{"code": {"text": "decisive"}, "valueBoolean": False}]
for resource in resources:
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch):
"""Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's
slow posterior rhythm). Fails if the filter leaks alterations before validation."""
@@ -247,9 +207,8 @@ def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(c
def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch):
"""Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first
good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated,
the metrics against their age baseline (p5 as the low end of the reference, the median as a component) and each
electrode's z-score; and its episode, with the age group. Fails if the summary takes another EEG, shows the
alterations before validation, maps the electrodes' raw values or loses the age group."""
the metrics against their reference and the electrode values. Fails if the summary takes another EEG or shows the
alterations before validation."""
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
(child_1,) = episodes
path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea"
@@ -266,61 +225,8 @@ def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, mon
metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")]
rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-"))
assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5
assert {c["code"]["coding"][0]["code"]: c["valueQuantity"]["value"] for c in rhythm["component"]} == {
"z": -4.08, "mediana": 5.75}
(episode,) = resources(shown, "EpisodeOfCare")
assert episode["extension"][0]["valueCoding"]["code"] == "16_23"
electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-"))
assert [(c["code"]["coding"][0]["code"], c["valueQuantity"]["value"]) for c in electrodes["component"]] == [
("O1", -2.8), ("O2", -2.4), ("Pz", -1.1)]
def test_a_metric_the_baseline_couldnt_score_keeps_its_value():
"""Pins down: a metric with a value but no z (no baseline in production, or an age it doesn't cover) keeps its
value and has no interpretation nor reference; one without a value is `not-performed`. Fails if an unscored metric
loses its value (the summary couldn't tell it from one never measured) or gets an interpretation it doesn't have."""
from webapi.fhir import tea
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-05-20"}
row = {"procedimiento_id": 9, "ref_min": None, "ref_mediana": None, "ref_max": None, "grupo_edad_eeg": "16_23",
"estado": "no_evaluable", "valor_z": None}
unscored, unmeasured = tea.metric_observations(eeg, [{**row, "metrica": "ritmo_posterior", "valor": 6.8},
{**row, "metrica": "husos_sueno_n3", "valor": None}],
[], "P-X", False)[::-1]
assert unscored["valueQuantity"]["value"] == 6.8
assert not {"interpretation", "referenceRange", "dataAbsentReason", "component"} & set(unscored)
assert unmeasured["dataAbsentReason"]["coding"][0]["code"] == "not-performed" and "valueQuantity" not in unmeasured
def test_the_quality_checks_are_a_code_system_of_the_analysis(client):
"""Pins down: `CodeSystem/tea-eeg-criterio` is the EEG analysis's code system (`urn:tea:validation`) with every
check code and the catalog's label, and each metric has a text for every state, normal included.
Fails if a check code the quality observations use has no concept, or a metric loses its normal effect.
"""
from core.tea.enums import CriterioEeg
checks = get(client, "/tea/fhir/CodeSystem/tea-eeg-criterio")
assert checks["url"] == "urn:tea:validation"
assert {c["code"] for c in checks["concept"]} == {c.value for c in CriterioEeg}
assert next(c for c in checks["concept"] if c["code"] == "clean-windows")["display"] == "Ventanas limpias"
metrics = get(client, "/tea/fhir/CodeSystem/tea-eeg-metrica")
assert all(any(p["code"] == "efecto-normal" for p in c["property"]) for c in metrics["concept"])
def test_an_answer_that_doesnt_conform_to_fhir_never_leaves(client):
"""Pins down: `fhir()` validates every answer against R4B; one that doesn't conform is a 500 `OperationOutcome`.
Fails if a malformed resource reaches a client, or the check stops running.
"""
from webapi import create_app
from webapi.fhir.common import fhir
with create_app().test_request_context():
bad = fhir({"resourceType": "Observation", "id": "x"}) # no status, no code
good = fhir({"resourceType": "Observation", "id": "x", "status": "final", "code": {"text": "t"}})
assert (bad.status_code, json.loads(bad.data)["resourceType"]) == (500, "OperationOutcome")
assert (good.status_code, json.loads(good.data)["status"]) == (200, "final")
assert [c["code"]["coding"][0]["code"] for c in electrodes["component"]] == ["O1", "O2", "Pz"]
def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client):
-29
View File
@@ -261,35 +261,6 @@ def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
assert again["skipped_already_done"] >= 1
def test_eeg_run_analyses_at_most_the_limit_with_the_configured_cluster(client, monkeypatch):
"""Pins down: `POST /governance/eeg/run` runs the EEG analysis in the request with the body's `limit` (5 by
default), `all` and the cluster `EEG_ANALYSIS_CLUSTER` names, and answers its summary.
Fails if the route stops bounding the batch (a request could then run for hours) or ignores the body.
"""
import models.eeg_analysis
from models.eeg_analysis import Summary
calls = []
monkeypatch.setattr(models.eeg_analysis, "analyze_pending",
lambda **kwargs: calls.append(kwargs) or Summary(pending=2, valid=1, not_valid=1, failed=0))
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "sync")
body = client.post("/governance/eeg/run", json={}).get_json()
assert body == {"pending": 2, "valid": 1, "not_valid": 1, "failed": 0}
client.post("/governance/eeg/run", json={"limit": 1, "all": True, "cluster": "local"})
assert calls == [{"everything": False, "limit": 5, "cluster": "sync"},
{"everything": True, "limit": 1, "cluster": "local"}]
@pytest.mark.parametrize("body", [{"limit": 0}, {"limit": "many"}, {"cluster": "everywhere"}])
def test_eeg_run_refuses_a_bad_limit_or_cluster(client, body):
"""Pins down: a limit that isn't a positive whole number, or an unknown cluster, is a 400 before anything runs.
Fails if the route starts an analysis on a body it can't honour.
"""
assert client.post("/governance/eeg/run", json=body).status_code == 400
def test_list_ocr_jobs(client):
body = client.get("/governance/ocr/jobs").get_json()
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
-125
View File
@@ -1,125 +0,0 @@
"""What this module covers: the ADOS-2 association model's import targets (`tea.RelacionAdos2` and
`tea.RelacionAdos2Paciente`): their registration in `/imports/targets` with the natural keys the tables' unique
constraints define, the upsert merge on those keys through the import service (a re-import updates in place
instead of duplicating), and the schemas' validations (probabilities and q within [0, 1], the confidence
interval's order, the outcome code per level, the cataloged biomarker and level, the bounded key columns).
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`).
"""
import base64
import json
import pytest
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("tea")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
def _json_source(records: list[dict], *, target: str) -> dict:
raw = json.dumps(records).encode()
return {
"source_type": "json",
"target": target,
"column_mapping": {name: name for name in records[0]},
"payload": {"file_base64": base64.b64encode(raw).decode()},
}
# One item row and one domain row of a fitted model version, as the `tea` library writes them.
_MODELO_ITEM = {
"rel_id": "rel-1", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42,
"rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "item",
"rel_resultado": "sa_b9", "rel_evento": ">=1", "rel_or": 3.5, "rel_ic_inf": 1.4, "rel_ic_sup": 8.7,
"rel_q": 0.02,
}
_MODELO_DOMINIO = {
"rel_id": "rel-2", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42,
"rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "dominio",
"rel_resultado": "SA", "rel_evento": ">=4", "rel_or": 0.8, "rel_ic_inf": 0.4, "rel_ic_sup": 1.6,
"rel_q": 0.3,
}
# The probabilities of one EEG for both association rows, by the model.
_PACIENTE_1 = {"rap_id": "rap-1", "rap_rel_id": "rel-1", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
"rap_probabilidad": 0.81, "rap_probabilidad_referencia": 0.22}
_PACIENTE_2 = {"rap_id": "rap-2", "rap_rel_id": "rel-2", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
"rap_probabilidad": 0.35, "rap_probabilidad_referencia": 0.4}
def test_targets_list_the_association_tables_with_their_natural_keys(client):
"""Pins down: `/imports/targets` exposes both association tables with the conflict fields of the tables' unique
constraints (uq_relacion_ados2, uq_relacion_ados2_paciente), so `on_conflict=upsert` merges on them, and lists
them as fields to map. Fails if a target is deregistered or its conflict fields drift from the constraints."""
targets = {t["key"]: t for t in client.get("/imports/targets").get_json()["targets"]}
modelo, paciente = targets["tea.RelacionAdos2"], targets["tea.RelacionAdos2Paciente"]
assert modelo["conflict_fields"] == ["rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"]
assert paciente["conflict_fields"] == ["rap_rel_id", "rap_eeg_id"]
assert {"rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"} <= {f["name"] for f in modelo["fields"]}
assert {"rap_rel_id", "rap_eeg_id"} <= {f["name"] for f in paciente["fields"]}
def test_model_and_patient_rows_import_and_reimport_upserts_on_the_natural_keys(client):
"""Pins down: both tables load through the import service and a second import of the same rows updates in
place (created 0, nothing duplicated), keeping the value the later import carried. Fails if the conflict
fields stop matching the natural key (rows would duplicate) or the upsert stops updating."""
fuentes = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
_json_source([_PACIENTE_1, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
body = client.post("/imports/commit", json={"sources": fuentes, "on_conflict": "upsert"}).get_json()
assert [(r["target"], r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [
("tea.RelacionAdos2", 2, 0, 0), ("tea.RelacionAdos2Paciente", 2, 0, 0)]
cambiada = {**_PACIENTE_1, "rap_probabilidad": 0.55}
otra_vez = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
_json_source([cambiada, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
body = client.post("/imports/commit", json={"sources": otra_vez, "on_conflict": "upsert"}).get_json()
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 2, 0), (0, 2, 0)]
filas = client.get("/data/tea.RelacionAdos2Paciente", query_string={"limit": 500}).get_json()["rows"]
assert len(filas) == 2
assert next(f for f in filas if f["rap_id"] == "rap-1")["rap_probabilidad"] == 0.55
def test_invalid_model_rows_are_rejected(client):
"""Pins down: a model row with an out-of-range q, a non-positive odds ratio, an inverted confidence
interval, an unknown level or biomarker, an outcome code that doesn't match its level, or an over-long key
is rejected, none of it written. Fails if the schema loses one of those validations (the staging is
permissive; without them nothing else catches them)."""
casos = [
{**_MODELO_ITEM, "rel_id": "rel-m1", "rel_version": "v" * 33},
{**_MODELO_ITEM, "rel_id": "rel-m2", "rel_version": "0.9.1", "rel_q": 1.5},
{**_MODELO_ITEM, "rel_id": "rel-m3", "rel_version": "0.9.2", "rel_or": 0},
{**_MODELO_ITEM, "rel_id": "rel-m4", "rel_version": "0.9.3", "rel_ic_inf": 9.0, "rel_ic_sup": 4.0},
{**_MODELO_ITEM, "rel_id": "rel-m5", "rel_version": "0.9.4", "rel_nivel": "itemm"},
{**_MODELO_ITEM, "rel_id": "rel-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "SA"},
{**_MODELO_ITEM, "rel_id": "rel-m7", "rel_version": "0.9.6", "rel_biomarcador": "ritmo posterior"},
]
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert resultado["created"] == 0 and resultado["rejected"] == len(casos)
campos = {e["field"] for e in resultado["errors"]}
assert {"rel_version", "rel_q", "rel_or", "rel_nivel", "rel_biomarcador", "<entre campos>"} <= campos
filas = client.get("/data/tea.RelacionAdos2", query_string={"limit": 500}).get_json()["rows"]
assert not [f for f in filas if f["rel_id"].startswith("rel-m")]
def test_invalid_patient_rows_are_rejected(client):
"""Pins down: a probability outside [0, 1] (the model's or the reference's) is rejected. Fails if the
Bounded validation loosens, since a probability over 1 would silently skew what the screen shows."""
buena = {**_PACIENTE_1, "rap_id": "rap-ok", "rap_rel_id": "rel-9"}
casos = [buena,
{**buena, "rap_id": "rap-m1", "rap_probabilidad": 1.2},
{**buena, "rap_id": "rap-m2", "rap_probabilidad_referencia": -0.1}]
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2Paciente")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert (resultado["created"], resultado["rejected"]) == (1, 2)
assert {e["field"] for e in resultado["errors"]} == {"rap_probabilidad", "rap_probabilidad_referencia"}
+3 -3
View File
@@ -84,9 +84,9 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
# TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto]
# CaCu: three strata and its seven measures; CaMa: the BI-RADS stratum of the histopathological result and its
# eleven measures; TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 12, "tea": 11}[base.proyecto]
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
+10 -5
View File
@@ -78,17 +78,22 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
_json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"),
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"),
_json([{"neu_id": "neu-1", "neu_ord_id": "ord-1", "neu_pac_id": 1}], "tea.EvaluacionNeuropediatrica"),
_json([{"met_id": "met-1", "met_eeg_id": "eeg-1", "met_codigo": "RITMO_POSTERIOR", "met_valor": 5.5}], "tea.EegMetrica"),
_json([{"mel_met_id": "met-1", "mel_electrodo": "O1", "mel_valor": -1.2}], "tea.EegMetricaElectrodo"),
]
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
assert all(r["rejected"] == 0 for r in body["results"]), body
from persistance.tea import ados2_repository, eeg_repository, evaluacion_neuropediatrica_repository
from persistance.tea import (
ados2_repository,
eeg_metrica_electrodo_repository,
eeg_metrica_repository,
eeg_repository,
)
assert eeg_repository.get("eeg-1").eeg_ord_id == "ord-1"
assert eeg_repository.get("eeg-1").eeg_id_registro_laboratorio == "L-1"
metrica = eeg_metrica_repository.get(eeg_metrica_electrodo_repository.list()[0].mel_met_id)
assert eeg_repository.get(metrica.met_eeg_id).eeg_id_registro_laboratorio == "L-1"
assert ados2_repository.get("ado-1").ado_ord_id == "ord-1"
assert evaluacion_neuropediatrica_repository.get("neu-1").neu_ord_id == "ord-1"
def test_tea_rows_without_a_source_id_get_one(tea_client):
-148
View File
@@ -1,148 +0,0 @@
"""What this module covers: what the EEG analysis writes to TEA's bronze, carried into silver
(`webapi.orchestration.silver.tea`) and into dbt's views of the EEG's quality checks, metrics and electrodes
(`tea_paciente_eeg_criterios`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`).
Fixtures: `loaded`, a TEA database (`base_de`) loaded up to the event models, with one patient and one analysed EEG
`e-1`: valid, triage `completo`; three checks (95 % clean windows against a low limit of 60, the triage level as text,
and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0, p5/median/p95 5/6/7 and the registered
label of the baseline it was compared against, and its N2 spindles' value 2.5 with z -0.4 at Fz.
"""
import os
from datetime import date
import pytest
from sqlalchemy import text
from sqlmodel import Session, select
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
def _rows(sesion):
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Mchat, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1, eeg_nivel="completo",
eeg_fraccion_limpia=0.95, eeg_canales_malos=1, eeg_edad_meses=23.6, eeg_con_sueno=1))
sesion.add_all([
EegCriterio(cri_id="c-1", cri_eeg_id="e-1", cri_codigo="clean-windows", cri_valor=95.0, cri_unidad="%",
cri_bajo=60.0, cri_decisivo=1, cri_anormal=0),
EegCriterio(cri_id="c-2", cri_eeg_id="e-1", cri_codigo="triage-level", cri_valor_texto="completo",
cri_decisivo=1, cri_anormal=0),
EegCriterio(cri_id="c-3", cri_eeg_id="e-1", cri_codigo="dead-channel", cri_electrodo="T3",
cri_valor_texto="dead channel", cri_decisivo=0, cri_anormal=1),
])
sesion.add_all([
EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=1.2, met_fuera=0,
met_p5=5.0, met_mediana=6.0, met_p95=7.0, met_modelo="tea-eeg-posterior-rhythm/3"),
EegMetrica(met_id="n2", met_eeg_id="e-1", met_codigo="HUSOS_SUENO_N2", met_valor=2.5),
EegMetricaElectrodo(mel_id="n2-fz", mel_met_id="n2", mel_electrodo="Fz", mel_valor=1.4, mel_z=-0.4),
])
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models, with dbt's views created."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_eeg"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
def _observations(base, clase: str) -> dict:
from core.tea.indicadores.models import Observacion, Procedimiento
with Session(base.motor) as sesion:
rows = sesion.exec(select(Procedimiento.codigo_fuente, Observacion).join(
Observacion, Observacion.procedimiento_id == Procedimiento.procedimiento_id).where(
Procedimiento.estudio_id == "eeg", Procedimiento.clase == clase)).all()
return {(fuente, o.resultado_id): o.valor_numerico if o.valor_texto is None else o.valor_texto
for fuente, o in rows}
def test_the_verdict_and_study_checks_are_results_of_the_recording(loaded):
"""Pins down: the EEG's verdict, triage level and each study-wide check (value, limit, out of range or not) are
observations of its recording, under `eeg.calidad_<check>` in snake case; a check without a limit of that side
gives none.
Fails if the silver mapping drops the verdict, stops turning check codes into catalog results, or the catalog
loses one of them (the load skips a result the catalog doesn't have).
"""
toma = _observations(loaded, "toma")
assert toma[None, "eeg.valido"] == 1 and toma[None, "eeg.nivel"] == "completo"
assert (toma[None, "eeg.calidad_clean_windows"], toma[None, "eeg.calidad_clean_windows_bajo"],
toma[None, "eeg.calidad_clean_windows_anormal"]) == (95.0, 60.0, 0)
assert toma[None, "eeg.calidad_triage_level"] == "completo"
assert (None, "eeg.calidad_clean_windows_alto") not in toma
def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded):
"""Pins down: a bad channel is a part of its EEG at its electrode with the analysis's reason; a metric's value at
an electrode is a part with the value and its z.
Fails if the channel checks stop being parts, or the electrode z stops reaching silver.
"""
partes = _observations(loaded, "parte")
assert partes["T3", "eeg.calidad_dead_channel"] == "dead channel"
assert (partes["Fz", "eeg.husos_sueno_n2"], partes["Fz", "eeg.husos_sueno_n2_z"]) == (1.4, -0.4)
def test_a_metric_carries_its_deviation_from_the_baseline(loaded):
"""Pins down: a metric's z, -1/0/+1, the baseline's p5/median/p95 at the age and the baseline's registered label
are results of the recording.
Fails if the silver mapping or the catalog drops one of the deviation's results or the label (the load skips a
result the catalog doesn't have).
"""
toma = _observations(loaded, "toma")
assert [toma[None, f"eeg.ritmo_posterior{s}"]
for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95", "_modelo")] == \
[6.8, 1.2, 0, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3"]
def test_the_quality_view_lists_each_check_with_its_label(loaded):
"""Pins down: `tea_paciente_eeg_criterios` has one row per check of the EEG, study-wide ones without an electrode
and with their limit and decisive flag, the bad channel at its electrode as out of range and not decisive, each with the catalog's label; and the
electrodes view keeps only metric values, not channel checks.
Fails if the view stops pivoting a check's observations, misses the channel parts, or the electrodes view starts
reading the checks' parts as metrics.
"""
with loaded.motor.connect() as connection:
rows = connection.execute(text(
"select criterio, electrodo, valor, valor_texto, bajo, anormal, decisivo, etiqueta "
"from tea_paciente_eeg_criterios "
"order by criterio")).all()
electrodes = connection.execute(text("select metrica, electrodo from tea_paciente_eeg_electrodos")).all()
by_check = {r.criterio: r for r in rows}
assert set(by_check) == {"clean_windows", "triage_level", "dead_channel"}
assert (by_check["clean_windows"].valor, by_check["clean_windows"].bajo, by_check["clean_windows"].anormal,
by_check["clean_windows"].decisivo) == (95.0, 60.0, 0, 1)
assert (by_check["dead_channel"].electrodo, by_check["dead_channel"].anormal, by_check["dead_channel"].decisivo) == \
("T3", 1, 0)
assert by_check["clean_windows"].etiqueta == "Ventanas limpias"
assert [tuple(e) for e in electrodes] == [("husos_sueno_n2", "Fz")]
def test_a_metric_is_scored_by_the_analysis_s_deviation(loaded):
"""Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state, the baseline's
p5/median/p95 as the reference and the baseline's registered label; a metric without a z (no baseline in
production) can't be evaluated. And the electrodes view carries each electrode's z next to its value.
Fails if dbt goes back to scoring metrics against fixed ranges of its own, drops the baseline label, or drops the
electrode z.
"""
with loaded.motor.connect() as connection:
metrics = {r.metrica: r for r in connection.execute(text(
"select metrica, valor, ref_min, ref_mediana, ref_max, modelo, valor_z, estado "
"from tea_paciente_eeg_metricas"))}
(electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all()
rhythm = metrics["ritmo_posterior"]
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.modelo, rhythm.valor_z,
rhythm.estado) == (6.8, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3", 1.2, "normal")
assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
assert tuple(electrode) == (1.4, -0.4)
+4 -3
View File
@@ -19,7 +19,7 @@ from sqlmodel import select
import staging.tea as fixture
from conftest import base_de
from core.tea.models import Ados2, Eeg, EegCriterio, EegMetrica, Mchat
from core.tea.models import Ados2, Eeg, EegMetrica, Mchat
from webapi.compositions import answer_composition, composition_definitions
from webapi.durations import answer_duration, duration_definitions
from webapi.metrics import Question, answer, measure_definitions
@@ -219,7 +219,7 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
def without_the_good_eeg(session):
fixture.insertar(session)
session.flush()
for model, key in ((EegMetrica, "met_eeg_id"), (EegCriterio, "cri_eeg_id"), (Eeg, "eeg_id")):
for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")):
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
session.delete(row)
@@ -231,7 +231,8 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
with base.staging() as session:
session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1,
eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=1, eeg_nivel="completo",
eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0,
eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0,
eeg_ruido_linea_db=3.5))
session.commit()
base.run("load", allow_undecided=True)
-137
View File
@@ -1,137 +0,0 @@
"""What this module covers: `tea_paciente_relacion_ados2`, the gold view of the ADOS-2 association model: per
patient it keeps only the latest model version that scored the study's EEG, it takes the probabilities of the
study's EEG alone (not later EEGs, not model rows without a probability for it), and it computes `observado` from
the first ADOS-2 by date (the item's score, the domain's algorithm total, null when the outcome wasn't scored).
Fixtures: `loaded`, a TEA database (`base_de`) with one child in the cohort (M-CHAT, ADOS-2 with items), two good
EEGs (`e-1` the study's, `e-2` a later one), a second child without model rows, and a fitted model in two
versions whose patient rows point at both EEGs and both versions; needs `DBT_MANIFEST`.
"""
import os
from datetime import date
import pytest
from sqlalchemy import text
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
def _rows(sesion):
from core.tea.models import (
Ados2,
Eeg,
Mchat,
Pacientes,
RelacionAdos2,
RelacionAdos2Paciente,
)
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Pacientes(pac_id=2, pac_id_hospital="H-2", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add_all([
Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12),
Mchat(mch_id="m-2", mch_pac_id=2, mch_fecha=date(2025, 1, 10), mch_puntaje=8),
])
# Items: sa_b1 2, sa_b9 1 (SA algorithm total 3), rrb_d1 2, rrb_d2 1 (RRB total 3). rrb_d4 is not scored.
sesion.add(Ados2(ado_id="a-1", ado_pac_id=1, ado_fecha=date(2025, 2, 5), ado_modulo="MODULO_1", ado_css=7,
ado_clasificacion="AUTISMO", ado_sa_b1=2, ado_sa_b9=1, ado_rrb_d1=2, ado_rrb_d2=1))
sesion.add_all([
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1),
Eeg(eeg_id="e-2", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 6, 1), eeg_valido=1),
Eeg(eeg_id="e-3", eeg_pac_id=2, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1),
])
sesion.add_all([
RelacionAdos2(rel_id="rel-10", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
rel_resultado="sa_b9", rel_evento=">=1", rel_or=2.0, rel_ic_inf=1.0, rel_ic_sup=4.0,
rel_q=0.05),
RelacionAdos2(rel_id="rel-11", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio",
rel_resultado="SA", rel_evento=">=4", rel_or=0.6, rel_ic_inf=0.3, rel_ic_sup=1.2,
rel_q=0.4),
RelacionAdos2(rel_id="rel-20", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
rel_resultado="sa_b9", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7,
rel_q=0.02),
RelacionAdos2(rel_id="rel-21", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio",
rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6,
rel_q=0.3),
# A row of the latest version no probability was computed for: it can't reach the patient.
RelacionAdos2(rel_id="rel-22", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="PICOS_PAROXISTICOS", rel_zona="frontal_izq", rel_tipo="item",
rel_resultado="rrb_d4", rel_evento=">=1", rel_or=1.5, rel_ic_inf=0.8, rel_ic_sup=2.9,
rel_q=0.1),
# The same, without even a patient row anywhere: nothing to join on.
RelacionAdos2(rel_id="rel-23", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="PICOS_PAROXISTICOS", rel_zona="frontal_izq", rel_tipo="item",
rel_resultado="sa_b1", rel_evento=">=1", rel_or=1.1, rel_ic_inf=0.7, rel_ic_sup=1.8,
rel_q=0.2),
])
sesion.add_all([
# The stale version's probability: the latest version wins.
RelacionAdos2Paciente(rap_id="rap-0", rap_rel_id="rel-10", rap_eeg_id="e-1", rap_valor_z=-2.5,
rap_probabilidad=0.6, rap_probabilidad_referencia=0.25),
RelacionAdos2Paciente(rap_id="rap-1", rap_rel_id="rel-20", rap_eeg_id="e-1", rap_valor_z=-2.5,
rap_probabilidad=0.81, rap_probabilidad_referencia=0.22),
RelacionAdos2Paciente(rap_id="rap-2", rap_rel_id="rel-21", rap_eeg_id="e-1", rap_valor_z=-2.5,
rap_probabilidad=0.35, rap_probabilidad_referencia=0.4),
RelacionAdos2Paciente(rap_id="rap-3", rap_rel_id="rel-22", rap_eeg_id="e-1", rap_valor_z=1.1,
rap_probabilidad=0.5, rap_probabilidad_referencia=0.45),
# A probability for the later EEG: not the study's, it doesn't count.
RelacionAdos2Paciente(rap_id="rap-4", rap_rel_id="rel-20", rap_eeg_id="e-2", rap_valor_z=0.4,
rap_probabilidad=0.3, rap_probabilidad_referencia=0.25),
])
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models, with the view under test created."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_relacion"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
def _filas(loaded):
with loaded.motor.connect() as connection:
return connection.execute(text(
"select pac_id, procedimiento_id, version, validado, nivel, n_cohorte, biomarcador, zona, tipo,"
" resultado, evento, odds_ratio, ic_inf, ic_sup, q, valor_z, probabilidad,"
" probabilidad_referencia, observado from tea_paciente_relacion_ados2")).all()
def test_the_view_keeps_the_latest_version_of_the_study_eeg_only(loaded):
"""Pins down: one row per association row of the greatest model version that scored the study's EEG (1.1.0).
The stale version's probability (1.0.0), the probability for the later EEG (e-2), the model rows of 1.1.0
without a probability for the study's EEG (rel-23) or scored only on the other EEG don't appear, and a child
without model rows (patient 2) doesn't either. Fails if the view stops filtering by the study's EEG or by the
latest version."""
filas = _filas(loaded)
claves = sorted((f.version, f.resultado, f.tipo) for f in filas)
assert claves == [("1.1.0", "SA", "dominio"), ("1.1.0", "rrb_d4", "item"), ("1.1.0", "sa_b9", "item")]
assert {f.pac_id for f in filas} == {1}
def test_a_row_carries_the_model_metadata_and_the_patient_values(loaded):
"""Pins down: each row carries the model row as it arrived (version, validation, level, cohort size, metric,
zone, event, odds ratio with its interval and q) and the patient's values for the study's EEG. Fails if a
column stops being selected or gets renamed without the FHIR layer changing with it."""
(item,) = [f for f in _filas(loaded) if f.resultado == "sa_b9"]
assert (item.version, item.validado, item.nivel, item.n_cohorte) == ("1.1.0", 0, "item", 60)
assert (item.biomarcador, item.zona, item.evento) == ("RITMO_POSTERIOR", "occipital", ">=1")
assert (item.odds_ratio, item.ic_inf, item.ic_sup, item.q) == (3.5, 1.4, 8.7, 0.02)
assert (item.valor_z, item.probabilidad, item.probabilidad_referencia) == (-2.5, 0.81, 0.22)
def test_observado_is_the_outcome_score_of_the_first_ados2(loaded):
"""Pins down: `observado` is read from the first ADOS-2 by date (the one the patient summary shows): the
item's score for an item (sa_b9 1), the domain's algorithm total for a domain (SA: sa_b1 2 + sa_b9 1 = 3), and
null when the outcome wasn't scored (rrb_d4). It is never stored in the association tables. Fails if the view
starts reading another ADOS-2, sums the raw scores, or stores the outcome."""
observados = {f.resultado: f.observado for f in _filas(loaded)}
assert observados == {"sa_b9": 1, "SA": 3, "rrb_d4": None}
Generated
+144 -786
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -375,29 +375,6 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
return jsonify(updated)
@governance_bp.post("/eeg/run")
def run_eeg_analysis():
"""Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most
`limit` EEGs (5 by default), or every EEG with an EDF again with `all`. Larger batches are the indicator cycle's
or `python -m models tea analyze`'s. Rows already analysed with the current plan, modules and baselines are
skipped, so repeated calls are safe (VAR-09)."""
from models.eeg_analysis import analyze_pending
from webapi.orchestration.eeg import CLUSTERS, cluster as configured_cluster
body = request.get_json(silent=True) or {}
try:
limit = int(body.get("limit", 5))
except (TypeError, ValueError):
return jsonify({"error": "limit must be a whole number"}), 400
if limit < 1:
return jsonify({"error": "limit must be at least 1"}), 400
cluster = body.get("cluster") or configured_cluster()
if cluster not in CLUSTERS:
return jsonify({"error": f"cluster must be one of {', '.join(CLUSTERS)}"}), 400
summary = analyze_pending(everything=bool(body.get("all")), limit=limit, cluster=cluster)
return jsonify(asdict(summary))
@governance_bp.post("/ocr/run")
def run_ocr():
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
+21 -3
View File
@@ -6,12 +6,14 @@ date taken, then the greatest source id, then the latest report date, then the g
always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one
(`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy
shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to.
Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on
or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise.
Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off.
"""
from dataclasses import dataclass
from datetime import date
from datetime import date, timedelta
from sqlalchemy import Date, Integer, String, column, func, inspect, select, table
from sqlmodel import Session
@@ -25,6 +27,8 @@ ESCENARIO = "diagnostico"
VERSION = "0.1.0"
SIN_DATO = "SIN_DATO"
SIN_BIOPSIA = "SIN_BIOPSIA"
POST_TRATAMIENTO = "POST_TRATAMIENTO"
EN_OBSERVACION = "EN_OBSERVACION"
# Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest.
GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
@@ -35,14 +39,17 @@ CANDIDATOS = table(
column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String),
column("biopsia_fecha_reporte", Date), column("biopsia_grado", String),
)
LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date))
class CohorteNoDisponible(RuntimeError):
"""The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503)."""
"""The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't
run (503)."""
def disponible(sesion: Session) -> bool:
return inspect(sesion.get_bind()).has_table(CANDIDATOS.name)
inspector = inspect(sesion.get_bind())
return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO))
@dataclass(frozen=True)
@@ -58,6 +65,7 @@ class Fila:
# The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`).
primera_biopsia_fecha: date | None = None
primer_maligno_fecha: date | None = None
escenario_clinico: str = EN_OBSERVACION
@property
def resultado(self) -> str:
@@ -93,8 +101,17 @@ def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
return SIN_DATO
def en_postratamiento(sesion: Session, corte: date) -> set[int]:
"""The patients whose timeline puts them in post-treatment on or before `corte`."""
linea = LINEA_DE_TIEMPO.c
# Before the next day, so a date stored with a time still counts on its own day.
return set(sesion.execute(select(linea.pac_id).distinct().where(
linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars())
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
postratamiento = en_postratamiento(sesion, corte)
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS)
@@ -133,6 +150,7 @@ def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None,
primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None),
primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None),
escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION,
))
return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id))
+7 -2
View File
@@ -14,7 +14,7 @@ from datetime import date, timedelta
from sqlmodel import Session
from webapi.cama_follow_up.cohort import (
COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
COHORTE, EN_OBSERVACION, ESCENARIO, POST_TRATAMIENTO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
disponible, grupos_de_edad,
)
from webapi.orchestration.reference.rules import valor_de
@@ -25,11 +25,13 @@ VENTANA_POR_OMISION = 3
PAGINA_MAXIMA = 200
EXPORTACION_MAXIMA = 5000
GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"}
ESCENARIOS_CLINICOS = {POST_TRATAMIENTO: "Post-tratamiento", EN_OBSERVACION: "En observación"}
COLUMNAS = [
{"clave": "pac_id", "etiqueta": "Identificador de paciente"},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad"},
{"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]},
{"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico"},
]
@@ -80,6 +82,8 @@ def filtros_disponibles(sesion: Session) -> list[dict]:
*({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()),
{"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"},
{"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico", "opciones": [
{"codigo": c, "etiqueta": e} for c, e in ESCENARIOS_CLINICOS.items()]},
]
@@ -114,7 +118,8 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict)
def _item(f: Fila) -> dict:
return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads,
"mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia,
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None}
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None,
"escenario_clinico": f.escenario_clinico}
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
+1 -1
View File
@@ -15,7 +15,7 @@ from webapi.cama_follow_up.listing import (
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia")
FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")
-35
View File
@@ -99,40 +99,6 @@ class CompositionDefinition:
improvement_notation = None
class InvalidCategoryGroups(ValueError):
"""A composition's category groups (`categoria.grupos` and each label's `grupo`) don't hold together."""
def category_groups(url: str, rule: dict) -> dict[str, str]:
"""The groups of a composition's categories (`categoria.grupos`: code -> caption), checked against the labels that
name them (`categoria.etiquetas.<code>.grupo`). Optional: without either, there are none.
A label may name no group (a category kept apart, like «Sin biopsia aún»); every group named is declared, every
declared group has a category, and the no-data category, if grouped, is alone in the group of its own code, as the
indicator page reads it.
"""
grupos = rule.get("grupos")
labels = rule.get("etiquetas", {})
named = {code: spec["grupo"] for code, spec in labels.items() if isinstance(spec, dict) and "grupo" in spec}
if grupos is None:
if named:
raise InvalidCategoryGroups(f"{url}: categories name groups ({', '.join(sorted(named))}) but `grupos` is missing")
return {}
if not isinstance(grupos, dict) or not grupos or not all(
isinstance(code, str) and code and isinstance(caption, str) and caption.strip() for code, caption in grupos.items()):
raise InvalidCategoryGroups(f"{url}: `grupos` maps each group's code to a non-empty caption")
if unknown := sorted({g for g in named.values() if g not in grupos}):
raise InvalidCategoryGroups(f"{url}: undeclared groups {unknown}")
if unused := sorted(set(grupos) - set(named.values())):
raise InvalidCategoryGroups(f"{url}: groups without categories {unused}")
no_data = rule.get("sin_dato")
if no_data in named and (named[no_data] != no_data or [c for c, g in named.items() if g == no_data and c != no_data]):
raise InvalidCategoryGroups(f"{url}: the no-data category {no_data!r} goes alone in the group {no_data!r}")
if no_data in grupos and named.get(no_data) != no_data:
raise InvalidCategoryGroups(f"{url}: the group {no_data!r} is the no-data category's own")
return dict(grupos)
def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
"""The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`."""
m = json.loads(manifest.read_text(encoding="utf-8"))
@@ -146,7 +112,6 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
model = _semantic_model_of(metric, semantic)
node = models[model["depends_on"]["nodes"][0]]
rule = meta["categoria"]
category_groups(meta["measure_url"], rule) # fails the manifest's load if the groups don't hold together
definitions[meta["measure_url"]] = CompositionDefinition(
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
+1 -2
View File
@@ -354,6 +354,5 @@ def _included(tea, queries, e, simulated: bool) -> list[dict]:
tea.care_plan(e, simulated)]
resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r]
if (eeg := e.study_eeg()) is not None:
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks,
curves=tea.baseline_curves())
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
return resources
+3 -27
View File
@@ -1,9 +1,7 @@
"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with
their paging links, the simulated-data tag and the project's canonical URLs. Every answer is validated against FHIR's
R4B models (`fhir.resources`, the models the EEG analysis validates its own report with) before it leaves."""
their paging links, the simulated-data tag and the project's canonical URLs."""
import json
import logging
import os
from urllib.parse import urlencode
@@ -19,32 +17,10 @@ SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display":
MAX_COUNT = 200
DEFAULT_COUNT = 50
log = logging.getLogger(__name__)
def validated(resource: dict) -> dict:
"""The resource as FHIR's R4B models read it and write it back (R4B keeps R4's shape for these resources).
`ValueError` if it doesn't conform."""
from fhir.resources.R4B import get_fhir_model_class
try:
model = get_fhir_model_class(resource["resourceType"])
except KeyError as exc:
raise ValueError(f"no FHIR resource type {resource.get('resourceType')!r}") from exc
return model.model_validate(resource).model_dump(mode="json", exclude_none=True)
def fhir(resource: dict, status: int = 200) -> Response:
"""A resource as the answer, in FHIR's JSON media type. One that doesn't conform to FHIR never leaves: the answer
is then a 500 `OperationOutcome`, and the reason goes to the log."""
try:
body = validated(resource)
except ValueError:
if resource.get("resourceType") == "OperationOutcome":
raise
log.exception("a %s answer doesn't conform to FHIR R4B", resource.get("resourceType"))
return outcome(500, "exception", "la respuesta no es un recurso FHIR válido")
return Response(json.dumps(body, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
"""A resource as the answer, in FHIR's JSON media type."""
return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
-107
View File
@@ -1,107 +0,0 @@
"""The age-norm curves behind the EEG metrics' reference ranges, for the FHIR answers.
Each metric row names the baseline its analysis compared it against: its `modelo` (from `eeg_metrica.met_modelo`,
carried by `tea_paciente_eeg_metricas`) is the registered model's label, `tea-<scenario>/<version>`, pinned to the
version the analysis used (which may no longer be the one in production). The full centile curve of that exact
version is its registered artifact, loaded the way the analysis loads it (`models.tea.eeg.baselines`). A label that
can't be resolved, or a module that can't be loaded, gives no curve: the answer keeps the reference range it already
had.
"""
PERCENTILES = ("p5", "p25", "mediana", "p75", "p95")
class BaselineCurves:
"""Loads and caches the centile curves of the registered baselines the EEG analysis pinned.
`curve(label, metric)` is the curve the named version draws for the metric — `{"edad_meses": [...],
"p5": [...], "p25": [...], "mediana": [...], "p75": [...], "p95": [...]}` with the ages increasing and each
row's percentiles non-crossing — or None when the label doesn't name the metric's baseline or any step of the
resolution fails (unknown metric, unknown scenario, unreachable registry, unloadable artifact). Modules are
loaded once per label. `registry` and `loader` are injectable so tests run without a model registry.
"""
def __init__(self, registry=None, loader=None):
self._registry = registry
self._loader = loader
self._modules: dict[str, dict[str, object | None]] = {}
self._curves: dict[tuple[str, str], dict | None] = {}
def curve(self, label: str, metric: str) -> dict | None:
key = (label, metric)
if key not in self._curves:
self._curves[key] = self._extract(label, metric)
return self._curves[key]
def _extract(self, label: str, metric: str) -> dict | None:
spec = self._spec_of(metric)
module = self._module(label, spec.scenario) if spec is not None else None
if module is None:
return None
from models.tea.eeg.baselines import _feature_baseline
baseline = _feature_baseline(module, spec.feature)
curve = getattr(baseline, "curva", None) # a baseline without a curve (age blocks) draws none
if curve is None:
return None
rows = curve.dropna(subset=list(PERCENTILES))
if len(rows) < 2:
return None
return {"edad_meses": [float(v) for v in rows["edad_meses"]],
**{p: [float(v) for v in rows[p]] for p in PERCENTILES}}
@staticmethod
def _spec_of(metric: str):
"""The analysis's own mapping of the stored metric code to its library feature and baseline scenario."""
from models.tea.eeg.settings import settings
return next((m for m in settings().metrics if m.code.lower() == metric), None)
def _module(self, label: str, scenario: str):
modules = self._modules.setdefault(label, {})
if scenario not in modules:
modules[scenario] = self._load(label, scenario)
return modules[scenario]
def _load(self, label: str, scenario: str):
version = self._version(label, scenario)
if version is None:
return None
try:
registry = self._registry if self._registry is not None else _default_registry()
loader = self._loader if self._loader is not None else _default_loader()
return loader(registry.resolve("tea", scenario, version).model_uri)
except Exception: # the registry may be unreachable or the artifact unloadable; the curve is omitted
return None
@staticmethod
def _version(label: str, scenario: str) -> str | None:
"""The version the label pins for the scenario, looked up among its `;`-joined baseline names."""
for name_version in label.split(";"):
name, _, version = name_version.rpartition("/")
if name.removeprefix("tea-") == scenario and version:
return version
return None
def _default_registry():
from models.io.registry import registry
return registry
def _default_loader():
from models.tea.eeg.baselines import _load
return _load
_shared: BaselineCurves | None = None
def baseline_curves() -> BaselineCurves:
"""The process-wide loader: each label's module is loaded once per deployment."""
global _shared
if _shared is None:
_shared = BaselineCurves()
return _shared
+3 -18
View File
@@ -11,7 +11,7 @@ import json
from datetime import datetime, timedelta
from pathlib import Path
from webapi.compositions import CompositionAnswer, CompositionDefinition, category_groups
from webapi.compositions import CompositionAnswer, CompositionDefinition
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
@@ -24,7 +24,6 @@ EXCLUDED = "measure-population-exclusion"
FIGURES = f"{STRUCTURE}/figuras"
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
CATEGORY_GROUP = f"{STRUCTURE}/categoria-grupo"
CONTRACT = f"{STRUCTURE}/contrato"
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
POPULATION_LABELS = {
@@ -88,16 +87,9 @@ def measure_resource(definition, title: str, description: str) -> dict:
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
category = meta.get("categoria", {})
# Optional and additive: a category's group (`grupo`) and each group's caption (`categoria-grupo`), only when the
# composition declares them; a client that doesn't know them reads the labels alone.
extensions += [{"url": CATEGORY_LABEL, "extension": [
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
{"url": "color", "valueString": spec["color"]},
*([{"url": "grupo", "valueCode": spec["grupo"]}] if spec.get("grupo") else [])]}
for code, spec in category.get("etiquetas", {}).items()]
extensions += [{"url": CATEGORY_GROUP, "extension": [
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": caption}]}
for code, caption in category_groups(definition.url, category).items()]
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
if meta.get("requiere_validacion"):
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
resource = {
@@ -149,20 +141,13 @@ def _groups(definition, result) -> list[dict]:
result.total)]}
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
category = definition.category.value
# A stratum value's caption, as a proportion's strata have it (`_label`), or from `meta.etiquetas_estrato`,
# which stays out of the strata's spec so the report's key doesn't change.
spec_of = {s.name: s.spec for s in definition.strata}
captions = definition.meta.get("etiquetas_estrato", {})
def caption(name: str, value: str) -> str | None:
return _label(spec_of.get(name, {}), value) or captions.get(name, {}).get(value)
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
for c, n in sorted(result.categories.items())]}]
for name, by_value in result.strata.items():
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
"stratum": [{"component": [
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v, caption(name, v))},
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
], "population": [_count("initial-population", n)]}
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
+51 -206
View File
@@ -4,29 +4,29 @@ Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, n
at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its
stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. The views carry the age the analysis compared
the references at and, per metric, the registered label of the baseline that comparison used, from which the metric
observations draw the baseline's full centile curve. The ADOS-2 association model reaches the summary as one
`RiskAssessment` per patient (a prediction per association row of `tea_paciente_relacion_ados2`), and stays out
while no model row scored the patient's study EEG.
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
Until the domain expert validates the age baselines, every alteration stays hidden (`alterations_validated`):
Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`):
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
"""
import hashlib
import os
from dataclasses import dataclass, field
from dataclasses import dataclass
from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
from webapi.fhir.eeg_curves import PERCENTILES, baseline_curves
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
("EEG", "fecha_eeg", "EEG de buena calidad"))
CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"),
("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"),
("calidad_correlacion", "Baja correlación entre canales", "canales"),
("calidad_sin_senal", "Canales planos o sin señal", "canales"),
("calidad_linea", "Ruido de la línea eléctrica", "dB"))
ALTERED = ("aumentado", "disminuido")
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
@@ -34,35 +34,26 @@ ICD10 = "http://hl7.org/fhir/sid/icd-10"
CATALOG = f"{CODE_SYSTEM}/tea-catalogo"
STAGE_DATE = f"{STRUCTURE}/fecha-etapa"
AGE_GROUP = f"{STRUCTURE}/grupo-edad"
CURVE = f"{STRUCTURE}/curva-referencia"
DEFAULT_SALT = "dev-simulado"
FOLLOW_UP = table("tea_seguimiento", *map(column, (
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
EEGS = table("tea_paciente_eegs", *map(column, (
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "edad_meses", "nivel",
"fraccion_limpia", "canales_malos", "ruido_linea_db", "calidad", "valido")))
CHECKS = table("tea_paciente_eeg_criterios", *map(column, (
"procedimiento_id", "pac_id", "criterio", "electrodo", "valor", "valor_texto", "bajo", "alto", "anormal",
"decisivo", "etiqueta", "unidad")))
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido",
*(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno")))))
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "modelo",
"valor_z", "estado")))
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
"valor", "valor_z")))
"valor")))
ADOS2 = table("tea_paciente_ados2", *map(column, (
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
"etiqueta", "puntaje", "puntaje_algoritmo")))
RELACION = table("tea_paciente_relacion_ados2", *map(column, (
"pac_id", "procedimiento_id", "version", "validado", "nivel", "n_cohorte", "biomarcador", "zona", "tipo",
"resultado", "evento", "odds_ratio", "ic_inf", "ic_sup", "q", "valor_z", "probabilidad",
"probabilidad_referencia", "observado")))
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
def alterations_validated() -> bool:
"""Whether the domain expert validated the EEG analysis's age baselines and the effect texts
"""Whether the domain expert validated the reference ranges, effect texts and quality thresholds
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
@@ -96,7 +87,6 @@ class Episode:
cutoff: date
eegs: list[dict]
metrics: list[dict]
checks: list[dict] = field(default_factory=list)
@property
def pseudonym(self) -> str:
@@ -158,16 +148,17 @@ class Episode:
def episodes(queries, cutoff: date) -> list[Episode]:
"""Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics."""
eegs, metrics, checks = (_rows(queries, select(EEGS)), _rows(queries, select(METRICS)),
_rows(queries, select(CHECKS)))
eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS))
by_child = {}
for child in _rows(queries, select(FOLLOW_UP)):
if (_date(child["fecha_mchat"]) or date.max) <= cutoff:
by_child[child["pac_id"]] = Episode(child, cutoff, [], [])
for rows, kind in ((eegs, "eegs"), (metrics, "metrics"), (checks, "checks")):
for row in rows:
if row["pac_id"] in by_child:
getattr(by_child[row["pac_id"]], kind).append(row)
for eeg in eegs:
if eeg["pac_id"] in by_child:
by_child[eeg["pac_id"]].eegs.append(eeg)
for metric in metrics:
if metric["pac_id"] in by_child:
by_child[metric["pac_id"]].metrics.append(metric)
return list(by_child.values())
@@ -238,61 +229,26 @@ def condition(e: Episode, simulated: bool) -> dict | None:
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulated: bool) -> list[dict]:
"""One `Observation` per quality check the EEG analysis evaluated, as the analysis's own validation report writes
it (`tea.validation.fhir`): its code in the analysis's code system, its value (a quantity or a text), whether it
was abnormal (A/N), its limit as the reference range, and as components the bad channel's electrode and whether
the check alone can make the EEG not valid. Study-wide checks first, then the bad channels by electrode."""
from tea.validation.fhir import INTERP, SYSTEM
def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]:
observations = []
mine = [c for c in checks if c["procedimiento_id"] == eeg["procedimiento_id"]]
for c in sorted(mine, key=lambda c: (c["electrodo"] is not None, c["electrodo"] or "", c["criterio"])):
code, unit = c["criterio"].replace("_", "-"), c["unidad"]
quantity = (lambda v: {"value": float(v), **({"unit": unit} if unit else {})})
resource = {
"resourceType": "Observation",
"id": "-".join(p for p in ("calidad", code, c["electrodo"], str(eeg["procedimiento_id"])) if p),
"status": "final", "code": {"coding": [coding(SYSTEM, code, c["etiqueta"] or code)],
"text": c["etiqueta"] or code},
for name, label, unit in CRITERIA:
if eeg[name] is None:
continue
value = ({"valueInteger": int(eeg[name])} if unit == "canales"
else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}})
observations.append(tagged({
"resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": concept(CATALOG, f"eeg.{name}", label),
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"interpretation": [concept(INTERP, "A" if c["anormal"] else "N")],
}
if c["valor"] is not None:
resource["valueQuantity"] = quantity(c["valor"])
elif c["valor_texto"] is not None:
resource["valueString"] = c["valor_texto"]
limits = {k: quantity(c[v]) for k, v in (("low", "bajo"), ("high", "alto")) if c[v] is not None}
if limits:
resource["referenceRange"] = [limits]
resource["component"] = [
*([{"code": {"text": "electrode"}, "valueString": c["electrodo"]}] if c["electrodo"] else []),
{"code": {"text": "decisive"}, "valueBoolean": bool(c["decisivo"])},
]
observations.append(tagged(resource, simulated))
**value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")],
}, simulated))
return observations
def curve_extension(label: str, curve: dict) -> dict:
"""The reference curve as one nested extension on the metric observation. `fuente` is the baseline's registered
label and `estado` the alterations validation gate (`TEA_ALTERACIONES_VALIDADAS`); each series is a run of
sub-extensions, one per point, read back in order (`edad-meses`, then the five percentiles), because a FHIR
extension holds scalars, not arrays."""
series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES))
return {"url": CURVE, "extension": [
{"url": f"{CURVE}/fuente", "valueString": label},
{"url": f"{CURVE}/estado", "valueString": "validada" if alterations_validated() else "pendiente"},
*({"url": f"{CURVE}/{name}", "valueDecimal": float(value)} for name, values in series for value in values)]}
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
simulated: bool, curves=None) -> list[dict]:
"""One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's
observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG
as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label
(`modelo`) and a loader, the observation also carries the baseline's full centile curve as an extension. A value
without a z is a metric the baseline couldn't score (none in production, or an age it doesn't cover): no
interpretation."""
simulated: bool) -> list[dict]:
"""One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or
why it couldn't be evaluated) and one per metric with a component per electrode."""
from webapi.fhir.terminology import TEA_EEG
observations = []
@@ -302,49 +258,36 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()}
if m["valor"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed")
if m["valor"] is None or m["valor_z"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown")
else:
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
if m["valor"] is not None and m["valor_z"] is not None:
resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get(
m["estado"], "N"))]
resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"),
"valueQuantity": {"value": round(float(m["valor_z"]), 2)}}]
if m["ref_mediana"] is not None:
resource["component"].append({
"code": concept(f"{CODE_SYSTEM}/puntaje", "mediana", "Mediana de la referencia a la edad"),
"valueQuantity": {"value": float(m["ref_mediana"]), "unit": spec["unidad"]}})
if m["ref_min"] is not None:
resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]},
"high": {"value": float(m["ref_max"]), "unit": spec["unidad"]},
"text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}]
if curves is not None and m.get("modelo"):
curve = curves.curve(m["modelo"], m["metrica"])
if curve is not None:
resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve))
observations.append(tagged(resource, simulated))
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]
and x["valor_z"] is not None]
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]]
if at:
observations.append(tagged({
"resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]),
"valueQuantity": {"value": round(float(x["valor_z"]), 2)}}
"valueQuantity": {"value": float(x["valor"])}}
for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated))
return observations
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
checks: list[dict] = (), curves=None) -> list[dict]:
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]:
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
no result beyond its quality, and the alterations stay out until validated. The report carries the recording's
duration, channel count and the age the analysis compared the references at as extensions, and each metric
observation the baseline's full centile curve when its label resolves (`curves`)."""
quality = quality_observations(eeg, list(checks), pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves)
no result beyond its quality, and the alterations stay out until validated."""
quality = quality_observations(eeg, pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
if eeg["valido"] == 1 and alterations_validated() else [])
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
@@ -355,105 +298,20 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered],
"conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]}
if eeg["calidad"] != "SIN_ANALIZAR":
from tea.validation.fhir import SYSTEM
report["conclusionCode"].append(concept(SYSTEM, "valid" if eeg["valido"] == 1 else "not-valid"))
if eeg["duracion_min"] is not None or eeg["edad_meses"] is not None or eeg["canales"] is not None:
if eeg["duracion_min"] is not None or eeg["canales"] is not None:
report["extension"] = [e for e in (
{"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])}
if eeg["duracion_min"] is not None else None,
{"url": f"{STRUCTURE}/edad-meses", "valueDecimal": float(eeg["edad_meses"])}
if eeg["edad_meses"] is not None else None,
{"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
) if e]
if eeg["calidad"] == "SIN_ANALIZAR":
report["conclusion"] = "EEG sin analizar todavía: no es válido para el estudio."
elif eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio" + (
f" (nivel de triaje: {eeg['nivel']})." if eeg["nivel"] else ".")
if eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio."
return [procedure, tagged(report, simulated), *quality, *altered]
def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_id: int | None,
simulated: bool) -> dict | None:
"""The association model as one `RiskAssessment`: a prediction per association row that scored the study's EEG,
the clearest cohort association (lowest q) first. The model's version, expert validation, level and cohort size
sit on the resource; each prediction carries the outcome (the ADOS-2 item or domain) and the probability the
model gives the patient, and as extensions the EEG metric and scalp zone, the patient's z, the cohort's odds
ratio with its confidence interval and q, the reference probability (z = 0) and the outcome observed in the
patient's ADOS-2. Zone and outcome labels come from the code systems, not from the row. Without rows there is
no resource."""
if not rows:
return None
from webapi.fhir.terminology import DOMINIOS_ADOS2, TEA_EEG, ados2_resultados
resultados, metricas, zonas = ados2_resultados(), TEA_EEG["metricas"], TEA_EEG["zonas"]
def prediction(f: dict) -> dict:
if f["tipo"] == "item":
code = f"ados2.{f['resultado']}"
outcome = concept(CATALOG, code, resultados.get(code, f["resultado"]))
else:
outcome = concept(f"{CODE_SYSTEM}/ados2-dominio", f["resultado"],
DOMINIOS_ADOS2.get(f["resultado"], f["resultado"]))
return {
"outcome": outcome,
"probabilityDecimal": float(f["probabilidad"]),
"extension": [
{"url": f"{STRUCTURE}/biomarcador",
"valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-metrica", f["biomarcador"],
metricas.get((f["biomarcador"] or "").lower(), {}).get("etiqueta"))},
{"url": f"{STRUCTURE}/zona", "valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-zona", f["zona"],
zonas.get(f["zona"], f["zona"]))},
*([{"url": f"{STRUCTURE}/tipo", "valueString": f["tipo"]}] if f["tipo"] else []),
*([{"url": f"{STRUCTURE}/evento", "valueString": f["evento"]}] if f["evento"] else []),
*([{"url": f"{STRUCTURE}/valor-z", "valueDecimal": float(f["valor_z"])}]
if f["valor_z"] is not None else []),
*([{"url": f"{STRUCTURE}/odds-ratio", "valueDecimal": float(f["odds_ratio"])}]
if f["odds_ratio"] is not None else []),
*([{"url": f"{STRUCTURE}/ic-inf", "valueDecimal": float(f["ic_inf"])}]
if f["ic_inf"] is not None else []),
*([{"url": f"{STRUCTURE}/ic-sup", "valueDecimal": float(f["ic_sup"])}]
if f["ic_sup"] is not None else []),
*([{"url": f"{STRUCTURE}/q", "valueDecimal": float(f["q"])}] if f["q"] is not None else []),
*([{"url": f"{STRUCTURE}/probabilidad-referencia", "valueDecimal":
float(f["probabilidad_referencia"])}] if f["probabilidad_referencia"] is not None else []),
*([{"url": f"{STRUCTURE}/observado", "valueInteger": int(f["observado"])}]
if f["observado"] is not None else []),
],
}
primero = rows[0]
resource = {
"resourceType": "RiskAssessment", "id": f"relacion-ados2-{pseudonym}", "status": "final",
"subject": {"reference": f"Patient/{pseudonym}"},
"code": {"coding": [coding(f"{CODE_SYSTEM}/tea-relacion-ados2", "modelo",
"Modelo de asociación de alteraciones del EEG con el ADOS-2")],
"text": "Asociación de alteraciones del EEG con el ADOS-2"},
"extension": [
{"url": f"{STRUCTURE}/modelo-version", "valueString": primero["version"]},
{"url": f"{STRUCTURE}/modelo-validado", "valueBoolean": primero["validado"] == 1},
*([{"url": f"{STRUCTURE}/modelo-nivel", "valueString": primero["nivel"]}]
if primero["nivel"] else []),
*([{"url": f"{STRUCTURE}/modelo-n-cohorte", "valueInteger": int(primero["n_cohorte"])}]
if primero["n_cohorte"] is not None else []),
],
"prediction": [prediction(f) for f in sorted(
rows, key=lambda f: (f["q"] is None, f["q"] or 0, f["biomarcador"] or "", f["resultado"] or ""))],
"basis": [{"reference": f"DiagnosticReport/eeg-{primero['procedimiento_id']}"},
*([{"reference": f"Observation/ados2-{ados2_id}"}] if ados2_id is not None else [])],
}
if fecha is not None:
resource["occurrenceDateTime"] = _date(fecha).isoformat()
return tagged(resource, simulated)
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
items, each item with its algorithm score."""
from webapi.fhir.terminology import DOMINIOS_ADOS2
if not rows:
return None
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
@@ -470,7 +328,7 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
if first["clasificacion"]:
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
for domain, label in DOMINIOS_ADOS2.items():
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
@@ -483,31 +341,18 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
"""The `$resumen-tea` collection: the patient, its screening episode (with its age group), its first ADOS-2 and
the EEG the study uses, as of today, and the ADOS-2 association model as one `RiskAssessment` when model rows
scored the study's EEG."""
"""The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today."""
pseudonym = seudonimo(pac_id, salt())
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
ados2_rows = _rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id))
ados2 = ados2_observation(ados2_rows, pseudonym, simulated)
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
resources += [ados2] if ados2 else []
first_ados2 = min((r for r in ados2_rows if r["fecha_ados2"] is not None),
key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]), default=None)
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
if child is not None:
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)),
_rows(queries, select(CHECKS).where(CHECKS.c.pac_id == pac_id)))
resources.append(episode_of_care(e, simulated))
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)))
eeg = e.study_eeg()
if eeg is not None:
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks,
curves=baseline_curves())
riesgo = relacion_ados2(_rows(queries, select(RELACION).where(RELACION.c.pac_id == pac_id)), pseudonym,
eeg["fecha_eeg"] if eeg is not None else None,
first_ados2["procedimiento_id"] if first_ados2 is not None else None, simulated)
if riesgo:
resources.append(riesgo)
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated)
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
+4 -20
View File
@@ -1,38 +1,33 @@
# TEA's EEG vocabulary for the FHIR answers: what each metric's state may mean (`efectos`, by state), and where each
# 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
# The effect texts are placeholders pending the domain expert's review, like the age baselines they go with.
# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where
# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`.
[metricas.ritmo_posterior]
etiqueta = "Ritmo posterior"
unidad = "Hz"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."]
[metricas.husos_sueno_n2]
etiqueta = "Husos de sueño N2"
unidad = "husos/min"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
[metricas.husos_sueno_n3]
etiqueta = "Husos de sueño N3"
unidad = "husos/min"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
[metricas.picos_paroxisticos]
etiqueta = "Picos paroxísticos"
unidad = "picos/min"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."]
[metricas.gradiente_anteroposterior]
etiqueta = "Gradiente anteroposterior"
unidad = "pendiente"
efectos.normal = ["Dentro de lo esperado para la edad."]
unidad = "razón posterior/anterior"
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."]
@@ -56,14 +51,3 @@ P4 = [0.33, -0.4]
T6 = [0.65, -0.47]
O1 = [-0.25, -0.77]
O2 = [0.25, -0.77]
# The scalp zones the association model relates an EEG alteration in with an ADOS-2 outcome, as the `tea` library
# codes them: what each zone is called on screen. A code outside this list shows as written.
[zonas]
frontal_izq = "Frontal izquierda"
frontal_der = "Frontal derecha"
central = "Central"
temporal_izq = "Temporal izquierda"
temporal_der = "Temporal derecha"
parietal = "Parietal"
occipital = "Occipital"
+3 -27
View File
@@ -1,7 +1,6 @@
"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's
catalog (`core/catalogos/<domain>.toml`: studies, results and their values), TEA's screening stages and diagnostic
results, TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under
the analysis's own code system with the catalog's labels."""
results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`)."""
import tomllib
from pathlib import Path
@@ -14,14 +13,6 @@ STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psico
("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG"))
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
DOMINIOS_ADOS2 = {"SA": "Afecto social", "RRB": "Comportamiento restringido y repetitivo"}
def ados2_resultados() -> dict[str, str]:
"""The ADOS-2 results' labels from the domain catalog, by their catalog code (`ados2.sa_b9`): what an
association row's outcome shows as."""
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["ados2"]["resultados"]
return {f"ados2.{name}": spec["etiqueta"] for name, spec in results.items()}
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
@@ -47,18 +38,6 @@ def catalog(domain: str) -> dict:
return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True)
def eeg_checks() -> dict:
"""The EEG analysis's quality checks (`CriterioEeg`), under the code system its validation report uses, each with
the catalog's label of its `eeg.calidad_<check>` result."""
from core.tea.enums import CriterioEeg
from tea.validation.fhir import SYSTEM
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["eeg"]["resultados"]
concepts = [{"code": c.value, "display": results[f"calidad_{c.value.replace('-', '_')}"]["etiqueta"]}
for c in CriterioEeg]
return {**_code_system("tea-eeg-criterio", "Reglas de calidad del EEG", concepts), "url": SYSTEM}
def tea_code_systems() -> dict[str, dict]:
metrics = [{"code": code, "display": spec["etiqueta"], "property": [
{"code": "unidad", "valueString": spec["unidad"]},
@@ -69,13 +48,10 @@ def tea_code_systems() -> dict[str, dict]:
_code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]),
_code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]),
{**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics),
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-normal", "type": "string"},
{"code": "efecto-aumentado", "type": "string"}, {"code": "efecto-disminuido", "type": "string"}]},
eeg_checks(),
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"},
{"code": "efecto-disminuido", "type": "string"}]},
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
_code_system("tea-eeg-zona", "Zonas del cuero cabelludo",
[{"code": z, "display": e} for z, e in TEA_EEG["zonas"].items()]),
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
{"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"},
{"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]),
-5
View File
@@ -138,11 +138,6 @@ def coerce_postal_code(v: Any) -> Any:
# SQLite and is not in the migrations, so the format is enforced here.
CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
# A short code of a natural key made of bounded VARCHAR(32) columns (`relacion_ados2`): an over-long value is a
# validation error here rather than a `Data too long` failure at insert on MySQL/Postgres. Optional, like every
# TEA field (see `tea/pacientes.py`).
ShortKey = Annotated[Optional[Annotated[str, StringConstraints(max_length=32)]], BeforeValidator(optional_str)]
def edf_file(v: Any) -> Any:
"""`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment).
+12 -14
View File
@@ -25,13 +25,13 @@ from persistance.cama import paciente_repository as cama_paciente_repository
from persistance.repository import Repository
from webapi.imports.schemas.base import ImportSchema
from persistance.tea import ados2_repository as tea_ados2_repository
from persistance.tea import eeg_metrica_electrodo_repository as tea_eeg_metrica_electrodo_repository
from persistance.tea import eeg_metrica_repository as tea_eeg_metrica_repository
from persistance.tea import eeg_repository as tea_eeg_repository
from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluacion_neuropediatrica_repository
from persistance.tea import mchat_repository as tea_mchat_repository
from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository
from persistance.tea import pacientes_repository as tea_pacientes_repository
from persistance.tea import relacion_ados2_paciente_repository as tea_relacion_ados2_paciente_repository
from persistance.tea import relacion_ados2_repository as tea_relacion_ados2_repository
from webapi.imports.schemas.cacu.biometria_hematica import (
BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema,
)
@@ -60,14 +60,14 @@ from webapi.imports.schemas.cama.ordenes_estudio import (
from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
from webapi.imports.schemas.tea.eeg import EegImportSchema
from webapi.imports.schemas.tea.eeg_metrica import EegMetricaImportSchema
from webapi.imports.schemas.tea.eeg_metrica_electrodo import EegMetricaElectrodoImportSchema
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema
from webapi.imports.schemas.tea.mchat import MchatImportSchema
from webapi.imports.schemas.tea.ordenes_estudio import (
OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema,
)
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
from webapi.imports.schemas.tea.relacion_ados2 import RelacionAdos2ImportSchema
from webapi.imports.schemas.tea.relacion_ados2_paciente import RelacionAdos2PacienteImportSchema
@dataclass(frozen=True)
@@ -187,16 +187,14 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
# one row.
conflict_fields=("eeg_id_registro_laboratorio",),
),
"tea.RelacionAdos2": EntitySpec(
schema=RelacionAdos2ImportSchema,
repository=tea_relacion_ados2_repository,
# The natural key the import and the `tea` library merge model rows on (the table's unique constraint).
conflict_fields=("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"),
"tea.EegMetrica": EntitySpec(
schema=EegMetricaImportSchema,
repository=tea_eeg_metrica_repository,
conflict_fields=("met_id",),
),
"tea.RelacionAdos2Paciente": EntitySpec(
schema=RelacionAdos2PacienteImportSchema,
repository=tea_relacion_ados2_paciente_repository,
# One probability per EEG and association row (the table's unique constraint).
conflict_fields=("rap_rel_id", "rap_eeg_id"),
"tea.EegMetricaElectrodo": EntitySpec(
schema=EegMetricaElectrodoImportSchema,
repository=tea_eeg_metrica_electrodo_repository,
conflict_fields=("mel_id",),
),
}
+9 -4
View File
@@ -1,14 +1,15 @@
"""Import schema for `core.tea.models.Eeg`: the study and its EDF, and the sleep, channels, duration and line noise
a report may state. The verdict, quality checks and metrics are the EEG analysis's, written from the EDF, never
imported."""
"""Import schema for `core.tea.models.Eeg`: the study, its EDF and what the EEG analysis writes back (sleep,
channels, duration and the five quality criteria)."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Bounded, EdfFile, FlexDate, OptionalStr, SourceId
_CHANNELS = Bounded(int, 0, None)
class EegImportSchema(ImportSchema):
# The source's own id, kept so the analysis rows that reference it still point at this record.
# The source's own id, kept so the metrics that reference it still point at this record.
eeg_id: SourceId = None
eeg_pac_id: Optional[int] = None
eeg_ord_id: OptionalStr = None
@@ -17,5 +18,9 @@ class EegImportSchema(ImportSchema):
eeg_con_sueno: Bounded(int, 0, 1) = None
eeg_canales: Bounded(int, 1, 256) = None
eeg_duracion_min: Bounded(float, 0, None) = None
eeg_canales_amplitud: _CHANNELS = None
eeg_canales_alta_frecuencia: _CHANNELS = None
eeg_canales_correlacion: _CHANNELS = None
eeg_canales_sin_senal: _CHANNELS = None
eeg_ruido_linea_db: Bounded(float, 0, None) = None
eeg_estudio: EdfFile = None
+16
View File
@@ -0,0 +1,16 @@
"""Import schema for `core.tea.models.EegMetrica`: a metric the EEG analysis measured. A blank value is a metric
that can't be evaluated."""
from typing import Optional
from core.tea.enums import MetricaEeg
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr, SourceId
_METRICA_CATALOG = Catalog(MetricaEeg)
class EegMetricaImportSchema(ImportSchema):
met_id: SourceId = None
met_eeg_id: OptionalStr = None
met_codigo: CatalogValue(_METRICA_CATALOG) = None
met_valor: Optional[float] = None
@@ -0,0 +1,12 @@
"""Import schema for `core.tea.models.EegMetricaElectrodo`: a metric's z-score at one 10-20 electrode."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import OptionalStr, SourceId
class EegMetricaElectrodoImportSchema(ImportSchema):
mel_id: SourceId = None
mel_met_id: OptionalStr = None
mel_electrodo: OptionalStr = None
mel_valor: Optional[float] = None
@@ -1,43 +0,0 @@
"""Import schema for `core.tea.models.RelacionAdos2`: one association of an EEG alteration in a scalp zone with an
ADOS-2 item or domain outcome, per fitted model version. `rel_evento` is the outcome event as a threshold on its
score, machine-readable (`>=2`); it is shown as written, never parsed."""
from typing import Annotated, Optional
from pydantic import Field, model_validator
from core.tea.enums import MetricaEeg, NivelRelacionAdos2
from core.tea.models import ADOS2_ITEMS
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, OptionalStr, ShortKey, SourceId
_NIVEL_CATALOG = Catalog(NivelRelacionAdos2)
_BIOMARCADOR_CATALOG = Catalog(MetricaEeg)
_DOMINIOS_ADOS2 = {"SA", "RRB"}
class RelacionAdos2ImportSchema(ImportSchema):
rel_id: SourceId = None
# The natural key the import merges model rows on: rel_version, rel_biomarcador, rel_zona, rel_resultado.
rel_version: ShortKey = None
rel_nivel: CatalogValue(_NIVEL_CATALOG) = None
rel_validado: Bounded(int, 0, 1) = None
rel_n_cohorte: Bounded(int, 1, None) = None
rel_biomarcador: CatalogValue(_BIOMARCADOR_CATALOG) = None
rel_zona: ShortKey = None
rel_tipo: CatalogValue(_NIVEL_CATALOG) = None
rel_resultado: ShortKey = None
rel_evento: OptionalStr = None
rel_or: Optional[Annotated[float, Field(gt=0)]] = None
rel_ic_inf: Bounded(float, 0, None) = None
rel_ic_sup: Bounded(float, 0, None) = None
rel_q: Bounded(float, 0, 1) = None
@model_validator(mode="after")
def _outcome_code_and_interval_checks(self):
if self.rel_ic_inf is not None and self.rel_ic_sup is not None and self.rel_ic_inf > self.rel_ic_sup:
raise ValueError("rel_ic_inf no puede ser mayor que rel_ic_sup")
if self.rel_tipo is not None and self.rel_resultado is not None:
validos = set(ADOS2_ITEMS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value else _DOMINIOS_ADOS2
if self.rel_resultado not in validos:
raise ValueError(f"'{self.rel_resultado}' no es un código de {self.rel_tipo} del ADOS-2")
return self
@@ -1,16 +0,0 @@
"""Import schema for `core.tea.models.RelacionAdos2Paciente`: one patient's z and model probability for an
association row, per EEG. The observed outcome stays in `ados2`, never here."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Bounded, SourceId
class RelacionAdos2PacienteImportSchema(ImportSchema):
rap_id: SourceId = None
# The natural key the import merges patient rows on: rap_rel_id, rap_eeg_id.
rap_rel_id: SourceId = None
rap_eeg_id: SourceId = None
rap_valor_z: Optional[float] = None
rap_probabilidad: Bounded(float, 0, 1) = None
rap_probabilidad_referencia: Bounded(float, 0, 1) = None
+1 -2
View File
@@ -13,7 +13,6 @@ from datetime import date
from pathlib import Path
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
from webapi.orchestration.runner import run
@@ -45,7 +44,7 @@ def main(argv: list[str] | None = None) -> None:
return
logging.basicConfig(level=logging.INFO, format="%(message)s")
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project))
estimators=live_estimators(args.project))
for paso in run(ctx, only=args.only):
print(f"{paso.name:20} {paso.seconds:6.1f} s")
+1 -4
View File
@@ -1,7 +1,7 @@
"""Lo que recibe cada paso del ciclo."""
import os
from collections.abc import Callable, Mapping
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import date
from pathlib import Path
@@ -39,8 +39,5 @@ class Context:
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()`
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada.
estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
# The domain's EEG analysis (`webapi.orchestration.eeg.live_eeg_analysis`): run by the `analyze_eeg` step before
# the silver load, it writes the analysis of each stored EDF to bronze. Without it, that step does nothing.
eeg_analysis: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
repos: Any = field(default=None, compare=False, repr=False)
+2 -12
View File
@@ -11,7 +11,6 @@ Bronce lo escribe la ingesta, fuera del ciclo.
"""
import logging
from dataclasses import asdict
from datetime import date, datetime
from functools import partial
from importlib import import_module
@@ -82,17 +81,8 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
return counts
def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]:
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo`.
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
if ctx.eeg_analysis is None:
return {}
return asdict(ctx.eeg_analysis())
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis.
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
"""
-29
View File
@@ -1,29 +0,0 @@
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load.
`EEG_ANALYSIS_CLUSTER` says where the batch runs: `auto` (the default: the scheduler in `DASK_SCHEDULER_ADDRESS` if
set, otherwise a local cluster), `local`, `remote`, `sync` (in the cycle's own process), or `off`, which leaves the
analysis out of the cycle (`python -m models tea analyze` and `POST /governance/eeg/run` still run it).
"""
import os
from collections.abc import Callable
from functools import partial
from typing import Any
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
CLUSTERS = ("auto", "local", "remote", "sync")
def cluster() -> str:
value = os.environ.get(CLUSTER_ENV, "auto")
if value not in (*CLUSTERS, "off"):
raise ValueError(f"{CLUSTER_ENV} must be one of {', '.join((*CLUSTERS, 'off'))}, not {value!r}")
return value
def live_eeg_analysis(domain: str) -> Callable[[], Any] | None:
"""The domain's EEG analysis for the cycle, or none: only TEA has one, and `off` leaves it out."""
if domain != "tea" or cluster() == "off":
return None
from models.eeg_analysis import analyze_pending
return partial(analyze_pending, cluster=cluster())
+2 -2
View File
@@ -204,8 +204,8 @@ def _tipo_de_valor(resultado: dict, resultado_id: str) -> str:
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.")
if tipo_valor != "codigo" and "valores" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.")
if tipo_valor != "externo" and "sistema" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.")
if tipo_valor not in ("codigo", "externo") and "sistema" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo o externo lleva sistema, no uno de tipo {tipo_valor}.")
if tipo_valor != "numero" and "unidad" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.")
return tipo_valor
+1
View File
@@ -22,6 +22,7 @@ def de_derechohabiente(paciente) -> dict:
"dependencia": texto_limpio(paciente.pac_dependencia),
"parentesco": texto_limpio(paciente.pac_parentesco),
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
"fecha_defuncion": paciente.pac_fecha_defuncion,
}
+9 -42
View File
@@ -3,10 +3,8 @@
- 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;
- what the EEG analysis writes: the EEG's verdict and study-wide quality checks (`eeg_criterio` without an
electrode) and each metric with its deviation from the age baseline and the baseline's registered label are results
of the EEG's recording, not procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an
electrode are `parte`s of the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric.
- 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 (
@@ -20,7 +18,6 @@ from core.tea.models import (
ADOS2_ITEMS,
Ados2,
Eeg,
EegCriterio,
EegMetrica,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
@@ -53,20 +50,7 @@ def _metrica(f) -> str | None:
return None if codigo is None else codigo.lower()
def _criterio(f) -> str | None:
"""A quality check's results in the catalog: `calidad_` and its code in snake case (`clean-windows` ->
`calidad_clean_windows`)."""
codigo = texto_limpio(f.cri_codigo)
return None if codigo is None else "calidad_" + codigo.lower().replace("-", "_")
def _valor_de_criterio(f):
return f.cri_valor if f.cri_valor is not None else texto_limpio(f.cri_valor_texto)
SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG)
EEG_DEL_CRITERIO = Padre(estudio_id="eeg", clase="toma", fuente_id="cri_eeg_id", tabla=EEG)
DEVIATION = ("z", "fuera", "p5", "mediana", "p95")
DESDE_STAGING = (
@@ -111,43 +95,26 @@ DESDE_STAGING = (
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_valido": "eeg.valido",
"eeg_nivel": "eeg.nivel",
"eeg_fraccion_limpia": "eeg.fraccion_limpia",
"eeg_canales_malos": "eeg.canales_malos",
"eeg_edad_meses": "eeg.edad_meses",
"eeg_con_sueno": "eeg.con_sueno",
"eeg_canales": "eeg.canales",
"eeg_duracion_min": "eeg.duracion_min",
"eeg_ruido_linea_db": "eeg.ruido_linea",
"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(
EegCriterio, "cri_id", "toma", estudio_id="eeg", paciente=None, observa_en=EEG_DEL_CRITERIO,
solo_si=lambda f: f.cri_electrodo is None,
derivadas={"criterio": _criterio, "valor": _valor_de_criterio},
resultados={"valor": "eeg.{criterio}", "cri_anormal": "eeg.{criterio}_anormal",
"cri_decisivo": "eeg.{criterio}_decisivo", "cri_bajo": "eeg.{criterio}_bajo",
"cri_alto": "eeg.{criterio}_alto"},
),
DeStaging(
EegCriterio, "cri_id", "parte", estudio_id="eeg", paciente=None, padres=(EEG_DEL_CRITERIO,),
solo_si=lambda f: f.cri_electrodo is not None,
derivadas={"criterio": _criterio, "valor": _valor_de_criterio},
columnas={"codigo_fuente": "cri_electrodo"},
resultados={"valor": "eeg.{criterio}"},
),
DeStaging(
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
derivadas={"metrica": _metrica},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION},
"met_modelo": "eeg.{metrica}_modelo"},
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}", "mel_z": "eeg.{metrica}_z"},
resultados={"mel_valor": "eeg.{metrica}"},
),
)
+1 -3
View File
@@ -106,7 +106,6 @@ class RecomputationQueue:
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
from webapi.orchestration import Context, run, steps_of
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
@@ -116,8 +115,7 @@ class RecomputationQueue:
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
try:
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio))
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",