Compare commits

..

23 Commits

Author SHA1 Message Date
alberto af054460b5 Merge pull request 'Preview of one EDF and its ADOS-2 report, analysed in memory' (#21) from feature/tea-eeg-analysis into dev 2026-11-23 12:27:54 -06:00
ulises 6452e43cad Governance TEA EEG: preview of one EDF and its ADOS-2 report analysed in memory, nothing stored 2026-11-23 12:26:19 -06:00
alberto b0b797ac15 Merge pull request 'Governance TEA EEG: cohorts, baselines zip, cluster health, jobs with progress, EDF upload' (#20) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:32 -06:00
ulises 0e6494f053 Governance TEA EEG: reference cohorts, baselines export and import, cluster health, training and analysis jobs with progress, EDF upload, EEG queries 2026-11-23 09:31:38 -06:00
Roberto Treviño Cervantes 5831fcd9d9 Cycle: skip the scenarios whose definition turns off batch_estimates 2026-11-23 00:14:14 -06:00
Roberto Treviño Cervantes bd8c7aa55a Cycle: answer each measure's latest periods after a run, so the first reader finds them stored 2026-11-23 00:06:33 -06:00
Roberto Treviño Cervantes 1048175531 CaMa survival figure: the whole cohort's points from the pipeline's survival stage 2026-11-22 23:46:57 -06:00
Roberto Treviño Cervantes 5738a9c302 Merge dev into the CaMa consolidation branch 2026-11-22 23:28:00 -06:00
edgar bf93a5fff9 Merge pull request 'CaCu follow-up: CASO status with CIS, per-status probabilities, and a cycle that estimates with every production scenario' (#19) from integration/cacu-197-conciliacion into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/19
2026-11-22 23:25:34 -06:00
Roberto Treviño Cervantes 32483249c7 Indicators cycle recomputes the CaMa survival scenario points over each new build; the figure draws them 2026-11-22 23:22:31 -06:00
Roberto Treviño Cervantes 93649a0e27 CaMa survival figure takes the points the version's pipeline published for the scenario 2026-11-22 22:59:48 -06:00
Roberto Treviño Cervantes 201ef4fb03 CaMa follow-up list: the cohort of a revision is read from the views once 2026-11-22 22:20:12 -06:00
alberto 05b0ccfce6 Merge pull request 'ADOS-2 scoring step in the indicators cycle' (#18) from feature/tea-eeg-analysis into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/18
2026-11-22 22:13:43 -06:00
Roberto Treviño Cervantes f97d1202a9 Live models: the labelled members are saved once per build and version, prepared by the indicators cycle and loaded by each API worker as it starts 2026-11-22 22:02:04 -06:00
ulises eb88cb7eb0 ADOS-2 scoring step in the indicators cycle, run after the document import commits; EEG analysis ordered before the relation steps 2026-11-22 22:01:50 -06:00
ulises 430d165594 Document sources carry any field of the target from their own columns, such as its ids; the ADOS-2 items of a SQL source's PDF upsert into the existing row 2026-11-22 21:47:16 -06:00
ulises 74303aa1b9 TEA: the cycle's relate_ados2 step between the EEG analysis and the load, and the ADOS-2 relation in FHIR 2026-11-22 21:47:16 -06:00
Roberto Treviño Cervantes f7f8af8b4c CaMa: the follow-up row carries a provisional status, priority and mammogram-to-diagnosis days; the survival menu names the patient's own scenarios 2026-11-22 21:38:43 -06:00
Roberto Treviño Cervantes 88c9694a46 CaMa: the patient import takes the recurrence variables again, recurrence trains on the cohort export, the second survival route is retired 2026-11-22 19:51:20 -06:00
Roberto Treviño Cervantes 1fbeabb872 CaMa recurrence: every scenario the patient's covariates place her in 2026-11-22 18:04:57 -06:00
edgar 71557ecbd3 Merge pull request 'CaCu: windows to diagnosis and treatment, FHIR base URL, the patient's risks per outcome' (#17) from integration/cacu-197-conciliacion into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/17
2026-11-22 13:47:01 -06:00
Roberto Treviño Cervantes cc54c1dc86 Merge the CaMa recurrence follow-up imports and /cama/recurrencia into dev 2026-11-22 09:18:27 -06:00
ulises 9a62ddcdaf CaMa recurrence: import schemas for the follow-up and the new patient variables, silver mappings and /cama/recurrencia
The patient takes the menopausal state, molecular and clinical subtype, integrative cluster, cellularity, mutation load,
Ki-67 category and source of the record; a new import entity carries the recurrence and the last contact; hormone and
anti-HER2 therapy are treatments. The route serves each cohort's scenarios, a scenario's figure and a patient's scenarios
over the live cohort build, computing the models and the bootstrap in the background and caching them per build. Includes
the survival import work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:42 -06:00
65 changed files with 3616 additions and 192 deletions
+2
View File
@@ -50,6 +50,8 @@ ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
# Aggregate import log and the live indicator queue (webapi.recomputation).
ENV WEBAPI_REPORT_DIR=/data/reportes
ENV INDICADORES_DIR=/data/indicadores
# Each API worker loads the live models' members as it starts (`webapi.model_analysis.warm`).
ENV WEBAPI_PRECALENTAR_MODELOS=1
ENV MLFLOW_DISABLE_AGENT_HINT=1
# Without it the measure routes (/<domain>/indicadores, /<domain>/fhir) aren't
# registered. The entrypoint replaces it with one compiled against the
+1
View File
@@ -0,0 +1 @@
2026-11-22T10:18:21+00:00
File diff suppressed because one or more lines are too long
+60
View File
@@ -0,0 +1,60 @@
"""What this module covers: the cycle's `relate_ados2` step (TEA's ADOS-2 association, after the EEG analysis and
before the silver load) and how the cycle gets the association (`webapi.orchestration.eeg.live_ados2_relation`).
Fixtures: none; the graph is built from `webapi.orchestration.cycle` and the association is a stand-in.
"""
from types import SimpleNamespace
import pytest
from hamilton import driver
from webapi.orchestration import cycle, run, steps_of
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import RELATION_ENV, live_ados2_relation
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_the_association_runs_after_the_analysis_and_before_the_load(proyecto):
"""Pins down: `relate_ados2` waits for `analyze_eeg` only, and `load` waits for it, so the same cycle's gold
views show the association fitted on that cycle's analysis. Fails if the association runs before the analysis
(it would fit on the previous one) or after the load."""
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 deps["relate_ados2"] == {"analyze_eeg"}
assert "relate_ados2" in deps["load"]
order = steps_of(proyecto)
assert order.index("analyze_eeg") < order.index("relate_ados2") < order.index("load")
def test_the_step_returns_the_associations_summary_or_nothing():
"""Pins down: without an association the step is a no-op, and with one it runs it once and returns its summary
as a dict. Fails if the step runs an association nobody configured, or stops reporting what it wrote."""
assert [(p.name, p.summary) for p in run(Context("cacu", 2025, 2025), only=["relate_ados2"])] == [
("relate_ados2", {})]
calls = []
def relation():
calls.append(1)
from models.ados2_relation import Summary
return Summary(version="tea-20261121T120000-abcd1234", level="domain", children=3, associations=2, scored=6)
pasos = run(Context("tea", 2025, 2025, ados2_relation=relation, repos=SimpleNamespace()), only=["relate_ados2"])
assert calls == [1]
assert pasos[0].summary["version"] == "tea-20261121T120000-abcd1234" and pasos[0].summary["scored"] == 6
def test_only_tea_has_the_association_and_it_can_be_turned_off(monkeypatch):
"""Pins down: TEA's cycle gets `models.ados2_relation.relate`, the other domains none, `ADOS2_RELATION=off`
leaves it out and an unknown value is refused. Fails if another domain starts fitting it, `off` stops working,
or a mistyped value silently counts as on."""
from models.ados2_relation import relate
monkeypatch.delenv(RELATION_ENV, raising=False)
assert live_ados2_relation("tea") is relate
assert live_ados2_relation("cama") is None
monkeypatch.setenv(RELATION_ENV, "off")
assert live_ados2_relation("tea") is None
monkeypatch.setenv(RELATION_ENV, "maybe")
with pytest.raises(ValueError, match=RELATION_ENV):
live_ados2_relation("tea")
+60
View File
@@ -0,0 +1,60 @@
"""What this module covers: the cycle's `score_ados2` step (TEA's ADOS-2 CSS and classification, before the
association and the silver load) and how the cycle gets the scoring (`webapi.orchestration.eeg.live_ados2_scoring`).
Fixtures: none; the graph is built from `webapi.orchestration.cycle` and the scoring is a stand-in.
"""
from types import SimpleNamespace
import pytest
from hamilton import driver
from webapi.orchestration import cycle, run, steps_of
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import SCORING_ENV, live_ados2_scoring
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_the_scoring_runs_before_the_analysis_the_association_and_the_load(proyecto):
"""Pins down: `score_ados2` needs only the migrated schema and `analyze_eeg` waits for it, so the CSS is written
in seconds instead of after a long EEG analysis, and still before the association and the silver load read it.
Fails if the scoring moves after the analysis, the association or the load."""
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 deps["score_ados2"] == {"migrate"}
assert deps["analyze_eeg"] == {"migrate", "score_ados2"}
order = steps_of(proyecto)
assert order.index("score_ados2") < order.index("analyze_eeg") < order.index("relate_ados2") < order.index("load")
def test_the_step_returns_the_scorings_summary_or_nothing():
"""Pins down: without a scoring the step is a no-op, and with one it runs it once and returns its summary as a
dict. Fails if the step scores when nobody configured it, or stops reporting what it did."""
assert [(p.name, p.summary) for p in run(Context("cacu", 2025, 2025), only=["score_ados2"])] == [
("score_ados2", {})]
calls = []
def scoring():
calls.append(1)
from models.ados2_scoring import Summary
return Summary(evaluations=5, scored=4, unscored=1)
pasos = run(Context("tea", 2025, 2025, ados2_scoring=scoring, repos=SimpleNamespace()), only=["score_ados2"])
assert calls == [1]
assert pasos[0].summary == {"evaluations": 5, "scored": 4, "unscored": 1}
def test_only_tea_has_the_scoring_and_it_can_be_turned_off(monkeypatch):
"""Pins down: TEA's cycle gets `models.ados2_scoring.score_pending`, the other domains none, `ADOS2_SCORING=off`
leaves it out and an unknown value is refused. Fails if another domain starts scoring, `off` stops working, or
a mistyped value silently counts as on."""
from models.ados2_scoring import score_pending
monkeypatch.delenv(SCORING_ENV, raising=False)
assert live_ados2_scoring("tea") is score_pending
assert live_ados2_scoring("cama") is None
monkeypatch.setenv(SCORING_ENV, "off")
assert live_ados2_scoring("tea") is None
monkeypatch.setenv(SCORING_ENV, "maybe")
with pytest.raises(ValueError, match=SCORING_ENV):
live_ados2_scoring("tea")
+48 -3
View File
@@ -152,13 +152,14 @@ 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, 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."""
date, the clinical scenario, the provisional status and priority of her pathway and the days from the mammogram to
the diagnosis: no pseudonym, and no source id anywhere in the body. Fails if a field is added or dropped, 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",
"escenario_clinico"} for i in cuerpo["items"])
"escenario_clinico", "estatus", "prioridad", "dias_mastografia_diagnostico"} 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", "escenario_clinico"]
@@ -419,3 +420,47 @@ def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observa
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"}]
def test_the_status_priority_and_days_follow_her_pathway():
"""Pins down: a BI-RADS 5 with no biopsy is pending and high priority, a BI-RADS 4A with no biopsy is medium, a benign
biopsy is low, a cancer without treatment is high with the days from the mammogram to its first malignant report, and
one in treatment is low. Fails if a rule changes or the days stop counting from the mammogram."""
from webapi.cama_follow_up.cohort import EN_OBSERVACION, POST_TRATAMIENTO, Fila
from webapi.cama_follow_up.listing import _item
toma = date(2026, 11, 1)
fila = lambda **k: Fila(pac_id=1, mastografia_fecha=toma, grupo_edad="50-59", **{"biopsia": None, "biopsia_fecha": None, **k})
cancer = dict(biopsia="CARCINOMA_INVASOR", biopsia_fecha=date(2026, 11, 21), primer_maligno_fecha=date(2026, 11, 21))
pendiente_alta = _item(fila(birads="BIRADS_5"))
pendiente_media = _item(fila(birads="BIRADS_4A"))
benigna = _item(fila(birads="BIRADS_4A", biopsia="BENIGNO", biopsia_fecha=date(2026, 11, 10)))
sin_tratamiento = _item(fila(birads="BIRADS_6", **cancer, escenario_clinico=EN_OBSERVACION))
en_tratamiento = _item(fila(birads="BIRADS_6", **cancer, escenario_clinico=POST_TRATAMIENTO))
assert (pendiente_alta["estatus"], pendiente_alta["prioridad"]) == ("Pendiente de biopsia", "Alta")
assert pendiente_media["prioridad"] == "Media" and pendiente_media["dias_mastografia_diagnostico"] is None
assert (benigna["estatus"], benigna["prioridad"]) == ("Biopsia benigna", "Baja")
assert (sin_tratamiento["prioridad"], sin_tratamiento["dias_mastografia_diagnostico"]) == ("Alta", 20)
assert (en_tratamiento["estatus"], en_tratamiento["prioridad"]) == ("Diagnóstico confirmado, en tratamiento", "Baja")
def test_the_same_revision_reads_the_views_once_and_another_cutoff_reads_them_again(base, app, monkeypatch):
"""Pins down: pages, filters and files of one revision (same data and cut-off) come from the cohort read the first time, and
another cut-off reads the views again. Fails if every request rebuilds the cohort (minutes on a hospital's data) or a cached
cohort answers for another cut-off."""
from webapi.cama_follow_up import listing
leidas = []
original = listing.cohorte_al
monkeypatch.setattr(listing, "cohorte_al", lambda sesion, corte: leidas.append(corte) or original(sesion, corte))
listing._COHORTES.clear()
primera = get(app, page_size=200)
get(app, page=1, page_size=5)
get(app, ruta="/cama/seguimiento/exportacion")
otra = app.get("/cama/seguimiento", query_string={"corte": "2025-10-01", "meses": 0})
assert primera.status_code == 200 and otra.status_code in (200, 403)
assert [c.isoformat() for c in leidas] == [CORTE, "2025-10-01"]
+3 -3
View File
@@ -58,15 +58,15 @@ def fake_analysis(tea_base):
@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.
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema and the quick ADOS-2 scoring.
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.
only on the next cycle), or the analysis starts waiting for steps other than the migration and the scoring.
"""
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"}
assert deps["analyze_eeg"] == {"migrate", "score_ados2"}
order = steps_of(proyecto)
assert order.index("analyze_eeg") < order.index("load")
+34 -19
View File
@@ -1,9 +1,9 @@
"""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.
EEG (the clearest cohort association, lowest q, first), the model's metadata on the resource, the outcome as an
ADOS-2 item meaning or the total CSS 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; and the code systems the
outcomes and zones are labelled from. 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`.
@@ -21,9 +21,9 @@ UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_m
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."""
"""The kit's seven children, plus a fitted model: one item row (ados2_item_07, shared enjoyment) and one domain
row (CSS) of version 0.2.0, both scored for child 1's study EEG (eeg-1b, 20 May). Child 1's ADOS-2 (ado-1) is
Module 1, where item 07 is sa_b5, scored 2, and its CSS is 7; no other child gets model rows."""
from importlib import import_module
import_module("staging.tea").insertar(sesion)
@@ -32,11 +32,11 @@ def _rows(sesion):
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_resultado="ados2_item_07", 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_resultado="CSS", rel_evento=">=8", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6,
rel_q=0.3),
])
sesion.add_all([
@@ -93,15 +93,15 @@ def test_the_summary_emits_the_model_as_one_risk_assessment(client):
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"]
assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2_item_07", "CSS"]
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
"""Pins down: a prediction has the outcome as the ADOS-2 item meaning or the CSS, under the outcome code system
with its label from `ADOS2_ITEM_MEANINGS` (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
reference probability (z = 0) and the outcome observed in the patient's ADOS-2 (item 07's algorithm score 2,
the CSS 7). 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
@@ -109,11 +109,11 @@ def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_
(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"}
"system": "https://isssteleon.org/fhir/CodeSystem/tea-ados2-resultado", "code": "ados2_item_07",
"display": "Disfrute compartido en la interacción"}
assert dominio["outcome"]["coding"][0] == {
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio", "code": "SA",
"display": "Afecto social"}
"system": "https://isssteleon.org/fhir/CodeSystem/tea-ados2-resultado", "code": "CSS",
"display": "Puntaje de severidad calibrado (CSS)"}
assert (item["probabilityDecimal"], dominio["probabilityDecimal"]) == (0.81, 0.35)
extension = _extension(item)
assert extension["biomarcador"]["valueCoding"] == {
@@ -128,7 +128,7 @@ def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_
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
assert _extension(dominio)["observado"]["valueInteger"] == 7
def test_the_summary_omits_the_model_without_rows(client):
@@ -138,3 +138,18 @@ def test_the_summary_omits_the_model_without_rows(client):
(child_2,) = episodes
bundle = get(client, f"/tea/fhir/Patient/{child_2['id']}/$resumen-tea")
assert not resources(bundle, "RiskAssessment")
def test_the_outcome_and_zone_code_systems_cover_what_the_model_writes(client):
"""Pins down: `CodeSystem/tea-ados2-resultado` has one concept per item meaning of `ADOS2_ITEM_MEANINGS`, with
its label, plus `CSS`; `CodeSystem/tea-eeg-zona` has the `tea` library's zones (`tea.contracts.ZONES`) plus `posterior` and `global`.
Fails if an outcome or zone code the model writes has no label, so the screen would show the raw code."""
from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS
from tea.contracts import ZONES
resultados = {c["code"]: c["display"] for c in get(client, "/tea/fhir/CodeSystem/tea-ados2-resultado")["concept"]}
assert set(resultados) == set(ADOS2_ITEM_MEANINGS) | {ADOS2_CSS}
assert resultados["ados2_item_11"] == "Mostrar"
assert resultados["CSS"] == "Puntaje de severidad calibrado (CSS)"
zonas = {c["code"] for c in get(client, "/tea/fhir/CodeSystem/tea-eeg-zona")["concept"]}
assert zonas == set(ZONES) | {"posterior", "global"}
+121
View File
@@ -0,0 +1,121 @@
"""Cover the bundle HTTP contract with an app client and two temporary registries.
Fails if export loses ZIP metadata, import misreports registry versions or malformed uploads succeed.
"""
import hashlib
import json
import zipfile
from dataclasses import replace
from io import BytesIO
import mlflow
import numpy as np
import pytest
from flask import Flask
from models.io.registry import PRODUCTION_ALIAS
from models.tea.eeg import bundle, train
from models.tea.eeg.analyze import ReferenceStudy, pipeline
from models.tea.eeg.settings import settings
from webapi.blueprints.governance import governance_bp
from webapi.tea import baselines
BASELINES = "/governance/tea/baselines"
SCENARIO = "eeg-posterior-rhythm"
@pytest.fixture
def client():
"""Mount the governance routes so changes to route registration or error handling surface in HTTP."""
app = Flask(__name__)
app.config.update(TESTING=True)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
@pytest.fixture
def trained_registries(tmp_path, monkeypatch):
"""Train one synthetic baseline in SQLite and provide an empty destination to expose failed transfers."""
config = settings()
metric = next(metric for metric in config.metrics if metric.scenario == SCENARIO)
config = replace(config, metrics=(metric,))
monkeypatch.setattr(baselines, "settings", lambda: config)
monkeypatch.chdir(tmp_path)
previous_uri = mlflow.get_tracking_uri()
def use_store(name):
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
mlflow.set_tracking_uri(uri)
try:
use_store("source")
biomarker, phase = config.scenarios[SCENARIO]
features = pipeline(config).module(biomarker).features
rng = np.random.default_rng(0)
ages = np.linspace(16, 36, 100)
found = train.Listing.of("source", [(f"/synthetic/{k}.edf", float(age)) for k, age in enumerate(ages)])
studies = [
ReferenceStudy(key, age, 1, {
(biomarker, phase): {feature: float(1 + 0.02 * age + rng.normal(0, 0.1)) for feature in features},
})
for key, _, age in found.studies
]
train.train_all(config, "PROD", found=found, studies=studies)
yield use_store
finally:
mlflow.set_tracking_uri(previous_uri)
def test_export_and_import_baselines(client, trained_registries, monkeypatch):
"""Pin ZIP headers, cleanup and registry transfer. Fail if repeats register another version."""
real_export = bundle.export
export_paths = []
def capture_export(config, path, **kwargs):
export_paths.append(path)
return real_export(config, path, **kwargs)
monkeypatch.setattr(bundle, "export", capture_export)
with client.get(f"{BASELINES}/export?environment=prod&production=0") as response:
assert response.status_code == 200
assert response.mimetype == "application/zip"
assert response.headers["Content-Disposition"] == "attachment; filename=baselines.zip"
assert response.headers["X-Baselines-Versions"] == "1"
assert export_paths[0].is_file()
archive = response.data
sha256 = hashlib.sha256(archive).hexdigest()
assert response.headers["X-Baselines-Sha256"] == sha256
assert not export_paths[0].exists()
with zipfile.ZipFile(BytesIO(archive)) as exported:
manifest = json.loads(exported.read(bundle.MANIFEST))
assert list(manifest["escenarios"]) == [SCENARIO]
model = train.latest(SCENARIO, "PROD")
mlflow.MlflowClient().set_registered_model_alias(model.name, PRODUCTION_ALIAS, model.version)
with client.get(f"{BASELINES}/export?environment=dev&production=1") as response:
assert response.status_code == 200
assert response.data == archive
assert not export_paths[1].exists()
trained_registries("destination")
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
assert response.status_code == 200
assert response.json == {"sha256": sha256, "imported": [{"scenario": SCENARIO, "version": 1}]}
assert train.latest(SCENARIO, "PROD").tags[bundle.BUNDLE_TAG] == sha256
duplicate = client.post(f"{BASELINES}/import", data={"file": (BytesIO(archive), "baselines.zip")})
assert duplicate.status_code == 409
assert duplicate.json["error"]
versions = mlflow.MlflowClient().search_model_versions(f"name = '{model.name}'")
assert [int(version.version) for version in versions] == [1]
def test_import_rejects_garbage(client):
"""Pin a JSON 400 for non-ZIP bytes. Fail if the ZIP exception becomes a server error."""
response = client.post(f"{BASELINES}/import", data={"file": (BytesIO(b"garbage"), "baselines.zip")})
assert response.status_code == 400
assert response.json["error"]
+78
View File
@@ -0,0 +1,78 @@
"""Cover the cluster route with cluster_client and monkeypatched network probes.
Fails if an unapproved scheduler is probed or health results use the wrong HTTP status.
"""
from unittest.mock import Mock
import distributed
import pytest
from flask import Flask
from tea.pipeline import cluster_status
from webapi.blueprints.governance import governance_bp
CLUSTER_URL = "/governance/tea/cluster"
@pytest.fixture
def cluster_client(monkeypatch):
"""Mount the governance blueprint with clean config so machine defaults cannot affect routing."""
for variable in ("DASK_SCHEDULER_ADDRESS", "TEA_DASK_SCHEDULERS"):
monkeypatch.delenv(variable, raising=False)
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
def test_rejects_scheduler_outside_allow_list(cluster_client, monkeypatch):
"""Pin allow-list enforcement. Fail if an arbitrary scheduler reaches a network probe."""
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://default:8786")
monkeypatch.setenv("TEA_DASK_SCHEDULERS", "tcp://backup:8786")
probe = Mock()
monkeypatch.setattr(cluster_status.ClusterStatus, "check", probe)
response = cluster_client.get(CLUSTER_URL, query_string={"scheduler": "tcp://other:8786"})
assert response.status_code == 400
assert response.json["error"]
probe.assert_not_called()
@pytest.mark.parametrize("mode", ["invalid", "remote"])
def test_rejects_invalid_cluster_choice(cluster_client, mode):
"""Pin validation errors. Fail if an unknown mode or addressless remote request succeeds."""
response = cluster_client.get(CLUSTER_URL, query_string={"mode": mode})
assert response.status_code == 400
assert response.json["error"]
def test_local_mode_reports_reachable(cluster_client):
"""Pin local status serialization. Fail if local checks start reporting remote details."""
response = cluster_client.get(CLUSTER_URL, query_string={"mode": "local"})
assert response.status_code == 200
assert response.json["mode"] == "local"
assert response.json["reachable"] is True
assert response.json["scheduler"] is None
assert response.json["workers"] is None
@pytest.mark.parametrize("scheduler", ["tcp://backup:8786", "tcp://default:8786"])
def test_unreachable_approved_scheduler_returns_health(cluster_client, monkeypatch, scheduler):
"""Pin HTTP 200 on connection failure. Fail if either approval source rejects its address."""
connect = Mock(side_effect=OSError("connection refused"))
monkeypatch.setattr(distributed, "Client", connect)
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=OSError))
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://default:8786")
monkeypatch.setenv("TEA_DASK_SCHEDULERS", "tcp://first:8786, tcp://backup:8786 ")
response = cluster_client.get(CLUSTER_URL, query_string={"scheduler": scheduler})
assert response.status_code == 200
assert response.json["mode"] == "remote"
assert response.json["scheduler"] == scheduler
assert response.json["reachable"] is False
assert response.json["error"] == "connection refused"
connect.assert_called_once_with(scheduler, timeout=5)
+115
View File
@@ -0,0 +1,115 @@
"""Cover cohort metadata, uploads and request errors using a temporary root and the app client.
Fails if the API accepts unsafe files, bypasses the upload limit or loses stored metadata.
"""
from io import BytesIO
import pytest
from webapi import create_app
COHORTS = "/governance/tea/reference-cohorts"
@pytest.fixture
def cohort_client(tmp_path, monkeypatch):
"""Wire the app to a temporary root so escaped writes and metadata errors are observable."""
root = tmp_path / "reference"
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
app = create_app()
app.config.update(TESTING=True)
return app.test_client(), root
def test_list_reference_cohorts(cohort_client):
"""Pin nested EDF counts and age-table metadata. Fail if either is omitted."""
client, root = cohort_client
cohort = root / "reference-1"
nested = cohort / "2026"
nested.mkdir(parents=True)
(root / "empty").mkdir()
(root / "loose.edf").write_bytes(b"loose")
(cohort / "study.edf").write_bytes(b"edf")
(nested / "second.EDF").write_bytes(b"second")
(cohort / "edades.csv").write_bytes(b"ages")
response = client.get(COHORTS)
assert response.status_code == 200
assert response.json == [
{"name": "empty", "edfs": 0, "size_bytes": 0, "has_ages": False, "path": str(root / "empty")},
{"name": "reference-1", "edfs": 2, "size_bytes": 13, "has_ages": True, "path": str(cohort)},
]
@pytest.mark.parametrize("filename", ["study.edf", "edades.csv"])
def test_upload_reference_file(cohort_client, filename):
"""Pin each permitted upload and the stored bytes. Fail if the upload leaves a staging file."""
client, root = cohort_client
payload = b"reference data"
response = client.post(f"{COHORTS}/sample-1/files", data={"file": (BytesIO(payload), filename)})
assert response.status_code == 201
assert response.json == {"name": "sample-1", "file": filename, "size_bytes": len(payload)}
folder = root / "sample-1"
assert list(folder.iterdir()) == [folder / filename]
assert (folder / filename).read_bytes() == payload
@pytest.mark.parametrize(("name", "filename"), [
("sample", "other.csv"),
("sample", "../study.edf"),
("sample", r"..\study.edf"),
("sample", "nested/study.edf"),
("sample", r"nested\study.edf"),
("sample/other", "study.edf"),
("..", "study.edf"),
("sample..other", "study.edf"),
("bad%20name", "study.edf"),
("a" * 65, "study.edf"),
])
def test_reject_invalid_paths_and_extensions(cohort_client, name, filename):
"""Pin validation before writes. Fail if an unsafe component or unsupported extension is accepted."""
client, root = cohort_client
response = client.post(f"{COHORTS}/{name}/files", data={"file": (BytesIO(b"edf"), filename)})
assert response.status_code == 400
assert response.json["error"]
assert not root.exists()
def test_reject_a_cohort_symlink(cohort_client, tmp_path):
"""Pin root confinement. Fail if a cohort symlink allows an upload outside the root."""
client, root = cohort_client
outside = tmp_path / "outside"
outside.mkdir()
root.mkdir()
(root / "linked").symlink_to(outside, target_is_directory=True)
response = client.post(f"{COHORTS}/linked/files", data={"file": (BytesIO(b"edf"), "study.edf")})
assert response.status_code == 400
assert not list(outside.iterdir())
assert client.get(COHORTS).json == []
def test_missing_root_configuration(cohort_client, monkeypatch):
"""Pin a 503 on both endpoints. Fail if either silently falls back to a different root."""
client, _ = cohort_client
monkeypatch.delenv("TEA_REFERENCE_ROOT")
for response in (client.get(COHORTS), client.post(f"{COHORTS}/sample/files")):
assert response.status_code == 503
assert response.json["error"]
def test_upload_uses_app_size_limit(cohort_client):
"""Pin the existing JSON 413. Fail if multipart parsing bypasses the configured size limit."""
client, root = cohort_client
client.application.config["MAX_CONTENT_LENGTH"] = 1024
response = client.post(f"{COHORTS}/sample/files", data={"file": (BytesIO(b"x" * 1024), "study.edf")})
assert response.status_code == 413
assert response.json["error"]
assert not root.exists()
+155
View File
@@ -0,0 +1,155 @@
"""Cover governance EEG reads with SQLite recordings and a stub baseline registry.
Fails if the routes misreport analysis outcomes, FHIR counts or drawable metrics.
"""
from datetime import date
from types import SimpleNamespace
from unittest.mock import Mock
import pandas as pd
import pytest
from core.tea.models import Eeg, EegMetrica
from flask import Flask
from persistance import tea
from persistance.repository import Repository
from sqlalchemy import create_engine, event
from sqlmodel import Session
from webapi.blueprints.governance import governance_bp
from webapi.fhir.eeg_curves import BaselineCurves
from webapi.tea import eeg_queries
EEG_URL = "/governance/tea/eeg"
BASELINE_URL = "/governance/tea/baselines/eeg-posterior-rhythm/3"
UUID = "a62321cf-515e-4883-b1b3-48e4202f790c"
CURVE = {"edad_meses": [16.0, 24.0], "p5": [4.0, 5.0], "p25": [5.0, 6.0],
"mediana": [6.0, 7.0], "p75": [7.0, 8.0], "p95": [8.0, 9.0]}
@pytest.fixture
def client():
"""Mount the governance routes so incorrect paths or response handling fail requests."""
app = Flask(__name__)
app.config["TESTING"] = True
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
@pytest.fixture
def database(monkeypatch):
"""Seed pending, failed, valid and invalid EEGs with scored and unscored metrics to expose miscounts."""
engine = create_engine("sqlite://")
Eeg.__table__.create(engine)
EegMetrica.__table__.create(engine)
with Session(engine) as session:
session.add_all([
Eeg(eeg_id="1", eeg_estudio=b"EDF"),
Eeg(eeg_id="2", eeg_valido=0),
Eeg(eeg_id="10", eeg_error="read failed"),
Eeg(eeg_id=UUID, eeg_valido=1, eeg_nivel="completo", eeg_edad_meses=23.5,
eeg_id_registro_laboratorio="LAB-4", eeg_pac_id=12, eeg_fecha_estudio=date(2025, 4, 3)),
EegMetrica(met_eeg_id=UUID, met_codigo="RITMO_POSTERIOR", met_valor=8.1, met_z=2.5,
met_fuera=1, met_modelo="tea-eeg-posterior-rhythm/3"),
EegMetrica(met_eeg_id=UUID, met_codigo="HUSOS_SUENO_N2", met_valor=0.4),
EegMetrica(met_eeg_id="2", met_codigo="RITMO_POSTERIOR", met_valor=3.1, met_z=-2.5, met_fuera=-1),
EegMetrica(met_eeg_id="2", met_codigo="HUSOS_SUENO_N2"),
])
session.commit()
monkeypatch.setattr(tea, "eeg_repository", Repository(lambda: Session(engine), Eeg))
yield engine
engine.dispose()
@pytest.fixture
def registry(monkeypatch):
"""Resolve one concrete version with one feature curve, so incorrect labels or feature lookups fail."""
expected = ("tea", "eeg-posterior-rhythm", "3")
registry = Mock()
registry.resolve.side_effect = lambda *args: {expected: SimpleNamespace(model_uri="models:/posterior/3")}[args]
module = SimpleNamespace(baselines={"posterior_rhythm_hz": SimpleNamespace(curva=pd.DataFrame(CURVE))})
curves = BaselineCurves(registry=registry, loader=lambda uri: {"models:/posterior/3": module}[uri])
monkeypatch.setattr(eeg_queries, "baseline_curves", lambda: curves)
return registry
def test_recordings_page_without_edf_bytes(client, database):
"""Pin descending IDs, pagination and analysis flags. Fail if the query projects EDF bytes or counts errors as pending."""
statements = []
@event.listens_for(database, "before_cursor_execute")
def capture_sql(connection, cursor, statement, parameters, context, executemany):
statements.append(statement)
response = client.get(EEG_URL)
assert response.status_code == 200
assert response.json == [
{"id": UUID, "lab_id": "LAB-4", "patient_id": 12, "study_date": "2025-04-03", "valid": True,
"analysed": True},
{"id": 10, "lab_id": None, "patient_id": None, "study_date": None, "valid": None, "analysed": True},
{"id": 2, "lab_id": None, "patient_id": None, "study_date": None, "valid": False, "analysed": True},
{"id": 1, "lab_id": None, "patient_id": None, "study_date": None, "valid": None, "analysed": False},
]
assert client.get(EEG_URL, query_string={"limit": 2, "offset": 1}).json == response.json[1:3]
assert all("eeg_estudio" not in statement for statement in statements)
def test_recording_page_size(client, database):
"""Pin the default and maximum page sizes. Fail if oversized requests return more than 500 rows."""
with Session(database) as session:
session.add_all(Eeg(eeg_id=str(key)) for key in range(1000, 1501))
session.commit()
assert len(client.get(EEG_URL).json) == 200
assert len(client.get(EEG_URL, query_string={"limit": 1000}).json) == 500
def test_recording_metrics(client, database):
"""Pin metric values and EEG metadata. Fail if UUIDs, null scores or the pinned model label are lost."""
response = client.get(f"{EEG_URL}/{UUID}/metrics")
assert response.status_code == 200
assert response.json == {
"eeg_id": UUID, "valid": True, "level": "completo", "age_months": 23.5,
"metrics": [
{"name": "husos_sueno_n2", "value": 0.4, "z": None, "outside": None, "model": None},
{"name": "ritmo_posterior", "value": 8.1, "z": 2.5, "outside": 1, "model": "tea-eeg-posterior-rhythm/3"},
],
}
assert client.get(f"{EEG_URL}/2/metrics").json == {
"eeg_id": 2, "valid": False, "level": None, "age_months": None,
"metrics": [{"name": "ritmo_posterior", "value": 3.1, "z": -2.5, "outside": -1, "model": None}],
}
missing = client.get(f"{EEG_URL}/999/metrics")
assert missing.status_code == 404 and missing.json["error"]
def test_summary(client, database):
"""Pin stored and FHIR counts. Fail if one missing view hides the other or pending EEGs count as analysed."""
expected = {"eegs": 4, "analysed": 3, "valid": 1, "not_valid": 1, "failed": 1, "metrics": 4,
"metrics_with_z": 2, "high": 1, "low": 1, "fhir_eegs": 0, "fhir_metrics": 0}
assert client.get(f"{EEG_URL}/summary").json == expected
with database.begin() as connection:
connection.exec_driver_sql("CREATE VIEW tea_paciente_eegs AS SELECT eeg_id FROM eeg WHERE eeg_valido = 1")
assert client.get(f"{EEG_URL}/summary").json == {**expected, "fhir_eegs": 1}
with database.begin() as connection:
connection.exec_driver_sql("CREATE VIEW tea_paciente_eeg_metricas AS SELECT met_id FROM eeg_metrica")
assert client.get(f"{EEG_URL}/summary").json == {**expected, "fhir_eegs": 1, "fhir_metrics": 4}
def test_baseline_metrics_and_curve(client, registry):
"""Pin drawable names and the pinned version's series. Fail if routes include missing features or lose metadata."""
assert client.get(f"{BASELINE_URL}/metrics").json == ["ritmo_posterior"]
response = client.get(f"{BASELINE_URL}/curve", query_string={"metric": "ritmo_posterior"})
assert response.status_code == 200
assert response.json == {"scenario": "eeg-posterior-rhythm", "version": 3, "metric": "ritmo_posterior", **CURVE}
registry.resolve.assert_called_once_with("tea", "eeg-posterior-rhythm", "3")
@pytest.mark.parametrize(("scenario", "version", "metric"), [
("eeg-unknown", 3, "ritmo_posterior"),
("eeg-posterior-rhythm", 9, "ritmo_posterior"),
("eeg-posterior-rhythm", 3, "unknown"),
])
def test_missing_curve(client, registry, scenario, version, metric):
"""Pin missing curve responses. Fail if unknown scenarios, versions or metrics return a successful curve."""
response = client.get(f"/governance/tea/baselines/{scenario}/{version}/curve", query_string={"metric": metric})
assert response.status_code == 404 and response.json["error"]
+172
View File
@@ -0,0 +1,172 @@
"""What this module covers: `POST /governance/tea/eeg/preview`, which analyses one EDF (and an ADOS-2 report) in memory and
answers a patient-summary bundle without writing to any database, and the `EegPreview` class behind it.
Fixtures: `app_client`, the real app over an empty migrated TEA database, with its engine so the tests can count rows;
`edf`, a synthetic two-minute EDF from `models/tests/tea/synth_edf.py` (too short to be a valid study, so only its
quality part is answered); `ados2_pdf`, a one-page report with a Module 2 score table drawn with reportlab.
"""
import importlib.util
import io
from pathlib import Path
import pytest
from sqlalchemy import text
SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py"
URL = "/governance/tea/eeg/preview"
ROWS = [("Señalar", "1"), ("Gestos descriptivos, convencionales, instrumentales o informativos", "0"),
("Contacto visual inusual", "2"), ("Expresiones faciales dirigidas a otros", "1"),
("Disfrute compartido durante la interacción", "0"), ("Mostrar", "2"),
("Iniciación espontánea de la atención conjunta", "1"), ("Características de las iniciaciones sociales", "1"),
("Calidad general de la relación", "2"), ("Uso estereotipado o idiosincrásico de palabras o frases", "1"),
("Manierismos de manos y dedos y otros manierismos complejos", "2"),
("Intereses inusualmente repetitivos o comportamientos estereotipados", "1")]
@pytest.fixture(scope="module")
def edf() -> bytes:
"""A synthetic two-minute EDF, the same file for every test."""
spec = importlib.util.spec_from_file_location("synth_edf", SYNTH)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.edf_bytes(minutes=2)
@pytest.fixture(scope="module")
def ados2_pdf() -> bytes:
"""A report whose Module 2 table lists twelve items with their algorithm scores."""
from reportlab.pdfgen.canvas import Canvas
buffer = io.BytesIO()
pdf = Canvas(buffer, pagesize=(612, 792))
pdf.setFont("Helvetica", 10)
y = 720
for caption, score in [("Afectación Social (AS)", None), *ROWS[:8], ("TOTAL DE AFECTACIÓN SOCIAL", "7"),
("Comportamiento restringido y repetitivo (CRR)", None), *ROWS[8:],
("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", "6"),
("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", "13")]:
pdf.drawString(76, y, caption)
if score is not None:
pdf.drawCentredString(512, y, score)
y -= 20
pdf.showPage()
pdf.save()
return buffer.getvalue()
@pytest.fixture
def app_client(tmp_path):
"""The real app over an empty migrated TEA database; yields (client, engine)."""
from conftest import base_de
from webapi import create_app
base = base_de("tea", tmp_path, datos=lambda session: None)
app = create_app()
app.config.update(TESTING=True)
try:
with app.test_client() as client:
yield client, base.motor
finally:
base.motor.dispose()
def _post(client, **files):
return client.post(URL, data={k: (io.BytesIO(v), name) for k, (name, v) in files.items()},
content_type="multipart/form-data")
def _types(response):
return [e["resource"]["resourceType"] for e in response.json["bundle"]["entry"]]
def test_an_edf_is_analysed_and_nothing_is_stored(app_client, edf, monkeypatch):
"""Pins the summary bundle (report with its quality observations) and zero rows written to `eeg`, `eeg_criterio`
and `eeg_metrica`. Fails if the route stores the recording, or answers without the EEG's report."""
client, engine = app_client
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
response = _post(client, edf=("estudio.edf", edf))
assert response.status_code == 200, response.json
assert "DiagnosticReport" in _types(response) and "Procedure" in _types(response)
assert "Observation" in _types(response)
with engine.connect() as connection:
for table in ("eeg", "eeg_criterio", "eeg_metrica"):
assert connection.execute(text(f"select count(*) from {table}")).scalar() == 0
def test_a_file_that_is_not_an_edf_is_refused(app_client):
"""Pins 400 for a recording MNE cannot open and for a missing field. Fails if either answers 200 or 500."""
client, _ = app_client
assert _post(client, edf=("estudio.edf", b"no es un edf")).status_code == 400
assert client.post(URL, data={}, content_type="multipart/form-data").status_code == 400
def test_without_a_report_the_bundle_has_no_ados2(app_client, edf):
"""Pins that the ADOS-2 observation appears only with a readable report. Fails if one is invented."""
client, _ = app_client
response = _post(client, edf=("estudio.edf", edf))
assert [e for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")] == []
def test_an_unreadable_report_gives_a_notice_not_an_error(app_client, edf):
"""Pins 200 plus a Spanish notice when the attached PDF has no ADOS-2 table. Fails if the route answers 500, drops
the EEG, or says nothing about the report."""
client, _ = app_client
from reportlab.pdfgen.canvas import Canvas
buffer = io.BytesIO()
pdf = Canvas(buffer)
pdf.drawString(72, 700, "Nota clinica sin tabla")
pdf.showPage()
pdf.save()
response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", buffer.getvalue()))
assert response.status_code == 200
assert any("ADOS-2" in aviso for aviso in response.json["avisos"])
assert "DiagnosticReport" in _types(response)
def test_without_an_age_the_css_is_not_invented(app_client, edf, ados2_pdf):
"""Pins the notice when the report gives no CSS and the EDF no age. Fails if a CSS is made up or the notice is lost."""
client, _ = app_client
response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf))
assert response.status_code == 200
assert any("CSS" in aviso for aviso in response.json["avisos"])
def test_a_report_that_is_not_a_pdf_is_refused(app_client, edf):
"""Pins 400 for an ADOS-2 file that is not a PDF. Fails if text is handed to the document extraction."""
client, _ = app_client
assert _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", b"texto")).status_code == 400
def test_the_ados2_report_is_read_and_scored(app_client, edf, ados2_pdf, monkeypatch):
"""Pins that the table's items and module reach the bundle's ADOS-2 observation, scored by the platform's scorer at
the age the analysis used. Fails if the report is ignored, or its items are lost, or nothing is scored."""
import dataclasses
from models.tea.eeg import analyze
real = analyze.measure
monkeypatch.setattr(analyze, "measure", lambda *args: dataclasses.replace(real(*args), age_months=30.0))
client, engine = app_client
response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf))
assert response.status_code == 200, response.json
ados2 = [e["resource"] for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")]
assert len(ados2) == 1 and len(ados2[0]["component"]) > 10, response.json["avisos"]
with engine.connect() as connection:
assert connection.execute(text("select count(*) from ados2")).scalar() == 0
def test_alterations_are_listed_although_the_validation_flag_is_off(monkeypatch):
"""Pins `show_alterations=True` over the environment gate in the FHIR builder. Fails if a preview of a valid EEG
hides its metrics because `TEA_ALTERACIONES_VALIDADAS` is unset."""
from webapi.fhir import tea
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
eeg = {"procedimiento_id": "p", "fecha_eeg": "2026-01-01", "calidad": "BUENO", "valido": 1, "nivel": None,
"duracion_min": 5, "edad_meses": 24.0, "canales": 19}
metric = {"procedimiento_id": "p", "metrica": "ritmo_posterior", "valor": 7.0, "grupo_edad_eeg": "24 meses",
"ref_min": 6.0, "ref_mediana": 7.5, "ref_max": 9.0, "modelo": None, "valor_z": -0.4, "estado": "normal"}
hidden = tea.eeg_resources(eeg, "x", [metric], [], True)
shown = tea.eeg_resources(eeg, "x", [metric], [], True, show_alterations=True)
assert len(shown) == len(hidden) + 1
+51
View File
@@ -0,0 +1,51 @@
"""Cover progress lookup with a Flask client and temporary training and analysis folders.
Fails if the route selects the wrong directory or changes the progress response status or shape.
"""
import json
import pytest
from flask import Flask
from webapi.blueprints.governance import governance_bp
@pytest.fixture
def progress_client(tmp_path, monkeypatch):
"""Set up isolated job folders so reading the configured indicator root is required."""
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client()
@pytest.mark.parametrize(("kind", "base"), [("train", "entrenamientos"), ("analyze", "analisis_eeg")])
def test_progress_snapshot(progress_client, tmp_path, kind, base):
"""Pin progress lookup for both job kinds. Fail if missing files succeed or the snapshot is wrapped."""
url = f"/governance/tea/jobs/{kind}/example/progress"
response = progress_client.get(url)
assert response.status_code == 404 and set(response.json) == {"error"}
folder = tmp_path / base / "example"
folder.mkdir(parents=True)
(folder / "job.json").write_text("{}", encoding="utf-8")
response = progress_client.get(url)
assert response.status_code == 404 and set(response.json) == {"error"}
snapshot = {"updated_at": "2026-01-01T00:00:00+00:00", "phase": "midiendo", "done": 2, "total": 10,
"elapsed_s": 1, "eta_s": None, "tasks": None, "cluster": None, "history": []}
(folder / "progress.json").write_text(json.dumps(snapshot), encoding="utf-8")
response = progress_client.get(url)
assert response.status_code == 200
assert response.json == snapshot
response = progress_client.get(f"/governance/tea/jobs/{kind}/nested%2F..%2Fexample/progress")
assert response.status_code == 404 and set(response.json) == {"error"}
def test_unknown_kind(progress_client):
"""Pin invalid kind handling. Fail if an unsupported job kind becomes a missing job."""
response = progress_client.get("/governance/tea/jobs/other/example/progress")
assert response.status_code == 400
assert set(response.json) == {"error"}
+97
View File
@@ -0,0 +1,97 @@
"""What this module covers: `POST /governance/tea/eeg/upload`, which registers one EDF as an EEG through the import
pipeline (`tea.Eeg`, upsert on the laboratory id).
Fixtures: `app_client`, a migrated empty TEA database (`base_de`) behind the real app; `edf`, a synthetic EDF of two
minutes from `models/tests/tea/synth_edf.py` (nothing comes from a patient).
"""
import importlib.util
from pathlib import Path
import pytest
from sqlalchemy import text
SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py"
@pytest.fixture(scope="module")
def edf() -> bytes:
"""A synthetic two-minute EDF, the same file for every test."""
spec = importlib.util.spec_from_file_location("synth_edf", SYNTH)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.edf_bytes(minutes=2)
@pytest.fixture
def app_client(tmp_path):
"""The real app over an empty migrated TEA database; yields (client, engine)."""
from conftest import base_de
from webapi import create_app
base = base_de("tea", tmp_path, datos=lambda session: None)
app = create_app()
app.config.update(TESTING=True)
try:
with app.test_client() as client:
yield client, base.motor
finally:
base.motor.dispose()
def _post(client, edf, name="estudio-1.edf", **form):
from io import BytesIO
return client.post("/governance/tea/eeg/upload", data={"file": (BytesIO(edf), name), **form},
content_type="multipart/form-data")
def test_an_uploaded_edf_becomes_an_eeg_row(app_client, edf):
"""Pins down: a valid EDF is stored in `eeg` with its file, and the answer carries the new id and the lab id.
Fails if the route stops going through the `tea.Eeg` import (no row, no bytes, or no id in the answer).
"""
client, engine = app_client
response = _post(client, edf)
assert response.status_code == 201, response.get_json()
body = response.get_json()
assert body["created"] is True and body["eeg_id"] is not None and body["lab_id"]
with engine.connect() as connection:
stored = connection.execute(text("select length(eeg_estudio), eeg_pac_id from eeg")).one()
assert stored[0] == len(edf) and stored[1] is None
def test_uploading_the_same_study_twice_updates_it(app_client, edf):
"""Pins down: the laboratory id is the natural key, so a second upload updates the row and does not add one.
Fails if the upsert policy is lost and the study is duplicated or rejected.
"""
client, engine = app_client
first = _post(client, edf).get_json()
second = _post(client, edf)
assert second.status_code == 201
assert second.get_json()["created"] is False and second.get_json()["eeg_id"] == first["eeg_id"]
with engine.connect() as connection:
assert connection.execute(text("select count(*) from eeg")).scalar() == 1
def test_a_file_that_is_not_an_edf_is_refused(app_client):
"""Pins down: bytes MNE cannot open answer 400 with a message and write nothing.
Fails if the connector's validation is bypassed and garbage reaches the table.
"""
client, engine = app_client
response = _post(client, b"not an edf at all")
assert response.status_code == 400 and response.get_json()["error"]
with engine.connect() as connection:
assert connection.execute(text("select count(*) from eeg")).scalar() == 0
def test_the_request_needs_a_file_and_a_numeric_patient(app_client, edf):
"""Pins down: a missing `file` and a non-numeric `patient_id` are 400s before any import runs.
Fails if the form is read without checking, which would turn bad input into a 500.
"""
client, _ = app_client
assert client.post("/governance/tea/eeg/upload", data={}).status_code == 400
assert _post(client, edf, patient_id="abc").status_code == 400
+147
View File
@@ -0,0 +1,147 @@
"""What this module covers: filling `tea.Ados2`'s item columns from the ADOS-2 score table of a PDF read from a SQL
source (`DocumentConnector` with `sql`, the score-table extractor of `extraction.nlp.score_tables`) and merging them
with `on_conflict=upsert` into the row the hospital's table import created, which keeps its header.
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`); `hospital`, a SQLite file
standing for the hospital with one ADOS-2 row whose evaluation PDF is a two-page report, prose first and the
Module 2 score table second.
"""
import base64
import io
import json
import sqlite3
import pytest
from sqlalchemy import create_engine, text
# Module 2 rows as the evaluation prints them: description, algorithm score, column.
_ROWS = [
("Señalar", "1", "ado_sa_a6"),
("Gestos descriptivos, convencionales, instrumentales o informativos", "0", "ado_sa_a7"),
("Contacto visual inusual", "2", "ado_sa_b1"),
("Expresiones faciales dirigidas a otros", "1", "ado_sa_b2"),
("Disfrute compartido durante la interacción", "0", "ado_sa_b3"),
("Mostrar", "2", "ado_sa_b5"),
("Iniciación espontánea de la atención conjunta", "1", "ado_sa_b6"),
("Características de las iniciaciones sociales", "1", "ado_sa_b8"),
("Cantidad de comunicación social recíproca", "S/D", "ado_sa_b11"),
("Calidad general de la relación", "2", "ado_sa_b12"),
("Uso estereotipado o idiosincrásico de palabras o frases", "1", "ado_rrb_a4"),
("Interés sensorial inusual en los materiales de juego o en las personas", "0", "ado_rrb_d1"),
("Manierismos de manos y dedos y otros manierismos complejos", "2", "ado_rrb_d2"),
("Intereses inusualmente repetitivos o comportamientos estereotipados", "1", "ado_rrb_d4"),
]
def _evaluation_pdf() -> bytes:
from reportlab.pdfgen.canvas import Canvas
buffer = io.BytesIO()
pdf = Canvas(buffer, pagesize=(612, 792))
pdf.setFont("Helvetica", 10)
pdf.drawString(72, 720, "Evaluación psicológica. Se observa afectación social en el juego libre.")
pdf.showPage()
pdf.setFont("Helvetica", 10)
y = 720
def row(caption, score=None):
nonlocal y
pdf.drawString(76, y, caption)
if score is not None:
pdf.drawCentredString(512, y, score)
y -= 20
row("Afectación Social (AS)")
for caption, score, _ in _ROWS[:10]:
row(caption, score)
social = sum(int(s) for _, s, _ in _ROWS[:10] if s != "S/D")
row("TOTAL DE AFECTACIÓN SOCIAL", str(social))
row("Comportamiento restringido y repetitivo (CRR)")
for caption, score, _ in _ROWS[10:]:
row(caption, score)
restricted = sum(int(s) for _, s, _ in _ROWS[10:])
row("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", str(restricted))
row("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", str(social + restricted))
pdf.showPage()
pdf.save()
return buffer.getvalue()
@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
@pytest.fixture
def hospital(tmp_path):
"""The hospital: `ados2` with one header row and no items, and the ADOS-2 order holding the evaluation PDF."""
url = f"sqlite:///{tmp_path / 'hospital.db'}"
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE ados2 (ado_id TEXT, ado_pac_id INTEGER, ado_ord_id TEXT)"))
conn.execute(text("CREATE TABLE ordenes_estudio (ord_id TEXT, ord_pdf_blob BLOB)"))
conn.execute(text("INSERT INTO ados2 VALUES ('ADO-1', 7, 'ORD-1')"))
conn.execute(text("INSERT INTO ordenes_estudio VALUES ('ORD-1', :pdf)"), {"pdf": _evaluation_pdf()})
return url
def _json_source(records: list[dict]) -> dict:
return {
"source_type": "json",
"target": "tea.Ados2",
"column_mapping": {name: name for name in records[0]},
"payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()},
}
def _document_source(url: str) -> dict:
items = [column for _, _, column in _ROWS]
return {
"source_type": "document",
"target": "tea.Ados2",
"column_mapping": {name: name for name in ["ado_id", *items]},
"payload": {
"target": "tea.Ados2",
"sql": {
"connection_string": url,
"query": "select a.ado_id, a.ado_pac_id, o.ord_pdf_blob from ados2 a "
"join ordenes_estudio o on o.ord_id = a.ado_ord_id",
"column": "ord_pdf_blob",
"key_column": "ado_id",
"fields": {"ado_id": "ado_id", "ado_pac_id": "ado_pac_id"},
},
},
}
def test_the_evaluations_score_table_fills_the_items_of_the_existing_row(client, hospital, wire_domain):
"""Pins down: after the header row is imported, a `document` source over the hospital's ADOS-2 PDF, committed
with upsert, writes each item's algorithm score into its Module 2 column on that same row, leaves an `S/D` item
empty, and keeps the header (module, CSS, patient). Fails if the document's items stop reaching the columns,
the upsert creates a second row or blanks the header, or the module is read from the wrong item set."""
header = {"ado_id": "ADO-1", "ado_pac_id": 7, "ado_modulo": "MODULO_2", "ado_algoritmo": "Menor de 5 años",
"ado_css": 6, "ado_clasificacion": "AUTISMO"}
first = client.post("/imports/commit", json={"sources": [_json_source([header])], "on_conflict": "upsert"})
assert first.status_code == 200, first.get_json()
second = client.post("/imports/commit", json={"sources": [_document_source(hospital)], "on_conflict": "upsert"})
body = second.get_json()
assert second.status_code == 200, body
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 1, 0)]
from persistance import settings
path = settings.settings.tea_database_url.removeprefix("sqlite:///")
con = sqlite3.connect(path)
con.row_factory = sqlite3.Row
rows = con.execute("select * from ados2").fetchall()
assert len(rows) == 1
stored = dict(rows[0])
expected = {column: (None if score == "S/D" else int(score)) for _, score, column in _ROWS}
assert {column: stored[column] for column in expected} == expected
assert (stored["ado_modulo"], stored["ado_css"], stored["ado_pac_id"]) == ("MODULO_2", 6, 7)
+21
View File
@@ -200,6 +200,27 @@ def test_an_import_into_tea_queues_its_recomputation(client):
assert body["indicadores_en_recalculo"] is True
def test_an_ados2_import_scores_the_evaluations_it_wrote(client):
"""Pins down: after a commit that wrote `tea.Ados2` rows, their CSS and classification are computed from the
stored items, module and the child's age, without waiting for the cycle; a value the source gave stays. Fails if
the commit stops scoring (the CSS would wait for the next cycle, behind any EEG analysis) or scores over a value
the source supplied."""
patient = _json_source([{"pac_id": 9100, "pac_id_hospital": "T-ADOS", "pac_fecha_nacimiento": "2022-01-01"}],
target="tea.Pacientes", column_mapping={"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital",
"pac_fecha_nacimiento": "pac_fecha_nacimiento"})
client.post("/imports/commit", json={"sources": [patient], "on_conflict": "upsert"})
items = {"ado_sa_b1": 2, "ado_sa_b2": 2, "ado_sa_b3": 2, "ado_sa_b4": 2, "ado_rrb_d1": 2, "ado_rrb_d2": 2}
rows = [{"ado_id": "a-1", "ado_pac_id": 9100, "ado_fecha": "2026-01-01", "ado_modulo": "MODULO_3", **items},
{"ado_id": "a-2", "ado_pac_id": 9100, "ado_fecha": "2026-01-01", "ado_modulo": "MODULO_3", "ado_css": 9,
"ado_clasificacion": "AUTISMO", **items}]
ados = _json_source(rows, target="tea.Ados2", column_mapping={k: k for k in rows[0] | rows[1]})
body = client.post("/imports/commit", json={"sources": [ados], "on_conflict": "upsert"}).get_json()
assert body["results"][0]["created"] == 2
stored = {r["ado_id"]: r for r in client.get("/data/tea.Ados2").get_json()["rows"]}
assert (stored["a-1"]["ado_css"], stored["a-1"]["ado_clasificacion"]) == (7, "AUTISMO")
assert stored["a-2"]["ado_css"] == 9
@pytest.fixture
def sql_source_db(tmp_path):
db_path = tmp_path / "external_source.db"
+20 -6
View File
@@ -34,17 +34,18 @@ def _json_source(records: list[dict], *, target: str) -> dict:
}
# One item row and one domain row of a fitted model version, as the `tea` library writes them.
# One item row (an item meaning code) and one domain row (the total CSS) 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_resultado": "ados2_item_11", "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_resultado": "CSS", "rel_evento": ">=8", "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.
@@ -89,8 +90,8 @@ def test_model_and_patient_rows_import_and_reimport_upserts_on_the_natural_keys(
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
interval, an unknown level or biomarker, an outcome code that doesn't match its level (`CSS` as an item, a
domain code instead of `CSS`), 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},
@@ -98,8 +99,9 @@ def test_invalid_model_rows_are_rejected(client):
{**_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-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "CSS"},
{**_MODELO_ITEM, "rel_id": "rel-m7", "rel_version": "0.9.6", "rel_biomarcador": "ritmo posterior"},
{**_MODELO_DOMINIO, "rel_id": "rel-m8", "rel_version": "0.9.7", "rel_resultado": "SA"},
]
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2")],
"on_conflict": "upsert"}).get_json()
@@ -111,6 +113,18 @@ def test_invalid_model_rows_are_rejected(client):
assert not [f for f in filas if f["rel_id"].startswith("rel-m")]
def test_per_module_column_code_is_rejected_as_an_item_outcome(client):
"""Pins down: an item outcome given as a module's column code (`sa_b9`, a different item in each module) is
rejected with a cross-field error. Fails if the schema accepts column codes again, which would break the
natural key and the observed-outcome join across modules."""
fila = {**_MODELO_ITEM, "rel_id": "rel-c1", "rel_version": "0.9.8", "rel_resultado": "sa_b9"}
body = client.post("/imports/commit", json={"sources": [_json_source([fila], target="tea.RelacionAdos2")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert (resultado["created"], resultado["rejected"]) == (0, 1)
assert {e["field"] for e in resultado["errors"]} == {"<entre campos>"}
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."""
+94 -4
View File
@@ -101,13 +101,15 @@ def live_client(client, monkeypatch):
masks = {"< 45 años": np.arange(200) < 100, "Diminuto": np.arange(200) < 3, "Estadio IV": np.zeros(200, bool)}
holder.files["analisis/desarrollo.json"] = json.dumps({"tablas": {"escenarios_resumen": SUMMARY}}).encode()
def curves(spec, model, labelled_members, name):
def curves(spec, model, labelled_members, name, points=None):
holder.calls += 1
holder.points = points
if holder.error:
raise live.QueryError(holder.error)
return {"n": 100, "escenario": name or "Toda la cohorte"}
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3"))
monkeypatch.setattr(model_analysis, "_current_build", lambda d, s: None)
monkeypatch.setattr(live, "scenario_masks", lambda frame: masks)
monkeypatch.setattr(live, "curves", curves)
model_analysis._ANSWERS.clear()
@@ -121,6 +123,7 @@ def test_the_menu_offers_the_scenarios_with_a_summary_row_and_enough_patients(li
menu = live_client.get("/cama/modelo/escenarios?paciente=7").get_json()
assert menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}] and menu["predeterminado"] == "< 45 años"
assert menu["de_la_paciente"] == [{"nombre": "< 45 años", "n": 100}]
assert menu["modelo"]["version"] == "3"
assert live_client.get("/cama/modelo/escenarios?paciente=500").status_code == 422
@@ -187,14 +190,18 @@ def recurrence_client(monkeypatch):
def test_the_recurrence_menu_has_the_scenarios_with_a_summary_row_and_the_patients_default(recurrence_client):
"""Pins down: `GET /cama/modelo/recurrencia` returns the figures of the scenarios that have a row in the version's summary (not
the one without), the summary rows, the version, and, for patient 7, the larger scenario her age, grade and receptors meet as the
default (one that needs the nodes, which the hospital does not report, is never it). Fails if a scenario with no row is offered,
the rows are not returned, or the default is not one she meets."""
default (one that needs the nodes, which the hospital does not report, is never it), and every scenario she meets. Fails if a
scenario with no row is offered, the rows are not returned, or the default or her scenarios include one she does not meet."""
body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json()
assert [(f["cohorte"], f["escenario"]) for f in body["escenarios"]] == [("metabric", "< 45 años"), ("metabric", "RE− · grado 3"), ("metabric", "Ganglios 4+"), ("scanb", "Grado 3")]
assert len(body["resumen"]) == 4 and body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60]
assert body["predeterminado"] == {"cohorte": "metabric", "escenario": "RE− · grado 3"}
assert recurrence_client.get("/cama/modelo/recurrencia").get_json()["predeterminado"] is None
assert body["de_la_paciente"][0] == body["predeterminado"]
assert all(s in [{"cohorte": f["cohorte"], "escenario": f["escenario"]} for f in body["escenarios"]] for s in body["de_la_paciente"])
assert {"cohorte": "metabric", "escenario": "Ganglios 4+"} not in body["de_la_paciente"]
anonymous = recurrence_client.get("/cama/modelo/recurrencia").get_json()
assert anonymous["predeterminado"] is None and anonymous["de_la_paciente"] == []
def test_without_a_recurrence_version_it_is_a_404(recurrence_client):
@@ -202,3 +209,86 @@ def test_without_a_recurrence_version_it_is_a_404(recurrence_client):
recurrence_client.holder.production = None
assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 404
def test_the_members_are_computed_once_per_build_and_version_and_read_from_their_file_after(tmp_path, monkeypatch):
"""Pins down: the first reader of a build's labelled members computes them from the build and leaves them in
`INDICADORES_DIR/modelos`; the next reader (another worker, or the API after the cycle) reads that file without touching the
build, and a new build replaces the old file. Fails if every worker reads the build again, or old builds pile up."""
import pandas as pd
from models.cama.survival import live
from models.io import storage
from webapi import model_analysis
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
reads = []
class Build:
def __init__(self, domain, build_id):
reads.append(build_id)
def frame(self):
return pd.DataFrame()
def lineage(self):
return {}
monkeypatch.setattr(storage, "KitBuild", Build)
monkeypatch.setattr(live, "members", lambda spec, frame, lineage: pd.DataFrame({"pac_id": [1, 2], "stage": ["I", None]}))
first = model_analysis._members("spec", "cama", "survival", "3", 8)
again = model_analysis._members("spec", "cama", "survival", "3", 8)
model_analysis._members("spec", "cama", "survival", "3", 9)
assert reads == [8, 9] and again.equals(first)
assert [p.name for p in (tmp_path / "modelos").iterdir()] == ["cama-survival-v3-armado9.parquet"]
def test_the_figure_takes_the_points_the_version_published_for_the_scenario(live_client):
"""Pins down: the live figure of a scenario carries the points the pipeline's survival stage published for it
(`subgrupos_puntos`: LR, HBN and their combination with bootstrap intervals), and none for a scenario without them. Fails if
the figure draws the members' own scores where the version has the pipeline's."""
rows = [{"modelo": m, "meses": h, "S": 0.9, "IC_inf": 0.85, "IC_sup": 0.95, "subgrupo": "< 45 años"}
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
record = json.loads(live_client.holder.files["analisis/desarrollo.json"])
record["tablas"]["subgrupos_puntos"] = {"columnas": ["modelo", "meses", "S", "IC_inf", "IC_sup", "subgrupo"], "filas": rows}
live_client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode()
live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"})
published = live_client.holder.points
live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Estadio IV"})
assert published["COMB"] == {"S": [0.9] * 3, "low": [0.85] * 3, "high": [0.95] * 3}
assert live_client.holder.points is None
def test_the_cycle_computes_the_scenario_points_once_per_build_and_the_figure_takes_them(live_client, tmp_path, monkeypatch):
"""Pins down: `refresh_subgroups` runs the pipeline's survival stage over the latest build's members once and saves its
scenario points beside them; the figure then draws those points instead of the ones the version published when it trained,
and a new build replaces the file. Fails if the figure keeps the training's points after the data changed, or every cycle
reruns the stage for the same build."""
from models.cama.survival import development
from webapi import model_analysis
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
build = {"id": 8}
monkeypatch.setattr(model_analysis, "_current_build", lambda d, s: ("3", build["id"]))
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: (SimpleNamespace(config={"desarrollo": {}}), "model", None, "3"))
runs = []
def stage(labelled, desarrollo):
runs.append(build["id"])
return [{"modelo": m, "meses": h, "S": 0.7, "IC_inf": 0.6, "IC_sup": 0.8, "subgrupo": "< 45 años"}
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
monkeypatch.setattr(development, "subgroup_points", stage)
first = model_analysis.refresh_subgroups("cama")
again = model_analysis.refresh_subgroups("cama")
rows = model_analysis._subgroup_rows("cama", "survival", "3")
build["id"] = 9
model_analysis.refresh_subgroups("cama")
assert first == ["survival"] and again == [] and runs == [8, 9]
assert [r["S"] for r in rows if r["modelo"] == "COMB"] == [0.7] * 3
assert [p.name for p in (tmp_path / "modelos").glob("*-subgrupos.json")] == ["cama-survival-v3-armado9-subgrupos.json"]
+86
View File
@@ -0,0 +1,86 @@
"""What this module covers: the cluster choice of an indicator recomputation: how `POST /reportes/indicadores/<d>/recalcular`
validates it, how the queue carries it in the pending marker, and how the worker applies it to one run only.
Fixtures: `queue`, a `RecomputationQueue` over a temporary folder.
"""
import json
import os
import pytest
from flask import Flask
from webapi.blueprints.reports import reports_bp
from webapi.recomputation import RecomputationQueue, _cluster_override
@pytest.fixture
def queue(tmp_path, monkeypatch):
"""A queue over an empty temporary folder, which the route also uses through INDICADORES_DIR."""
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
return RecomputationQueue(tmp_path)
@pytest.fixture
def client(queue):
"""The reports blueprint alone, over the same folder as `queue`."""
app = Flask(__name__)
app.register_blueprint(reports_bp, url_prefix="/reportes")
return app.test_client()
def test_a_request_carries_its_cluster_choice_to_the_worker(queue):
"""Pins down: the marker keeps the choice, `requested_cluster` reads it back, and a plain request has none.
Fails if `request_run` drops the choice or the marker stops being readable after a plain request.
"""
queue.request_run("tea", {"mode": "local"})
assert queue.requested_cluster("tea") == {"mode": "local"}
queue.request_run("tea")
assert queue.requested_cluster("tea") is None
assert queue.requested_cluster("cacu") is None
def test_a_marker_written_as_plain_text_still_counts_as_pending(queue):
"""Pins down: a marker left by an older version (a bare timestamp) is pending and has no cluster choice.
Fails if the worker starts to crash on, or ignore, markers that are not JSON.
"""
queue._pending.mkdir(parents=True)
(queue._pending / "tea").write_text("2026-01-01T00:00:00+00:00", encoding="utf-8")
assert queue.pending() == ["tea"] and queue.requested_cluster("tea") is None
def test_the_route_validates_and_queues_the_choice(client, queue):
"""Pins down: a valid choice is queued (202), a bad mode, a non-object body and `remote` without a scheduler are
400s that queue nothing, and no body keeps working.
Fails if the route queues unchecked input, or stops accepting the body-less call the UI used before.
"""
ok = client.post("/reportes/indicadores/tea/recalcular", json={"cluster": {"mode": "local"}})
assert ok.status_code == 202 and queue.requested_cluster("tea") == {"mode": "local"}
for bad in ({"cluster": {"mode": "nope"}}, ["x"]):
assert client.post("/reportes/indicadores/tea/recalcular", json=bad).status_code == 400
os.environ.pop("DASK_SCHEDULER_ADDRESS", None)
assert client.post("/reportes/indicadores/tea/recalcular", json={"cluster": {"mode": "remote"}}).status_code == 400
assert client.post("/reportes/indicadores/tea/recalcular").status_code == 202
def test_a_run_applies_the_choice_and_then_restores_the_environment(monkeypatch):
"""Pins down: during the run the choice is in the environment (`local` drops the scheduler), and afterwards the
process environment is exactly as before, even when the run fails.
Fails if one run's choice leaks into the next runs of the worker.
"""
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:1")
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
before = dict(os.environ)
with _cluster_override({"mode": "local"}):
assert os.environ["EEG_ANALYSIS_CLUSTER"] == "local" and "DASK_SCHEDULER_ADDRESS" not in os.environ
assert dict(os.environ) == before
with pytest.raises(RuntimeError):
with _cluster_override({"mode": "remote", "scheduler": "tcp://other:2"}):
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://other:2"
raise RuntimeError("boom")
assert dict(os.environ) == before
with _cluster_override(None):
assert dict(os.environ) == before
+146
View File
@@ -0,0 +1,146 @@
"""Cover the analysis job routes with captured launches and saved job files.
Fixtures: analysis_client supplies the Flask routes, a temporary job directory and EEG rows.
Fails if scope or cluster options are lost, or persisted jobs change their API shape or order.
"""
import json
import os
import sys
from types import SimpleNamespace
import pytest
from flask import Flask
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, create_engine
from core.tea.models import Eeg
from persistance.tea import eeg_repository
from webapi import detached_jobs
from webapi.blueprints.governance import governance_bp
URL = "/governance/tea/eeg/analyze-jobs"
SUMMARY = {"pending": 3, "valid": 1, "not_valid": 1, "failed": 1}
@pytest.fixture
def analysis_client(tmp_path, monkeypatch):
"""Supply EEG IDs 1 and 2 (numeric) and two UUID ids, and capture child launches to detect invalid launches and lost options."""
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
monkeypatch.delenv("DASK_SCHEDULER_ADDRESS", raising=False)
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
launches = []
engine = create_engine("sqlite://", poolclass=StaticPool)
Eeg.__table__.create(engine)
with Session(engine) as session:
session.add_all([Eeg(eeg_id="1", eeg_estudio=b"edf"), Eeg(eeg_id="2"),
Eeg(eeg_id="ed257fbd-61d5-4c9c-bb72-00c4ec550961", eeg_estudio=b"edf"),
Eeg(eeg_id="a735a43f-376a-403a-b19f-13670130152a", eeg_estudio=b"edf")])
session.commit()
def popen(argv, **kwargs):
launches.append((argv[4:], kwargs["env"]))
return SimpleNamespace(pid=os.getpid())
monkeypatch.setattr(detached_jobs.subprocess, "Popen", popen)
monkeypatch.setattr(eeg_repository, "open_session", lambda: Session(engine))
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
yield app.test_client(), launches
engine.dispose()
@pytest.mark.parametrize("body,flags", [
({}, []),
({"all": False}, []),
({"all": True}, ["--all"]),
({"limit": 4}, ["--limit", "4"]),
({"ids": [1, 2]}, ["--ids", "1,2"]),
({"ids": ["ed257fbd-61d5-4c9c-bb72-00c4ec550961", "a735a43f-376a-403a-b19f-13670130152a"]},
["--ids", "ed257fbd-61d5-4c9c-bb72-00c4ec550961,a735a43f-376a-403a-b19f-13670130152a"]),
])
def test_launch_scope(analysis_client, tmp_path, body, flags):
"""Pin scope flags, response fields and the progress directory. Fail if launch wiring changes."""
client, launches = analysis_client
response = client.post(URL, json=body)
assert response.status_code == 202
assert launches[0][0] == [sys.executable, "-m", "models", "tea", "analyze", *flags, "--cluster", "auto"]
assert response.json.keys() == {"id", "iniciado", "estado", "codigo", "salida", "error", "cluster", "ids", "summary"}
folder = tmp_path / "analisis_eeg" / response.json["id"]
assert launches[0][1]["RUN_PROGRESS_DIR"] == str(folder)
assert response.json["ids"] == ([str(i) for i in body["ids"]] if "ids" in body else None)
assert response.json["cluster"] is response.json["summary"] is None
@pytest.mark.parametrize("choice,mode,scheduler", [
({"mode": "auto"}, "remote", "tcp://inherited:8786"),
({"mode": "local"}, "local", None),
({"mode": "sync"}, "sync", "tcp://inherited:8786"),
({"mode": "remote"}, "remote", "tcp://inherited:8786"),
({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"),
])
def test_cluster_choice(analysis_client, monkeypatch, choice, mode, scheduler):
"""Pin the cluster flag and training-style child environment. Fail if either loses the requested choice."""
client, launches = analysis_client
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote")
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786")
response = client.post(URL, json={"cluster": choice})
assert response.status_code == 202
argv, env = launches[0]
assert argv[-2:] == ["--cluster", choice["mode"]]
assert env["EEG_ANALYSIS_CLUSTER"] == mode
assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler
assert response.json["cluster"] == (dict(choice, scheduler=scheduler) if mode == choice["mode"] == "remote" else choice)
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786"
@pytest.mark.parametrize("body", [
[], {"all": 1}, {"limit": 0}, {"limit": True}, {"ids": []}, {"ids": [True]}, {"ids": None}, {"ids": ["a,b"]}, {"ids": [" "]}, {"ids": ["x" * 65]},
{"ids": [1], "all": True}, {"ids": [1], "limit": 2}, {"all": True, "limit": 2},
{"cluster": {"mode": "remote"}}, {"cluster": {"mode": "invalid"}},
])
def test_invalid_options(analysis_client, body):
"""Pin 400 for invalid options. Fail if malformed scopes or cluster choices launch a child."""
client, launches = analysis_client
assert client.post(URL, json=body).status_code == 400
assert not launches
def test_unknown_eeg_ids(analysis_client):
"""Pin 404 and the missing IDs. Fail if an unknown EEG reaches the child."""
client, launches = analysis_client
response = client.post(URL, json={"ids": [1, 99, 98]})
assert response.status_code == 404
assert "98, 99" in response.json["error"]
assert not launches
def test_refuses_second_analysis(analysis_client):
"""Pin the running-job conflict. Fail if a blank request can launch a concurrent analysis."""
client, launches = analysis_client
assert client.post(URL).status_code == 202
assert client.post(URL).status_code == 409
assert len(launches) == 1
def test_saved_jobs_report_summary_and_list_newest_first(analysis_client, tmp_path):
"""Pin summary parsing after exit and descending job order. Fail if a running job exposes counts."""
client, _ = analysis_client
older, newer = "20260101T000000-aaaaaa", "20260102T000000-bbbbbb"
for job_id in (newer, older):
folder = tmp_path / "analisis_eeg" / job_id
folder.mkdir(parents=True)
(folder / "job.json").write_text(json.dumps({"id": job_id, "pid": os.getpid(), "iniciado": job_id}))
(folder / "stdout.log").write_text(f"analysis output\nsummary: {json.dumps(SUMMARY)}\n")
if job_id == older:
(folder / "exit").write_text("1\n")
jobs = client.get(URL).json
assert [job["id"] for job in jobs] == [newer, older]
assert jobs[0]["estado"] == "en_curso" and jobs[0]["summary"] is None
assert jobs[1]["estado"] == "fallido" and jobs[1]["summary"] == SUMMARY
assert client.get(f"{URL}/{older}").json == jobs[1]
assert client.get(f"{URL}/unknown").status_code == 404
+55 -17
View File
@@ -1,18 +1,25 @@
"""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).
the first ADOS-2 by date (an item meaning's algorithm score in that ADOS-2's module, the CSS for `CSS`, null when
the module has no such item or it wasn't scored); and the dbt var the view maps item meanings with
(`tea.ados2_reactivos`) equals `core.tea.models.ADOS2_ITEM_MEANINGS`.
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`.
versions whose patient rows point at both EEGs and both versions; needs `DBT_MANIFEST`. The var test reads
`Transformation/dbt_project.yml` and needs no fixture.
"""
import os
from datetime import date
from pathlib import Path
import pytest
import yaml
from sqlalchemy import text
DBT_PROJECT = Path(__file__).resolve().parents[2] / "Transformation" / "dbt_project.yml"
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
@@ -32,9 +39,12 @@ def _rows(sesion):
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.
# Module 1 items: sa_b1 2 (item 04), sa_b9 3 (item 11, algorithm score 2), rrb_d1 2 (item 20), rrb_d2 8
# (item 21, algorithm score 0). rrb_d4 (item 22) is not scored. A later ADOS-2 in another module doesn't count.
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))
ado_clasificacion="AUTISMO", ado_sa_b1=2, ado_sa_b9=3, ado_rrb_d1=2, ado_rrb_d2=8))
sesion.add(Ados2(ado_id="a-2", ado_pac_id=1, ado_fecha=date(2025, 8, 5), ado_modulo="TODDLER", ado_css=4,
ado_clasificacion="AUTISMO", ado_sa_b9=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),
@@ -43,29 +53,38 @@ def _rows(sesion):
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_resultado="ados2_item_11", 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_resultado="CSS", rel_evento=">=8", 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_resultado="ados2_item_11", 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_resultado="CSS", rel_evento=">=8", 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_resultado="ados2_item_22", rel_evento=">=1", rel_or=1.5, rel_ic_inf=0.8, rel_ic_sup=2.9,
rel_q=0.1),
# Item 10 is sa_b9 in the Toddler module only: Module 1's sa_b9 is item 11, not this one.
RelacionAdos2(rel_id="rel-24", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="HUSOS_SUENO_N2", rel_zona="central", rel_tipo="item",
rel_resultado="ados2_item_10", rel_evento=">=1", rel_or=1.3, rel_ic_inf=0.9, rel_ic_sup=2.0,
rel_q=0.2),
RelacionAdos2(rel_id="rel-25", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="HUSOS_SUENO_N2", rel_zona="central", rel_tipo="item",
rel_resultado="ados2_item_21", rel_evento=">=1", rel_or=1.2, rel_ic_inf=0.8, rel_ic_sup=1.9,
rel_q=0.3),
# 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_resultado="ados2_item_04", rel_evento=">=1", rel_or=1.1, rel_ic_inf=0.7, rel_ic_sup=1.8,
rel_q=0.2),
])
sesion.add_all([
@@ -78,6 +97,10 @@ def _rows(sesion):
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),
RelacionAdos2Paciente(rap_id="rap-5", rap_rel_id="rel-24", rap_eeg_id="e-1", rap_valor_z=0.2,
rap_probabilidad=0.4, rap_probabilidad_referencia=0.4),
RelacionAdos2Paciente(rap_id="rap-6", rap_rel_id="rel-25", rap_eeg_id="e-1", rap_valor_z=0.3,
rap_probabilidad=0.45, rap_probabilidad_referencia=0.4),
# 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),
@@ -113,7 +136,9 @@ def test_the_view_keeps_the_latest_version_of_the_study_eeg_only(loaded):
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 claves == [("1.1.0", "CSS", "dominio"), ("1.1.0", "ados2_item_10", "item"),
("1.1.0", "ados2_item_11", "item"), ("1.1.0", "ados2_item_21", "item"),
("1.1.0", "ados2_item_22", "item")]
assert {f.pac_id for f in filas} == {1}
@@ -121,7 +146,7 @@ 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"]
(item,) = [f for f in _filas(loaded) if f.resultado == "ados2_item_11"]
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)
@@ -129,9 +154,22 @@ def test_a_row_carries_the_model_metadata_and_the_patient_values(loaded):
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."""
"""Pins down: `observado` is read from the first ADOS-2 by date (Module 1, the one the patient summary shows):
an item meaning's algorithm score through its column code in that module (item 11 is sa_b9 there, 3 counts as
2; item 21 is rrb_d2, 8 counts as 0), null for an item the module doesn't have (item 10, Toddler only, even
though sa_b9 was scored) or that wasn't scored (item 22, rrb_d4), and the ADOS-2's CSS for `CSS` (7). Fails if
the view joins by column code instead of meaning and module, stops applying the algorithm's score mapping,
reads the later ADOS-2, or stores the outcome."""
observados = {f.resultado: f.observado for f in _filas(loaded)}
assert observados == {"sa_b9": 1, "SA": 3, "rrb_d4": None}
assert observados == {"ados2_item_11": 2, "ados2_item_21": 0, "ados2_item_10": None, "ados2_item_22": None,
"CSS": 7}
def test_the_dbt_item_map_equals_the_item_meanings():
"""Pins down: `vars.tea.ados2_reactivos` in dbt_project.yml, which the view maps item outcomes with, has the
same meaning codes and per-module column codes as `core.tea.models.ADOS2_ITEM_MEANINGS`, which the import
schema and the FHIR layer use. Fails if one copy gains, loses or remaps an item without the other."""
from core.tea.models import ADOS2_ITEM_MEANINGS
reactivos = yaml.safe_load(DBT_PROJECT.read_text(encoding="utf-8"))["vars"]["tea"]["ados2_reactivos"]
assert reactivos == {codigo: modulos for codigo, (_, _, modulos) in ADOS2_ITEM_MEANINGS.items()}
+7 -10
View File
@@ -50,7 +50,7 @@ def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings
assert ("cama", "survival") in entries and ("cacu", "cin2_logistic") in entries
assert entries[("tea", "eeg")]["kind"] == "referencia" and entries[("cama", "survival")]["kind"] == "cohorte"
assert ("cama", "seer_survival") not in entries
assert entries[("cama", "recurrence")]["kind"] == "referencia" # trained on its external files, not on a dbt cohort
assert entries[("cama", "recurrence")]["kind"] == "cohorte" # the patients loaded from METABRIC and SCAN-B
@pytest.mark.parametrize("code,estado", [
@@ -118,15 +118,12 @@ def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypat
assert "--manifest" not in tea and "--reference-dir" not in cama
def test_a_scenario_with_external_data_trains_without_a_dbt_export_or_manifest(monkeypatch):
"""Pins down: CaMa's recurrence scenario, whose training data are files, is started with no `--export`, `--manifest` or dbt
manifest, while CaMa's survival scenario still is. Fails if an external scenario is refused for want of a manifest or run
through the cohort export, which would train it on the wrong data."""
monkeypatch.delenv("DBT_MANIFEST", raising=False)
def test_cama_recurrence_trains_on_the_cohort_export_like_survival(monkeypatch):
"""Pins down: CaMa's recurrence scenario, trained on the patients loaded from METABRIC and SCAN-B, is started with the
cohort export and the dbt manifest, as survival is. Fails if it is run without a database build, which would leave it
with no patients."""
monkeypatch.setenv("DBT_MANIFEST", "m.json")
recurrence = training_jobs._command("cama", "recurrence")
monkeypatch.setenv("DBT_MANIFEST", "m.json")
survival = training_jobs._command("cama", "survival")
assert "--export" not in recurrence and "--manifest" not in recurrence
assert "--export" in survival and survival[survival.index("--manifest") + 1] == "m.json"
assert "--export" in recurrence and recurrence[recurrence.index("--manifest") + 1] == "m.json"
+228
View File
@@ -0,0 +1,228 @@
"""Cover TEA training options and compatibility through the governance route.
Fixtures: training_client uses a temporary job directory and captures subprocess launches.
Fails if request options stop controlling argv, the child environment, or persisted state.
"""
import json
import os
import sys
from types import SimpleNamespace
import pytest
from flask import Flask
from webapi import training_jobs
from webapi.blueprints.governance import governance_bp
TRAIN_URL = "/governance/model-versions/tea/eeg/train-jobs"
@pytest.fixture
def training_client(tmp_path, monkeypatch):
"""Capture training launches. Real subprocesses would bypass the captured argv and environment."""
for variable in (*training_jobs.REFERENCE_ENV.values(), "TEA_REFERENCE_ROOT",
"DASK_SCHEDULER_ADDRESS", "EEG_ANALYSIS_CLUSTER"):
monkeypatch.delenv(variable, raising=False)
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
launches = []
def popen(argv, **kwargs):
launches.append((argv[4:], kwargs["env"]))
return SimpleNamespace(pid=os.getpid())
monkeypatch.setattr(training_jobs.subprocess, "Popen", popen)
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
return app.test_client(), launches
def test_body_overrides_reference_environment(training_client, monkeypatch, tmp_path):
"""Pin body precedence and persisted choices. Fail if an override or flag is lost."""
client, launches = training_client
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
monkeypatch.setenv("TEA_REFERENCE_NAME", "fallback")
monkeypatch.setenv("TEA_REFERENCE_DIR", str(tmp_path / "fallback"))
monkeypatch.setenv("TEA_REFERENCE_AGES", str(tmp_path / "fallback.csv"))
monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "60")
body = {
"reference_name": "cohort-1",
"reference_dir": str(tmp_path / "cohort"),
"reference_ages": str(tmp_path / "ages.csv"),
"line_hz": 50,
"promote": False,
"cluster": {"mode": "local"},
}
response = client.post(TRAIN_URL, json=body)
assert response.status_code == 202
job = response.json["job"]
assert job["cluster"] == body["cluster"]
argv, _ = launches[0]
assert argv == [
sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train",
"--reference-dir", body["reference_dir"], "--reference-ages", body["reference_ages"],
"--line-hz", "50", "--reference-name", "cohort-1",
]
folder = tmp_path / "entrenamientos" / job["id"]
saved = json.loads((folder / "job.json").read_text())
assert saved["parameters"] == {key: value for key, value in body.items() if key != "cluster"}
assert saved["cluster"] == body["cluster"]
assert client.get(f"/governance/training-jobs/{job['id']}").json["job"]["cluster"] == body["cluster"]
def test_reference_name_can_be_passed_without_a_directory(training_client):
"""Pin a name-only request. Fail if the flag becomes conditional on a reference directory."""
client, launches = training_client
response = client.post(TRAIN_URL, json={"reference_name": "cohort-1", "promote": True})
assert response.status_code == 202
argv, _ = launches[0]
assert argv[-2:] == ["--reference-name", "cohort-1"]
assert "--reference-dir" not in argv
assert "--promote" in argv
@pytest.mark.parametrize("cluster,mode,scheduler", [
(None, "remote", "tcp://inherited:8786"),
({"mode": "auto"}, "remote", "tcp://inherited:8786"),
({"mode": "local"}, "local", None),
({"mode": "sync"}, "sync", "tcp://inherited:8786"),
({"mode": "remote"}, "remote", "tcp://inherited:8786"),
({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"),
])
def test_cluster_changes_only_the_child_environment(training_client, monkeypatch, cluster, mode, scheduler):
"""Pin cluster variables and scheduler fallback. Fail if mode leaks into argv or the parent."""
client, launches = training_client
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote")
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786")
response = client.post(TRAIN_URL, json={"cluster": cluster} if cluster else {})
assert response.status_code == 202
choice = {"mode": "remote", "scheduler": scheduler} if cluster == {"mode": "remote"} else cluster
assert response.json["job"]["cluster"] == choice
argv, env = launches[0]
assert argv == [sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote"]
assert env["EEG_ANALYSIS_CLUSTER"] == mode
assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler
assert os.environ["EEG_ANALYSIS_CLUSTER"] == "remote"
assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786"
@pytest.mark.parametrize("field", ["reference_dir", "reference_ages"])
def test_reference_paths_must_resolve_inside_root(training_client, monkeypatch, tmp_path, field):
"""Pin containment after symlink resolution. Fail if a local path can escape the root."""
client, launches = training_client
root = tmp_path / "reference"
root.mkdir()
(root / "escape").symlink_to(tmp_path, target_is_directory=True)
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
response = client.post(TRAIN_URL, json={field: str(root / "escape")})
assert response.status_code == 400
assert field in response.json["error"]
assert not launches
def test_remote_reference_can_be_outside_root(training_client, monkeypatch, tmp_path):
"""Pin the remote path exemption. Fail if worker paths are rejected by the API root check."""
client, launches = training_client
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
response = client.post(TRAIN_URL, json={
"reference_dir": "/worker/reference",
"cluster": {"mode": "remote", "scheduler": "tcp://chosen:8786"},
})
assert response.status_code == 202
assert "/worker/reference" in launches[0][0]
def test_remote_requires_a_scheduler(training_client):
"""Pin the missing-scheduler response. Fail if an unconfigured remote job starts."""
client, launches = training_client
response = client.post(TRAIN_URL, json={"cluster": {"mode": "remote"}})
assert response.status_code == 400
assert "DASK_SCHEDULER_ADDRESS" in response.json["error"]
assert not launches
@pytest.mark.parametrize("request_options", [{}, {"json": {}}])
def test_empty_body_keeps_environment_defaults(training_client, monkeypatch, tmp_path, request_options):
"""Pin launch defaults and the progress folder. Fail if either is lost for an empty request."""
client, launches = training_client
monkeypatch.setenv("TEA_REFERENCE_DIR", "/reference")
monkeypatch.setenv("TEA_REFERENCE_AGES", "/reference/ages.csv")
monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "50")
response = client.post(TRAIN_URL, **request_options)
assert response.status_code == 202
assert response.json["job"]["cluster"] is None
argv, env = launches[0]
folder = tmp_path / "entrenamientos" / response.json["job"]["id"]
assert env == {**os.environ, "RUN_PROGRESS_DIR": str(folder)}
assert argv == [
sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote",
"--reference-dir", "/reference", "--reference-ages", "/reference/ages.csv", "--line-hz", "50",
]
@pytest.mark.parametrize("body", [
{"reference_name": "nested/cohort"},
{"reference_name": "a" * 65},
{"reference_dir": "relative"},
{"line_hz": 55},
{"promote": "false"},
{"cluster": {"mode": "unknown"}},
[],
])
def test_invalid_body_options_are_rejected(training_client, body):
"""Pin JSON and option validation. Fail if an invalid value reaches the subprocess."""
client, launches = training_client
response = client.post(TRAIN_URL, json=body)
assert response.status_code == 400
assert response.json["error"]
assert not launches
def test_a_named_cohort_is_trained_from_its_folder_and_ages(training_client, monkeypatch, tmp_path):
"""Pin that a cohort name with a folder under `TEA_REFERENCE_ROOT` launches with that folder, its `edades.csv`
and the chosen line frequency. Fail if the name stays a bare label, which the child rejects without a directory."""
client, launches = training_client
cohort = tmp_path / "tiny"
cohort.mkdir()
(cohort / "edades.csv").write_text("archivo,edad_meses\na.edf,20\n")
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
response = client.post(TRAIN_URL, json={"reference_name": "tiny", "line_hz": 50, "promote": False})
assert response.status_code == 202
argv, _ = launches[0]
assert argv[argv.index("--reference-dir") + 1] == str(cohort.resolve())
assert argv[argv.index("--reference-ages") + 1] == str((cohort / "edades.csv").resolve())
assert argv[argv.index("--line-hz") + 1] == "50"
assert argv[argv.index("--reference-name") + 1] == "tiny"
def test_an_explicit_directory_wins_over_the_cohort_folder(training_client, monkeypatch, tmp_path):
"""Pin that a request giving `reference_dir` is never redirected to the cohort named beside it.
Fail if resolving a name overrides a directory the caller chose."""
client, launches = training_client
(tmp_path / "tiny").mkdir()
(tmp_path / "other").mkdir()
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
client.post(TRAIN_URL, json={"reference_name": "tiny", "reference_dir": str(tmp_path / "other")})
argv, _ = launches[0]
assert argv[argv.index("--reference-dir") + 1] == str((tmp_path / "other").resolve())
assert "--reference-ages" not in argv
Generated
+1 -1
View File
@@ -4424,7 +4424,7 @@ wheels = [
[[package]]
name = "tea"
version = "0.2.0"
version = "0.3.0"
source = { editable = "../models/libs/tea" }
dependencies = [
{ name = "antropy" },
+21
View File
@@ -1,4 +1,5 @@
import datetime as _dt
import logging
import os
from decimal import Decimal
@@ -12,6 +13,7 @@ from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reports import reports_bp
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
from webapi.cama_recurrence.routes import cama_recurrence_bp
from webapi.follow_up.routes import follow_up_blueprint
@@ -104,9 +106,28 @@ def create_app() -> Flask:
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama")
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
app.register_blueprint(recurrence_blueprint(), url_prefix="/cama")
if os.environ.get("WEBAPI_PRECALENTAR_MODELOS") == "1":
_warm_in_background()
return app
def _warm_in_background() -> None:
"""Loads the live models' members in each worker as it starts, so the first patient opened doesn't wait for them."""
import threading
from webapi.model_analysis import LIVE_SCENARIOS, warm
def run():
for domain in LIVE_SCENARIOS:
try:
warm(domain)
except Exception: # the request that needs them will try again and say why
logging.getLogger(__name__).exception("no se pudieron precargar los modelos de %s", domain)
threading.Thread(target=run, name="precarga-modelos", daemon=True).start()
+214
View File
@@ -18,6 +18,7 @@ import os
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
from tempfile import NamedTemporaryFile
from urllib.parse import quote
from core.governance.enums import EstatusExtraccion
@@ -32,6 +33,10 @@ from models.reports import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
from persistance.settings import settings
from werkzeug.wsgi import wrap_file
from webapi.tea.analyze_jobs import AnalysisRunning, AnalyzeJobs
from webapi.tea.reference_cohorts import ReferenceCohortStore
governance_bp = Blueprint("governance", __name__)
@@ -57,6 +62,123 @@ def _pk_name(repository: Repository) -> str:
return next(iter(repository.model.__table__.primary_key.columns)).name
@governance_bp.get("/tea/cluster")
def tea_cluster_status():
"""Report health for a configured TEA cluster."""
from tea.pipeline.cluster_status import ClusterStatus
scheduler = request.args.get("scheduler")
if scheduler is not None:
allowed = {
address.strip()
for address in os.environ.get("TEA_DASK_SCHEDULERS", "").split(",")
if address.strip()
}
if not scheduler or (
scheduler != os.environ.get("DASK_SCHEDULER_ADDRESS") and scheduler not in allowed
):
raise ValueError("El planificador Dask no está autorizado.")
return jsonify(ClusterStatus().check(
mode=request.args.get("mode", "auto"),
scheduler=scheduler,
reference_name=request.args.get("reference"),
))
@governance_bp.get("/tea/reference-cohorts")
def list_reference_cohorts():
"""List the stored TEA reference cohorts."""
root = os.environ.get("TEA_REFERENCE_ROOT")
if not root:
return jsonify({"error": "TEA_REFERENCE_ROOT no está configurado."}), 503
return jsonify(ReferenceCohortStore(root).list_cohorts())
@governance_bp.post("/tea/reference-cohorts/<path:name>/files")
def upload_reference_cohort_file(name: str):
"""Add an EDF or an age table to a reference cohort."""
root = os.environ.get("TEA_REFERENCE_ROOT")
if not root:
return jsonify({"error": "TEA_REFERENCE_ROOT no está configurado."}), 503
upload = request.files.get("file")
if upload is None or not upload.filename:
return jsonify({"error": "Se requiere el campo file."}), 400
return jsonify(ReferenceCohortStore(root).save_file(name, upload.filename, upload.stream)), 201
@governance_bp.get("/tea/baselines/export")
def export_baselines():
"""Download trained EEG baselines as a ZIP."""
from webapi.tea.baselines import BaselineBundles
production = request.args.get("production", "0")
if production not in ("0", "1"):
return jsonify({"error": "production debe ser 0 o 1."}), 400
archive = NamedTemporaryFile(suffix=".zip")
try:
exported = BaselineBundles().export(
Path(archive.name), environment=request.args.get("environment", "prod"), production=production == "1"
)
response = Response(wrap_file(request.environ, archive), mimetype="application/zip")
response.headers["Content-Disposition"] = "attachment; filename=baselines.zip"
response.headers["X-Baselines-Sha256"] = exported.sha256
response.headers["X-Baselines-Versions"] = str(len(exported.versions))
return response
except BaseException:
archive.close()
raise
@governance_bp.post("/tea/baselines/import")
def import_baselines():
"""Register trained EEG baselines from an uploaded ZIP."""
from webapi.tea.baselines import BaselineBundles, BaselineConflict
upload = request.files.get("file")
if upload is None or not upload.filename:
return jsonify({"error": "Se requiere el campo file."}), 400
try:
return jsonify(BaselineBundles().import_(upload.stream))
except BaselineConflict as error:
return jsonify({"error": str(error)}), 409
@governance_bp.post("/tea/eeg/upload")
def upload_eeg():
"""Register one EDF file as an EEG through the import pipeline."""
from webapi.imports.services.import_service import ImportRequestError
from webapi.tea.edf_intake import EdfIntake
upload = request.files.get("file")
if upload is None or not upload.filename:
return jsonify({"error": "Se requiere el campo file."}), 400
patient = request.form.get("patient_id", "").strip()
if patient and not patient.isdigit():
return jsonify({"error": "patient_id debe ser un entero."}), 400
try:
added = EdfIntake().add(upload.filename, upload.read(), int(patient) if patient else None)
except (ImportRequestError, ValueError) as error:
return jsonify({"error": str(error)}), 400
return jsonify(added), 201
@governance_bp.post("/tea/eeg/preview")
def preview_eeg():
"""Analyse one EDF, and the child's ADOS-2 report if given, without storing either: the summary bundle."""
from webapi.tea.eeg_preview import EegPreview, PreviewError
edf = request.files.get("edf")
if edf is None or not edf.filename:
return jsonify({"error": "Se requiere el campo edf."}), 400
report = request.files.get("ados2")
try:
return jsonify(EegPreview().run(edf.read(), report.read() if report is not None and report.filename else None))
except PreviewError as error:
return jsonify({"error": str(error)}), 400
# -- model versions ----------------------------------------------------------------
@@ -142,6 +264,11 @@ def start_training_job(domain: str, scenario: str):
return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.",
"job": training_jobs.running(domain, scenario)}), 409
try:
if domain == "tea" and request.get_data():
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValueError("El cuerpo debe ser un objeto JSON.")
return jsonify({"job": training_jobs.start(domain, scenario, body)}), 202
return jsonify({"job": training_jobs.start(domain, scenario)}), 202
except RuntimeError as error:
return jsonify({"error": str(error)}), 503
@@ -441,6 +568,49 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
return jsonify(updated)
@governance_bp.post("/tea/eeg/analyze-jobs")
def start_analyze_job():
"""Start a detached EEG analysis."""
body = request.get_json(silent=True) if request.get_data() else {}
try:
return jsonify(AnalyzeJobs().start(body)), 202
except AnalysisRunning as error:
return jsonify({"error": str(error)}), 409
@governance_bp.get("/tea/eeg/analyze-jobs")
def list_analyze_jobs():
"""List detached EEG analyses."""
return jsonify(AnalyzeJobs().jobs())
@governance_bp.get("/tea/eeg/analyze-jobs/<job_id>")
def analyze_job(job_id: str):
"""Read a detached EEG analysis."""
return jsonify(AnalyzeJobs().get(job_id))
@governance_bp.get("/tea/jobs/<kind>/<path:job_id>/progress")
def tea_job_progress(kind: str, job_id: str):
"""Read the latest progress snapshot for a detached TEA job."""
from webapi import training_jobs
if kind == "train":
base = training_jobs._base()
elif kind == "analyze":
base = AnalyzeJobs().base
else:
raise ValueError("Tipo de trabajo TEA no válido.")
folder = base / job_id
if "/" not in job_id and job_id not in {".", ".."} and (folder / "job.json").is_file():
try:
return jsonify(json.loads((folder / "progress.json").read_text(encoding="utf-8")))
except FileNotFoundError:
pass
raise LookupError(f"No se encontró el progreso del trabajo {job_id}.")
@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
@@ -495,3 +665,47 @@ def run_ocr():
"needs_review": summary.needs_review,
}
)
@governance_bp.get("/tea/baselines/<scenario>/<int:version>/metrics")
def tea_baseline_metrics(scenario: str, version: int):
"""List the metrics with a curve in the baseline version."""
from webapi.tea.eeg_queries import BaselineQueries
return jsonify(BaselineQueries(scenario, version).metrics())
@governance_bp.get("/tea/baselines/<scenario>/<int:version>/curve")
def tea_baseline_curve(scenario: str, version: int):
"""Read a metric's curve from the baseline version."""
from webapi.tea.eeg_queries import BaselineQueries
return jsonify(BaselineQueries(scenario, version).curve(request.args.get("metric", "").lower()))
@governance_bp.get("/tea/eeg")
def tea_eeg_recordings():
"""List EEG recordings with their analysis status."""
from webapi.tea.eeg_queries import EegQueries
limit = int(request.args.get("limit", 200))
offset = int(request.args.get("offset", 0))
if limit < 0 or offset < 0:
raise ValueError("El límite y el desplazamiento deben ser mayores o iguales a cero.")
return jsonify(EegQueries().recordings(limit, offset))
@governance_bp.get("/tea/eeg/<eeg_id>/metrics")
def tea_eeg_metrics(eeg_id: str):
"""Read one EEG's verdict and metric values."""
from webapi.tea.eeg_queries import EegQueries
return jsonify(EegQueries().metrics(eeg_id))
@governance_bp.get("/tea/eeg/summary")
def tea_eeg_summary():
"""Count EEG analysis outcomes and FHIR view rows."""
from webapi.tea.eeg_queries import EegQueries
return jsonify(EegQueries().summary())
+18
View File
@@ -384,6 +384,23 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
return reports
def _score_ados2_after(domain: str, results: list) -> None:
"""After a commit that wrote ADOS-2 evaluations, their CSS and classification from the items just stored, so they
exist before the recomputation (which may be queued behind a long EEG analysis). Best-effort, like the request
for the recomputation: the rows are saved, and the cycle's `score_ados2` step scores whatever this missed."""
if not any(r.target == "tea.Ados2" and (r.created or r.updated) for r in results):
return
from webapi.orchestration.eeg import live_ados2_scoring
scoring = live_ados2_scoring(domain)
if scoring is None:
return
try:
scoring()
except Exception:
log.exception("no se pudo calcular el CSS del ADOS-2 de %s", domain)
@imports_bp.post("/commit")
def commit():
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
@@ -404,6 +421,7 @@ def commit():
import_audit.record(audit)
recalculating = False
if audit.domain in DOMAINS and any(r.created or r.updated for r in results):
_score_ados2_after(audit.domain, results)
try:
RecomputationQueue().request_run(audit.domain)
recalculating = True
+11 -1
View File
@@ -1,7 +1,10 @@
"""Aggregate reports: the log of import attempts and the state of the live
indicator recomputation. Nothing here returns row-level data."""
import os
from flask import Blueprint, Response, jsonify, request
from webapi.detached_jobs import cluster_environment
from webapi.imports import audit as import_audit
from webapi.recomputation import DOMAINS, RecomputationQueue
@@ -45,5 +48,12 @@ def recomputation_status():
def recompute(dominio: str):
if dominio not in DOMAINS:
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
RecomputationQueue().request_run(dominio)
body = request.get_json(silent=True) if request.get_data() else {}
if not isinstance(body, dict):
return jsonify({"error": "El cuerpo debe ser un objeto JSON."}), 400
try:
cluster = cluster_environment(body, dict(os.environ))
except ValueError as error:
return jsonify({"error": str(error)}), 400
RecomputationQueue().request_run(dominio, cluster)
return jsonify({"pendiente": True}), 202
+51 -2
View File
@@ -9,7 +9,10 @@ cohort that was counted.
import calendar
import hashlib
import json
from collections import OrderedDict
from datetime import date, timedelta
from threading import Lock
from sqlmodel import Session
@@ -115,11 +118,57 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict)
return elegidas, desde
# Provisional status and priority of a patient's diagnostic pathway, pending their clinical definition for CaMa.
ESTATUS = {"PENDIENTE_BIOPSIA": "Pendiente de biopsia", "BIOPSIA_SIN_RESULTADO": "Biopsia sin resultado",
"BIOPSIA_BENIGNA": "Biopsia benigna", "CANCER_SIN_TRATAMIENTO": "Diagnóstico confirmado, sin tratamiento registrado",
"CANCER_EN_TRATAMIENTO": "Diagnóstico confirmado, en tratamiento"}
BIRADS_ALTOS = {"BIRADS_5", "BIRADS_6"}
def _estatus(f: Fila) -> str:
if f.primer_maligno_fecha is not None:
return "CANCER_EN_TRATAMIENTO" if f.escenario_clinico == POST_TRATAMIENTO else "CANCER_SIN_TRATAMIENTO"
return {SIN_BIOPSIA: "PENDIENTE_BIOPSIA", SIN_DATO: "BIOPSIA_SIN_RESULTADO"}.get(f.resultado, "BIOPSIA_BENIGNA")
def _prioridad(f: Fila, estatus: str) -> str:
if estatus == "CANCER_SIN_TRATAMIENTO" or (estatus == "PENDIENTE_BIOPSIA" and f.birads in BIRADS_ALTOS):
return "Alta"
return "Media" if estatus in ("PENDIENTE_BIOPSIA", "BIOPSIA_SIN_RESULTADO") else "Baja"
def _item(f: Fila) -> dict:
estatus = _estatus(f)
diagnostico = f.primer_maligno_fecha
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,
"escenario_clinico": f.escenario_clinico}
"escenario_clinico": f.escenario_clinico, "estatus": ESTATUS[estatus], "prioridad": _prioridad(f, estatus),
"dias_mastografia_diagnostico": (diagnostico - f.mastografia_fecha).days
if diagnostico and diagnostico >= f.mastografia_fecha else None}
# The cohorts already read, by database, revision and the parameters the cohort reads: the same data and cut-off give the same
# cohort, so only a new load, another cut-off or a changed parameter reads the views again.
_COHORTES: OrderedDict = OrderedDict()
_COHORTES_LOCK = Lock()
COHORTES_EN_MEMORIA = 4
PARAMETROS_DE_LA_COHORTE = ("cama.birads_4_a_6", "cama.biopsia_cancer", "cama.grupos_edad", "cama.birads_gravedad")
def _cohorte(sesion: Session, corte: date, revision: str) -> list[Fila]:
parametros = json.dumps([valor_de(sesion, k, tablas=TABLAS) for k in PARAMETROS_DE_LA_COHORTE], default=str)
clave = (str(sesion.get_bind().url), revision, parametros)
with _COHORTES_LOCK:
if clave in _COHORTES:
_COHORTES.move_to_end(clave)
return _COHORTES[clave]
filas = cohorte_al(sesion, corte)
with _COHORTES_LOCK:
_COHORTES[clave] = filas
while len(_COHORTES) > COHORTES_EN_MEMORIA:
_COHORTES.popitem(last=False)
return filas
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
@@ -132,7 +181,7 @@ def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, pa
raise PedidoInvalido("el contexto de la cohorte lleva cohorte, escenario y revisión juntos.")
if any(contexto) and contexto != (COHORTE, ESCENARIO, actual):
raise RevisionDistinta("la cohorte, el escenario o la revisión no son los que sirve el servidor para este corte")
elegidas, desde = _selecciona(cohorte_al(sesion, corte), corte=corte, meses=meses, filtros=filtros)
elegidas, desde = _selecciona(_cohorte(sesion, corte, actual), corte=corte, meses=meses, filtros=filtros)
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
acotada = meses != 0 or any(v is not None for v in filtros.values())
if (elegidas and len(elegidas) < umbral) or (acotada and not elegidas):
View File
+42
View File
@@ -0,0 +1,42 @@
"""`/cama/recurrencia`: the scenarios of each cohort, the figure of one and the scenarios a patient meets."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_recurrence import service
cama_recurrence_bp = Blueprint("cama_recurrence", __name__)
@cama_recurrence_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_recurrence_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_recurrence_bp.get("/figura")
def figure():
cohort = request.args.get("cohorte", "").strip()
scenario = request.args.get("escenario", "").strip()
if not cohort or not scenario:
raise BadRequest("faltan los parámetros «cohorte» y «escenario»")
try:
return jsonify(service.figure(cohort, scenario))
except service.Calculating:
return jsonify({"estado": "calculando"}), 202
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}» en la cohorte «{cohort}»")
except LookupError:
raise NotFound(f"el escenario «{scenario}» no tiene recaídas suficientes para dibujarse")
@cama_recurrence_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+183
View File
@@ -0,0 +1,183 @@
"""CaMa's recurrence analysis over the live cohort build.
Each cohort (METABRIC, SCAN-B) is recoded from the latest build of `cama/cohorte_total` by the dictionary of
`models.cama.recurrence`. Its covariates, the terms of each horizon and the bootstrap of the combined estimate are
computed once per build, in the background, and kept on disk; a scenario's figure is computed when it is asked for and kept
in memory. A new build computes them again.
"""
import hashlib
import pickle
import tempfile
import threading
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.recurrence import analysis, cohort as recurrence_cohort
from models.io.storage import KitBuild
DOMAIN, COHORT = "cama", "cama/cohorte_total"
CACHE_DIR = Path(tempfile.gettempdir()) / "cama_recurrence"
class NotAvailable(LookupError):
"""There is no cohort build to draw on."""
class Calculating(RuntimeError):
"""The cohort's models and bootstrap are still being computed."""
@dataclass
class CohortState:
name: str
frame: pd.DataFrame
scenarios: list[dict]
masks: dict
status: str = "calculando"
error: str | None = None
covariates: list[str] = field(default_factory=list)
dropped: list[str] = field(default_factory=list)
models: dict = field(default_factory=dict)
point: dict = field(default_factory=dict)
draws: dict = field(default_factory=dict)
figures: dict = field(default_factory=dict)
@dataclass
class Live:
build_id: int
model: dict
events: pd.DataFrame
cohorts: dict[str, CohortState]
_lock = threading.RLock()
_live: Live | None = None
def _cache_file(build_id: int, name: str, model_text: str, members: int) -> Path:
key = hashlib.sha256(f"{build_id}|{name}|{members}|{model_text}".encode()).hexdigest()[:20]
return CACHE_DIR / f"{name}-{key}.pkl"
def _compute(state: CohortState, model: dict, cache: Path) -> None:
try:
if cache.is_file():
with cache.open("rb") as handle:
saved = pickle.load(handle)
else:
settings, calculator = model["modeling"], model["calculator"]
horizons = model["config"]["horizons_months"]
cfg = model["cohorts"][state.name]
covariates, dropped = analysis.prune_covariates(state.frame, cfg["covariates"], cfg["treatment"], settings)
models = analysis.select_models(state.frame, covariates, horizons, settings)
calc = analysis.Calculator(state.frame, covariates, models, horizons, settings["bdeu_ess"])
point = calc.risk(np.arange(calc.n), state.masks)
draws = calc.bootstrap(state.masks, calculator["bootstrap_replicas"], settings["seed"])
saved = {"covariates": covariates, "dropped": dropped, "models": models, "point": point, "draws": draws}
CACHE_DIR.mkdir(parents=True, exist_ok=True)
with cache.open("wb") as handle:
pickle.dump(saved, handle)
with _lock:
state.covariates, state.dropped, state.models = saved["covariates"], saved["dropped"], saved["models"]
state.point, state.draws, state.status = saved["point"], saved["draws"], "listo"
except Exception as error: # the cohort reports its failure; the others keep working
with _lock:
state.status, state.error = "error", f"{type(error).__name__}: {error}"
def live() -> Live:
"""The latest build's cohorts; recoded again only when the build changed."""
global _live
repositories = import_module(f"persistance.{DOMAIN}")
build_id = repositories.cohort_repository.latest_build(COHORT)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el análisis de recurrencia")
with _lock:
if _live is not None and _live.build_id == int(build_id):
return _live
model = recurrence_cohort.load()
model_text = recurrence_cohort.TOML.read_text(encoding="utf-8")
events = KitBuild(DOMAIN, int(build_id)).frame()
cohorts = {}
for name, cfg in model["cohorts"].items():
frame = recurrence_cohort.recode(events, model, name)
if frame.empty:
continue
scenarios = cfg["scenarios"]
state = CohortState(name, frame, scenarios, analysis.scenario_masks(frame, scenarios))
cohorts[name] = state
cache = _cache_file(int(build_id), name, model_text, len(frame))
threading.Thread(target=_compute, args=(state, model, cache), daemon=True).start()
_live = Live(int(build_id), model, events, cohorts)
return _live
def _cohort(current: Live, name: str) -> CohortState:
if name not in current.cohorts:
raise KeyError(name)
return current.cohorts[name]
def scenarios() -> dict:
current = live()
minimum = current.model["calculator"]["min_events"]
cohorts = []
for name, state in current.cohorts.items():
rows = []
for scenario in state.scenarios:
mask = state.masks[scenario["name"]]
events = int(state.frame.loc[mask, "evento"].sum())
rows.append({"nombre": scenario["name"], "condiciones": scenario["when"], "n": int(mask.sum()),
"recaidas": events, "dibujable": events >= minimum})
cohorts.append({"id": name, "nombre": current.model["cohorts"][name]["name"], "estado": state.status,
"error": state.error, "escenarios": rows})
return {"build": current.build_id, "horizontes": current.model["config"]["horizons_months"], "cohortes": cohorts}
def figure(cohort: str, scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for an unknown cohort or scenario, `Calculating` while the cohort
is being computed, `LookupError` when the scenario has too few recurrences to be drawn."""
current = live()
state = _cohort(current, cohort)
if scenario not in state.masks:
raise KeyError(scenario)
with _lock:
if state.status == "calculando":
raise Calculating(cohort)
if state.status == "error":
raise RuntimeError(state.error)
if scenario not in state.figures:
figure_record = analysis.scenario_figure(
state.frame, scenario, state.masks[scenario], state.point[scenario], state.draws[scenario],
current.model["config"]["horizons_months"], current.model["calculator"])
if figure_record is None:
raise LookupError(scenario)
state.figures[scenario] = {"cohorte": cohort, "cohorte_nombre": current.model["cohorts"][cohort]["name"],
"condiciones": next(s["when"] for s in state.scenarios if s["name"] == scenario),
"build": current.build_id, **figure_record}
return state.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient's covariates meet in each cohort; one that needs a covariate she lacks does not include her."""
current = live()
events = current.events[current.events["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
found = []
# The analysis is for patients after treatment: those whose timeline holds the post-treatment scenario.
if not (events["tipo"] == "escenario_postratamiento").any():
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": False, "escenarios": found}
for name, state in current.cohorts.items():
recoded = recurrence_cohort.recode(events, current.model, name, of_source=False, follow_up=False)
if recoded.empty:
continue
masks = analysis.scenario_masks(recoded, state.scenarios)
found += [{"cohorte": name, "escenario": n} for n, mask in masks.items() if bool(mask[0])]
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": True, "escenarios": found}
+90
View File
@@ -0,0 +1,90 @@
"""File-backed state and launch support for detached jobs."""
import json
import os
import subprocess
import uuid
from datetime import datetime, timezone
from pathlib import Path
TAIL_CHARS = 4000
def cluster_environment(body: dict, env: dict[str, str]) -> dict | None:
"""Apply a cluster choice to the child environment."""
if "cluster" not in body:
return None
cluster = body["cluster"]
if not isinstance(cluster, dict) or cluster.get("mode") not in ("auto", "local", "remote", "sync"):
raise ValueError("cluster.mode debe ser auto, local, remote o sync.")
mode = cluster["mode"]
scheduler = cluster.get("scheduler")
if "scheduler" in cluster and (not isinstance(scheduler, str) or not scheduler.strip() or "\0" in scheduler):
raise ValueError("cluster.scheduler debe ser texto no vacío.")
if mode == "auto":
return {"mode": mode}
env["EEG_ANALYSIS_CLUSTER"] = mode
if mode == "local":
env.pop("DASK_SCHEDULER_ADDRESS", None)
if mode == "remote":
scheduler = scheduler or env.get("DASK_SCHEDULER_ADDRESS")
if not scheduler:
raise ValueError("El modo remote requiere cluster.scheduler o DASK_SCHEDULER_ADDRESS.")
env["DASK_SCHEDULER_ADDRESS"] = scheduler
return {"mode": mode, "scheduler": scheduler}
return {"mode": mode}
def _alive(pid: int) -> bool:
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def _tail(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else ""
def state(folder: Path) -> dict:
"""Read job metadata, logs, and process state."""
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
exit_file = folder / "exit"
code = int(exit_file.read_text().strip() or 1) if exit_file.exists() else None
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
if code == 0:
status = "completado"
elif code is not None:
status = "fallido"
else:
status = "en_curso" if _alive(job["pid"]) else "interrumpido"
return {**job, "estado": status, "codigo": code, "salida": out, "error": err}
def launch(base: Path, argv: list[str], env: dict[str, str], metadata: dict, *,
precise_id: bool = False, cwd: Path | None = None) -> Path:
"""Start a detached command and publish its job metadata."""
now = datetime.now(timezone.utc)
timestamp = now.strftime("%Y%m%dT%H%M%S%f" if precise_id else "%Y%m%dT%H%M%S")
job_id = f"{timestamp}-{uuid.uuid4().hex[:6]}"
folder = base / job_id
folder.mkdir(parents=True)
shell = '{ "$@" > "$0/stdout.log" 2> "$0/stderr.log"; echo $? > "$0/exit.tmp"; mv "$0/exit.tmp" "$0/exit"; }'
process = subprocess.Popen(["sh", "-c", shell, str(folder.resolve()), *argv],
cwd=cwd or folder, env={**env, "RUN_PROGRESS_DIR": str(folder.resolve())},
start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
job = {**metadata, "id": job_id, "pid": process.pid,
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
temporary = folder / "job.json.tmp"
temporary.write_text(json.dumps(job), encoding="utf-8")
temporary.replace(folder / "job.json")
return folder
def folders(base: Path) -> list[Path]:
"""List published jobs newest first by their timestamped IDs."""
return sorted((path for path in base.glob("*") if (path / "job.json").exists()), reverse=True)
+14 -16
View File
@@ -273,7 +273,7 @@ def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulate
return observations
def curve_extension(label: str, curve: dict) -> dict:
def curve_extension(label: str, curve: dict, validated: bool | None = None) -> 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
@@ -281,12 +281,12 @@ def curve_extension(label: str, curve: dict) -> dict:
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}/estado", "valueString": "validada" if (alterations_validated() if validated is None else 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]:
simulated: bool, curves=None, validated: bool | None = 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
@@ -322,7 +322,7 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
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))
resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve, validated))
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]
@@ -338,14 +338,16 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
checks: list[dict] = (), curves=None) -> list[dict]:
checks: list[dict] = (), curves=None, show_alterations: bool | None = None) -> 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`)."""
observation the baseline's full centile curve when its label resolves (`curves`). `show_alterations` overrides
the validation gate for an analysis the caller shows without storing it; None follows the gate."""
quality = quality_observations(eeg, list(checks), pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves)
if eeg["valido"] == 1 and alterations_validated() else [])
shown = alterations_validated() if show_alterations is None else show_alterations
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves, validated=shown)
if eeg["valido"] == 1 and shown else [])
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
"subject": {"reference": f"Patient/{pseudonym}"},
@@ -379,24 +381,20 @@ def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_i
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
sit on the resource; each prediction carries the outcome (an ADOS-2 item meaning or the total CSS) 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
from webapi.fhir.terminology import 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"]))
outcome = concept(f"{CODE_SYSTEM}/tea-ados2-resultado", f["resultado"],
resultados.get(f["resultado"], f["resultado"]))
return {
"outcome": outcome,
"probabilityDecimal": float(f["probabilidad"]),
+5 -1
View File
@@ -58,12 +58,16 @@ 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.
# codes them, plus `posterior` (the posterior rhythm) and `global` (the anteroposterior gradient): what each zone is
# called on screen. A code outside this list shows as written.
[zonas]
frontal_izq = "Frontal izquierda"
frontal_der = "Frontal derecha"
frontal_media = "Frontal media"
central = "Central"
temporal_izq = "Temporal izquierda"
temporal_der = "Temporal derecha"
parietal = "Parietal"
occipital = "Occipital"
posterior = "Posterior"
global = "Global"
+8 -5
View File
@@ -1,6 +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
results, the ADOS-2 association model's outcomes (`core.tea.models.ADOS2_ITEM_MEANINGS` and the CSS), 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."""
import tomllib
@@ -15,13 +15,14 @@ STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psico
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"}
CSS_ETIQUETA = "Puntaje de severidad calibrado (CSS)"
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()}
"""The association model's outcome labels by code: each item meaning (`ados2_item_11`) and the total CSS."""
from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS
return {**{code: label for code, (label, _, _) in ADOS2_ITEM_MEANINGS.items()}, ADOS2_CSS: CSS_ETIQUETA}
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
@@ -76,6 +77,8 @@ def tea_code_systems() -> dict[str, dict]:
[{"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("tea-ados2-resultado", "Desenlaces del ADOS-2 del modelo de asociación",
[{"code": c, "display": e} for c, e in ados2_resultados().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"}]),
+15 -5
View File
@@ -150,7 +150,8 @@ class DocumentConnector(DataFrameConnector):
self.include_pattern = _compile_filter(include_pattern, "include_pattern")
self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern")
self.skipped: list[dict[str, str]] = []
known = {spec.name for spec in self.specs}
# A source's own ids (`ado_id`) are never read off a page, but a source may carry them.
known = set(entity.schema.model_fields)
unknown = sorted({name for values in self.source_fields.values() for name in values} - known)
if unknown:
raise ConnectorError(f"fields desconocidos para {target}: {', '.join(unknown)}")
@@ -264,6 +265,7 @@ class DocumentConnector(DataFrameConnector):
if self._df is None:
columns = (
[spec.name for spec in self.specs]
+ self._carried_columns()
+ ([self.nlp_field] if self.nlp_field else [])
+ self.caption_columns()
+ [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
@@ -272,11 +274,19 @@ class DocumentConnector(DataFrameConnector):
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
return self._df
def _carried_columns(self) -> list[str]:
"""Fields the source carries that no document spec reads, such as its own ids, in the order first seen."""
specs = {spec.name for spec in self.specs}
carried: list[str] = []
for values in self.source_fields.values():
carried.extend(name for name in values if name not in specs and name not in carried)
return carried
def caption_columns(self) -> list[str]:
"""Every caption the documents print that no field of the target
claims, in the order first seen: columns of their own, mappable
and usable in derived fields like any column of a table."""
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
reserved = {spec.name for spec in self.specs} | set(self._carried_columns()) | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
columns: list[str] = []
for record in self.records:
for found in record.discovered:
@@ -294,7 +304,7 @@ class DocumentConnector(DataFrameConnector):
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
row: dict[str, Any] = record.row()
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
reserved = {spec.name for spec in self.specs} | set(self._carried_columns()) | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
for found in record.discovered:
row.setdefault(_caption_column(found.caption, reserved), found.value)
row.update(self.overrides.get(str(index), {}))
@@ -468,11 +478,11 @@ def document_options(raw: dict[str, Any]) -> dict[str, Any]:
def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector":
"""A `DocumentConnector` over documents read from a source's columns,
their row values restricted to the fields extraction knows."""
their row values restricted to the target's fields."""
entity = ENTITY_REGISTRY.get(target)
if entity is None:
raise ConnectorError(f"destino desconocido: {target!r}")
known = {spec.name for spec in field_specs_for(entity)}
known = set(entity.schema.model_fields)
source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()}
return DocumentConnector(
batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options)
@@ -19,3 +19,21 @@ class BiopsiaMamaImportSchema(ImportSchema):
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
bx_pdf_blob: Optional[bytes] = None
bx_ocr_confianza: Optional[float] = None
bx_tipo_histologico: Optional[str] = None
bx_grado_nottingham: Optional[str] = None
bx_receptor_estrogeno: Optional[str] = None
bx_receptor_estrogeno_pct: Optional[float] = None
bx_receptor_progesterona: Optional[str] = None
bx_receptor_progesterona_pct: Optional[float] = None
bx_her2: Optional[str] = None
bx_her2_fish: Optional[str] = None
bx_ki67_pct: Optional[float] = None
bx_tamano_tumor_mm: Optional[float] = None
bx_ganglios_positivos: Optional[float] = None
bx_invasion_linfovascular: Optional[str] = None
bx_multifocalidad: Optional[str] = None
bx_margenes: Optional[str] = None
bx_pt: Optional[str] = None
bx_pn: Optional[str] = None
bx_lateralidad: Optional[str] = None
bx_localizacion: Optional[str] = None
@@ -22,3 +22,6 @@ class MastografiaImportSchema(ImportSchema):
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
mast_dicom_blob: Optional[bytes] = None
mast_interpretacion: Optional[str] = None
mast_densidad: Optional[str] = None
mast_margen_masa: Optional[str] = None
mast_tipo_hallazgo: Optional[str] = None
@@ -36,3 +36,5 @@ class NotaMedicaImportSchema(ImportSchema):
nm_presion_arterial_sistolica: Optional[int] = None
nm_presion_arterial_diastolica: Optional[int] = None
nm_temperatura: Optional[float] = None
nm_estadio_clinico: Optional[str] = None
nm_metastasis: Optional[str] = None
+12
View File
@@ -31,3 +31,15 @@ class PacienteImportSchema(ImportSchema):
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
pac_estado_civil: Optional[str] = None
pac_raza: Optional[str] = None
pac_brca1: Optional[str] = None
pac_brca2: Optional[str] = None
pac_estado_menopausico: Optional[str] = None
pac_pam50: Optional[str] = None
pac_subtipo_clinico: Optional[str] = None
pac_cluster_integrativo: Optional[str] = None
pac_celularidad: Optional[str] = None
pac_carga_mutacional: Optional[float] = None
pac_ki67_categoria: Optional[str] = None
pac_fuente: Optional[str] = None
@@ -0,0 +1,13 @@
"""Import schema for `core.cama.models.SeguimientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class SeguimientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
seg_tipo: RequiredStr
seg_fecha: FlexDate = None
seg_detalle: Optional[str] = None
@@ -0,0 +1,14 @@
"""Import schema for `core.cama.models.TratamientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class TratamientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
trat_tipo: RequiredStr
trat_fecha: FlexDate = None
trat_detalle: Optional[str] = None
trat_lateralidad: Optional[str] = None
+14
View File
@@ -18,6 +18,8 @@ from persistance.cacu import paciente_repository as cacu_paciente_repository
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
from persistance.cama import tratamiento_mama_repository as cama_tratamiento_mama_repository
from persistance.cama import seguimiento_mama_repository as cama_seguimiento_mama_repository
from persistance.cama import mastografia_repository as cama_mastografia_repository
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
@@ -53,6 +55,8 @@ from webapi.imports.schemas.cama.episodio_clinico import (
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
)
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
from webapi.imports.schemas.cama.tratamiento_mama import TratamientoMamaImportSchema
from webapi.imports.schemas.cama.seguimiento_mama import SeguimientoMamaImportSchema
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
from webapi.imports.schemas.cama.ordenes_estudio import (
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
@@ -154,6 +158,16 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
repository=cama_biometria_hematica_repository,
conflict_fields=None,
),
"cama.TratamientoMama": EntitySpec(
schema=TratamientoMamaImportSchema,
repository=cama_tratamiento_mama_repository,
conflict_fields=None,
),
"cama.SeguimientoMama": EntitySpec(
schema=SeguimientoMamaImportSchema,
repository=cama_seguimiento_mama_repository,
conflict_fields=None,
),
"cama.EpisodioClinico": EntitySpec(
schema=CamaEpisodioClinicoImportSchema,
repository=cama_episodio_clinico_repository,
+7 -5
View File
@@ -1,18 +1,19 @@
"""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."""
ADOS-2 outcome, per fitted model version. An item outcome is an item meaning code (`ADOS2_ITEM_MEANINGS`), the same
in every module; a domain outcome is the total calibrated severity score (`ADOS2_CSS`). `rel_evento` is the outcome
event as a threshold on its score, machine-readable (`>=1`); 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 core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS
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"}
_RESULTADOS_DOMINIO = {ADOS2_CSS}
class RelacionAdos2ImportSchema(ImportSchema):
@@ -37,7 +38,8 @@ class RelacionAdos2ImportSchema(ImportSchema):
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
validos = (set(ADOS2_ITEM_MEANINGS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value
else _RESULTADOS_DOMINIO)
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
+24
View File
@@ -124,3 +124,27 @@ def _last_load(repositories) -> datetime | None:
"""The start of the domain's last load: what's known now, and stable until the next load."""
_, ((last,),) = repositories.dbt_query_repository.rows(select(func.max(LOADS.c.inicio)))
return last
def answer_latest(project: str, repositories, manifest: Path, *, kinds: tuple[str, ...] = ("semestre", "mes"), latest: int = 2,
today: date | None = None) -> int:
"""Answers and stores each measure's `latest` periods of each kind started by `today`, asked as the dashboard asks them
(every fact dated, what is known at the last load), so the first reader after a load finds them stored. The answers it
gave; a measure whose rule is still undecided is skipped."""
today = today or date.today()
known = _last_load(repositories)
periods = [p for kind in kinds
for p in sorted((p for p in repositories.dim_periodo_repository.list(limit=10000, tipo=kind) if p.inicio <= today),
key=lambda p: p.inicio)[-latest:]]
given = 0
for definition in definitions_of(project, manifest).values():
answer_of, _ = ANSWERS[scoring_of(definition)]
for period in periods:
try:
answer_of(project, definition, Question(definition.url, period.periodo_id, None, known),
parameters=repositories.def_parametro_repository, periods=repositories.dim_periodo_repository,
history=repositories.history_repository, queries=repositories.dbt_query_repository)
except UndecidedRule:
break
given += 1
return given
+135 -15
View File
@@ -7,7 +7,10 @@ data are simulated. 404 while the scenario has no version in production, or its
"""
import json
import logging
import os
from collections import OrderedDict
from pathlib import Path
from threading import Lock
from flask import Blueprint, jsonify, request
@@ -19,6 +22,40 @@ _LIVE: dict = {}
_ANSWERS: OrderedDict = OrderedDict()
_LOCK = Lock()
MAX_ANSWERS = 64
# The scenarios whose members are scored over the data ingested so far, by domain.
LIVE_SCENARIOS = {"cama": ("survival",)}
log = logging.getLogger(__name__)
def _members_path(domain: str, scenario: str, version: str, build_id: int) -> Path:
folder = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "modelos"
return folder / f"{domain}-{scenario}-v{version}-armado{build_id}.parquet"
def _members(spec, domain: str, scenario: str, version: str, build_id: int):
"""The build's members labelled for the version: read from the file the first reader left (the cycle or another API worker), or
computed from the build and saved for the next. Reading the build takes minutes; the file, a fraction of a second."""
import pandas as pd
from models.cama.survival import live
from models.io.storage import KitBuild
path = _members_path(domain, scenario, version, build_id)
if path.exists():
try:
return pd.read_parquet(path)
except (OSError, ValueError):
log.warning("no se pudo leer %s; se recalcula", path)
build = KitBuild(domain, build_id)
labelled = live.members(spec, build.frame(), build.lineage())
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
labelled.to_parquet(tmp)
tmp.replace(path)
for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*.parquet"):
if old != path:
old.unlink(missing_ok=True)
return labelled
def _live_context(domain: str, scenario: str):
@@ -31,7 +68,6 @@ def _live_context(domain: str, scenario: str):
from models.cama.survival import live
from models.dags.training import Scenario
from models.io.registry import registry
from models.io.storage import KitBuild
resolved = registry.resolve(domain, scenario)
spec = Scenario.load(domain, scenario)
@@ -41,13 +77,90 @@ def _live_context(domain: str, scenario: str):
key = (resolved.version, build_id)
with _LOCK:
if _LIVE.get("key") != key:
build = KitBuild(domain, build_id)
model = live.rehydrate(mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1])
_LIVE.update(key=key, value=(spec, model, live.members(spec, build.frame(), build.lineage()), resolved.version))
_LIVE.update(key=key, value=(spec, model, _members(spec, domain, scenario, resolved.version, build_id), resolved.version))
_ANSWERS.clear()
return _LIVE["value"]
def _subgroups_path(domain: str, scenario: str, version: str, build_id: int) -> Path:
return _members_path(domain, scenario, version, build_id).with_name(f"{domain}-{scenario}-v{version}-armado{build_id}-subgrupos.json")
def _current_build(domain: str, scenario: str) -> tuple[str, int] | None:
import importlib
from models.dags.training import Scenario
from models.io.registry import registry
try:
version = registry.resolve(domain, scenario).version
except LookupError:
return None
build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(Scenario.load(domain, scenario).cohort)
return (str(version), build_id) if build_id is not None else None
def refresh_subgroups(domain: str) -> list[str]:
"""Runs the pipeline's survival stage over the members of the latest build (`development.subgroup_points`) for each live
scenario whose build has none yet, and saves its scenario points beside the members; the scenarios it computed. Minutes:
the indicators cycle calls it, not a request."""
from models.cama.survival import development
done = []
for scenario in LIVE_SCENARIOS.get(domain, ()):
try:
spec, _, labelled, version = _live_context(domain, scenario)
except LookupError:
continue
current = _current_build(domain, scenario)
if current is None:
continue
path = _subgroups_path(domain, scenario, *current)
if path.exists():
continue
rows = development.subgroup_points(labelled, spec.config.get("desarrollo", {}))
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
tmp.write_text(json.dumps(rows, default=str), encoding="utf-8")
tmp.replace(path)
for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*-subgrupos.json"):
if old != path:
old.unlink(missing_ok=True)
done.append(scenario)
return done
def _subgroup_rows(domain: str, scenario: str, version: str) -> list[dict]:
"""The scenario points of the latest build computed by the cycle (`refresh_subgroups`), or the ones the version published
when it trained while the cycle hasn't computed them, the whole cohort's among them as `WHOLE_COHORT`."""
from models.cama.survival.development import WHOLE_COHORT
current = _current_build(domain, scenario)
if current is not None and current[0] == str(version):
path = _subgroups_path(domain, scenario, *current)
if path.exists():
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
log.warning("no se pudo leer %s", path)
return _summary(domain, scenario, version, table="subgrupos_puntos") + [
{**row, "subgrupo": WHOLE_COHORT} for row in _summary(domain, scenario, version, table="cohorte_puntos")]
def warm(domain: str) -> list[str]:
"""Loads the live context of each of the domain's live scenarios (`LIVE_SCENARIOS`), leaving their members' file for every
reader; the scenarios it loaded. One without a version in production or a build is skipped."""
loaded = []
for scenario in LIVE_SCENARIOS.get(domain, ()):
try:
_live_context(domain, scenario)
except LookupError:
continue
loaded.append(scenario)
return loaded
def _summary(domain: str, scenario: str, version: str, artifact: str = "analisis/desarrollo.json", table: str = "escenarios_resumen") -> list[dict]:
"""The rows of the scenario summary a version published (`escenarios_resumen`): one per scenario, and for recurrence one per
cohort, scenario and horizon. `[]` for a version that published none (trained before the summary existed)."""
@@ -99,8 +212,9 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
@blueprint.get("/modelo/escenarios")
def scenarios_menu():
"""The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data
ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also names the one she
belongs to first as the default. 404 while there is no version in production."""
ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also gives the ones she belongs to
(`de_la_paciente`, the whole cohort when she is in none) and the first of them as the default. 404 while there is no version
in production."""
from models.cama.survival import live
try:
@@ -110,15 +224,18 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
in_summary = {row["escenario"] for row in _summary(domain, scenario, version)}
masks = live.scenario_masks(labelled)
menu = [{"nombre": name, "n": int(mask.sum())} for name, mask in masks.items() if name in in_summary and live.answerable(labelled, mask)]
default = menu[0]["nombre"] if menu else None
default, hers = (menu[0]["nombre"] if menu else None), []
paciente = request.args.get("paciente", "")
if paciente.isdigit():
try:
mine = live.patient_scenarios(labelled, int(paciente))
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
default = next((m["nombre"] for m in menu if m["nombre"] in mine), default)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu, "predeterminado": default})
hers = [m for m in menu if m["nombre"] in mine] or (
[{"nombre": live.WHOLE, "n": len(labelled)}] if mine == [live.WHOLE] else [])
default = hers[0]["nombre"] if hers else default
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu,
"de_la_paciente": hers, "predeterminado": default})
@blueprint.post("/modelo/curvas/consulta")
def live_curves():
@@ -129,15 +246,16 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
name = (request.get_json(silent=True) or {}).get("escenario")
try:
spec, model, labelled, version = _live_context(domain, scenario)
spec, _, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
key = json.dumps({"v": version, "e": name}, default=str)
published = live.published_points(_subgroup_rows(domain, scenario, version), name)
key = json.dumps({"v": version, "e": name, "p": published}, default=str)
with _LOCK:
record = _ANSWERS.get(key)
if record is None:
try:
record = live.curves(spec, model, labelled, name)
record = live.curves(spec, labelled, name, published)
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
with _LOCK:
@@ -154,7 +272,8 @@ def recurrence_blueprint() -> Blueprint:
"""CaMa's recurrence analysis, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia` answers the figures of every clinical
scenario of both external cohorts (METABRIC and SCAN-B) that has a row in the summary the production version published, those rows
(one per cohort, scenario and horizon) for the risk-factor label, and, given `?paciente=<pac_id>`, the scenario her own age, tumor
size, grade and receptors place her in first as the default. The figures describe the cohorts' patients, not her."""
size, grade and receptors place her in first as the default, and every scenario they place her in (`de_la_paciente`, the larger
first within each cohort). The figures describe the cohorts' patients, not her."""
blueprint = Blueprint("model_analysis_cama_recurrence", __name__)
@blueprint.get("/modelo/recurrencia")
@@ -171,7 +290,7 @@ def recurrence_blueprint() -> Blueprint:
summary = _summary("cama", "recurrence", resolved.version, "analisis/recurrencia_desarrollo.json")
present = {(r["cohorte"], r["escenario"]) for r in summary}
figures = [f for f in record["escenarios"] if (f["cohorte"], f["escenario"]) in present]
default = None
default, hers = None, []
paciente = request.args.get("paciente", "")
if paciente.isdigit():
try:
@@ -181,8 +300,9 @@ def recurrence_blueprint() -> Blueprint:
rows = labelled[labelled["pac_id"] == int(paciente)] if labelled is not None else None
if rows is not None and not rows.empty:
mine = patient.matching(figures, patient.covariates_of(rows.iloc[0]))
default = {"cohorte": mine[0]["cohorte"], "escenario": mine[0]["escenario"]} if mine else None
hers = [{"cohorte": f["cohorte"], "escenario": f["escenario"]} for f in mine]
default = hers[0] if hers else None
return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"],
"escenarios": figures, "resumen": summary, "predeterminado": default})
"escenarios": figures, "resumen": summary, "predeterminado": default, "de_la_paciente": hers})
return blueprint
+4 -1
View File
@@ -6,7 +6,10 @@ Each step is a function of `cycle.py`. It takes the `Context` and, as parameters
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
Persistance's repositories (`ctx.repos`), so each one can run on its own.
migrate -> catalogs, registry, definitions
migrate -> catalogs, registry, definitions, score_ados2
score_ados2 -> analyze_eeg (TEA: the ADOS-2 CSS and classification, quick)
analyze_eeg -> relate_ados2, load (TEA: the EEG analysis)
relate_ados2 -> load (TEA: the ADOS-2 association)
catalogs -> load, check_silver
load -> views, event_models, observe, check_silver
registry -> observe
+4 -2
View File
@@ -13,7 +13,7 @@ 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.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
from webapi.orchestration.runner import run
@@ -45,7 +45,9 @@ 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), eeg_analysis=live_eeg_analysis(args.project),
ados2_relation=live_ados2_relation(args.project),
ados2_scoring=live_ados2_scoring(args.project))
for paso in run(ctx, only=args.only):
print(f"{paso.name:20} {paso.seconds:6.1f} s")
+6
View File
@@ -42,5 +42,11 @@ class Context:
# 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)
# The domain's ADOS-2 scoring (`webapi.orchestration.eeg.live_ados2_scoring`): run by the `score_ados2` step, it
# writes each evaluation's CSS and classification from its items. Without it, that step does nothing.
ados2_scoring: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
# The domain's ADOS-2 association (`webapi.orchestration.eeg.live_ados2_relation`): run by the `relate_ados2` step
# after the EEG analysis, it fits the model on the analysed EEGs. Without it, that step does nothing.
ados2_relation: 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)
+25 -4
View File
@@ -82,17 +82,38 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
return counts
def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]:
def analyze_eeg(migrate: str, score_ados2: dict, ctx: Context) -> dict[str, int]:
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo`.
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo`
and `eeg_metrica_zona`.
Waits for `score_ados2` only so the quick scoring doesn't queue behind a long analysis.
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
if ctx.eeg_analysis is None:
return {}
return asdict(ctx.eeg_analysis())
def 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 score_ados2(migrate: str, ctx: Context) -> dict:
"""The CSS and classification of each ADOS-2 from its items, module, algorithm and the child's age
(`ctx.ados2_scoring`), written to bronze before the association and `load` read them. Returns how many
evaluations were scored; nothing without a scoring (every domain but TEA)."""
if ctx.ados2_scoring is None:
return {}
return asdict(ctx.ados2_scoring())
def relate_ados2(analyze_eeg: dict[str, int], ctx: Context) -> dict:
"""The ADOS-2 association fitted on the EEGs the analysis left (`ctx.ados2_relation`), written to
`relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns
the version and its counts; nothing without an association (every domain but TEA)."""
if ctx.ados2_relation is None:
return {}
return asdict(ctx.ados2_relation())
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], relate_ados2: dict, ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis and
the ADOS-2 association.
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
"""
+31 -1
View File
@@ -1,8 +1,12 @@
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load.
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load, and the
ADOS-2 association fitted on what it left.
`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).
`ADOS2_SCORING=off` leaves the ADOS-2 CSS and classification out of the cycle (`python -m models tea score-ados2`
still computes them).
`ADOS2_RELATION=off` leaves the association out (`python -m models tea relate-ados2` still runs it).
"""
import os
from collections.abc import Callable
@@ -11,6 +15,8 @@ from typing import Any
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
CLUSTERS = ("auto", "local", "remote", "sync")
RELATION_ENV = "ADOS2_RELATION"
SCORING_ENV = "ADOS2_SCORING"
def cluster() -> str:
@@ -27,3 +33,27 @@ def live_eeg_analysis(domain: str) -> Callable[[], Any] | None:
from models.eeg_analysis import analyze_pending
return partial(analyze_pending, cluster=cluster())
def live_ados2_relation(domain: str) -> Callable[[], Any] | None:
"""The domain's ADOS-2 association for the cycle, or none: only TEA has one, and `off` leaves it out."""
value = os.environ.get(RELATION_ENV, "on")
if value not in ("on", "off"):
raise ValueError(f"{RELATION_ENV} must be on or off, not {value!r}")
if domain != "tea" or value == "off":
return None
from models.ados2_relation import relate
return relate
def live_ados2_scoring(domain: str) -> Callable[[], Any] | None:
"""The domain's ADOS-2 scoring for the cycle, or none: only TEA has one, and `off` leaves it out."""
value = os.environ.get(SCORING_ENV, "on")
if value not in ("on", "off"):
raise ValueError(f"{SCORING_ENV} must be on or off, not {value!r}")
if domain != "tea" or value == "off":
return None
from models.ados2_scoring import score_pending
return score_pending
+4 -2
View File
@@ -63,8 +63,8 @@ class ScenarioEstimator:
def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
"""The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the
registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario
definition in `models` is skipped. Empty where none is in production, the same as no estimator being
configured: `estimate` then does nothing."""
definition in `models`, or one whose definition turns off `batch_estimates`, is skipped. Empty where none is in
production, the same as no estimator being configured: `estimate` then does nothing."""
from models.dags.training import Scenario
from models.io.registry import registry
@@ -74,5 +74,7 @@ def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
scenario = Scenario.load(domain, name)
except LookupError:
continue
if not scenario.batch_estimates:
continue
found.setdefault(scenario.cohort, []).append(ScenarioEstimator(domain, name))
return found
+81 -8
View File
@@ -4,10 +4,10 @@
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
"""
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente, SeguimientoMama, TratamientoMama
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.extracted import ConEstructurado, DesdeTexto
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
@@ -36,11 +36,39 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"biopsia.her2", "biopsia.ki67_pct", "biopsia.tamano_tumor_mm"),
texto=lambda f: f.bx_pdf_blob,
)
DE_LA_MASTOGRAFIA = ConEstructurado(DE_LA_INTERPRETACION, {"mastografia.densidad": "mast_densidad"})
# A mammogram's findings, each a part of its report.
LOS_HALLAZGOS = (
Hija("mastografia", "parte", solo_si=("mast_margen_masa",), fecha="mast_fecha_reporte",
resultados={"mast_margen_masa": "mastografia.margen_masa"}),
Hija("mastografia", "parte", solo_si=("mast_tipo_hallazgo",), fecha="mast_fecha_reporte",
resultados={"mast_tipo_hallazgo": "mastografia.tipo_hallazgo"}),
)
DE_LA_NOTA = DesdeTexto(
"cama", ("nota_medica.estadio_clinico",),
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
)
# What a biopsy report and a note carry structured wins over the text's reading; the rest is read from the text.
DE_LA_PATOLOGIA = ConEstructurado(DEL_REPORTE_DE_PATOLOGIA, {
"biopsia.tipo_histologico": "bx_tipo_histologico", "biopsia.grado_nottingham": "bx_grado_nottingham",
"biopsia.receptor_estrogeno": "bx_receptor_estrogeno", "biopsia.receptor_estrogeno_pct": "bx_receptor_estrogeno_pct",
"biopsia.receptor_progesterona": "bx_receptor_progesterona",
"biopsia.receptor_progesterona_pct": "bx_receptor_progesterona_pct", "biopsia.her2": "bx_her2",
"biopsia.ki67_pct": "bx_ki67_pct", "biopsia.her2_fish": "bx_her2_fish",
"biopsia.tamano_tumor_mm": "bx_tamano_tumor_mm", "biopsia.ganglios_positivos": "bx_ganglios_positivos",
"biopsia.invasion_linfovascular": "bx_invasion_linfovascular", "biopsia.multifocalidad": "bx_multifocalidad",
"biopsia.margenes": "bx_margenes", "biopsia.pt": "bx_pt", "biopsia.pn": "bx_pn",
})
DE_LA_NOTA_ESTRUCTURADA = ConEstructurado(DE_LA_NOTA, {
"nota_medica.estadio_clinico": "nm_estadio_clinico", "nota_medica.m": "nm_metastasis",
})
# The biopsy's sample: the breast and the site it was taken from, dated by its request or, without one, its report.
LA_TOMA_DE_LA_BIOPSIA = Hija(
"biopsia", "toma", solo_si=("bx_lateralidad", "bx_localizacion"), fecha="bx_fecha_toma",
resultados={"bx_lateralidad": "biopsia.lateralidad", "bx_localizacion": "biopsia.localizacion"},
)
DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
@@ -51,17 +79,62 @@ DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
derivadas=DE_LA_INTERPRETACION.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
fuentes=DE_LA_INTERPRETACION.fuentes,
derivadas=DE_LA_MASTOGRAFIA.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_MASTOGRAFIA.resultados},
fuentes=DE_LA_MASTOGRAFIA.fuentes, hijas=LOS_HALLAZGOS,
),
DeStaging(
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
derivadas={**DE_LA_PATOLOGIA.derivadas,
"bx_fecha_toma": lambda f: f.bx_fecha_solicitud or f.bx_fecha_reporte},
fuentes=DE_LA_PATOLOGIA.fuentes,
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
resultados={"bx_grado_histologico": "biopsia.grado", **DE_LA_PATOLOGIA.resultados}),
LA_TOMA_DE_LA_BIOPSIA),
),
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA_ESTRUCTURADA),
# Facts of the patient with no date of their own: dated at her birth, known as of the load.
DeStaging(
Paciente, "pac_id", "parte", estudio_id="sociodemografico", fecha="pac_fecha_nacimiento",
resultados={"pac_estado_civil": "sociodemografico.estado_civil", "pac_raza": "sociodemografico.raza",
"pac_estado_menopausico": "sociodemografico.estado_menopausico",
"pac_fuente": "sociodemografico.fuente"},
),
DeStaging(
Paciente, "pac_id", "reporte", estudio_id="prueba_genetica", fecha="pac_fecha_nacimiento",
solo_si=lambda f: f.pac_brca1 is not None or f.pac_brca2 is not None,
resultados={"pac_brca1": "prueba_genetica.brca1", "pac_brca2": "prueba_genetica.brca2"},
),
*(
DeStaging(
TratamientoMama, "trat_id", "encuentro", estudio_id=estudio, fecha="trat_fecha",
solo_si=lambda f, e=estudio: f.trat_tipo == e,
resultados={"trat_detalle": resultado, **({"trat_lateralidad": "cirugia.lateralidad"} if estudio == "cirugia" else {})},
)
for estudio, resultado in (
("cirugia", "cirugia.tipo_cirugia"), ("radioterapia", "radioterapia.intencion"),
("quimioterapia", "quimioterapia.intencion"), ("hormonoterapia", "hormonoterapia.intencion"),
("anti_her2", "anti_her2.intencion"),
)
),
*(
DeStaging(
SeguimientoMama, "seg_id", "encuentro", estudio_id=estudio, fecha="seg_fecha",
solo_si=lambda f, e=estudio: f.seg_tipo == e, resultados={"seg_detalle": resultado},
)
for estudio, resultado in (("recurrencia", "recurrencia.sitio"), ("ultimo_contacto", "ultimo_contacto.estado"))
),
DeStaging(
Paciente, "pac_id", "parte", estudio_id="perfil_molecular", fecha="pac_fecha_nacimiento",
solo_si=lambda f: any(getattr(f, c) is not None for c in (
"pac_pam50", "pac_subtipo_clinico", "pac_cluster_integrativo", "pac_celularidad", "pac_carga_mutacional",
"pac_ki67_categoria")),
resultados={"pac_pam50": "perfil_molecular.pam50", "pac_subtipo_clinico": "perfil_molecular.subtipo_clinico",
"pac_cluster_integrativo": "perfil_molecular.cluster_integrativo",
"pac_celularidad": "perfil_molecular.celularidad",
"pac_carga_mutacional": "perfil_molecular.carga_mutacional",
"pac_ki67_categoria": "perfil_molecular.ki67_categoria"},
),
)
+39
View File
@@ -130,3 +130,42 @@ def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
if texto is not None and str(texto.value).strip():
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
return None, None
@dataclass(frozen=True)
class ConEstructurado:
"""`DesdeTexto` whose results the row may carry already structured: a structured column wins over what the text
gives, and a column with no text twin is a result of its own. `estructurados`: result -> staging column;
each result keeps the text reading as its fallback when `lector` has it."""
lector: DesdeTexto | None
estructurados: dict[str, str]
@property
def derivadas(self) -> dict[str, Callable]:
columnas = dict(self.lector.derivadas) if self.lector else {}
leidos = set(self.lector.resultado_ids) if self.lector else set()
for resultado_id, columna in self.estructurados.items():
clave = _columna(resultado_id)
texto = self.lector.derivadas[clave] if resultado_id in leidos else (lambda f: None)
fuente = self.lector.derivadas[clave + "_fuente"] if resultado_id in leidos else (lambda f: None)
columnas[clave] = lambda f, c=columna, t=texto: _con_valor(getattr(f, c, None), t(f))
columnas[clave + "_fuente"] = lambda f, c=columna, t=fuente: (
None if _vacio(getattr(f, c, None)) else t(f))
return columnas
@property
def resultados(self) -> dict[str, str]:
return {_columna(r): r for r in {*(self.lector.resultado_ids if self.lector else ()), *self.estructurados}}
@property
def fuentes(self) -> dict[str, str]:
return {columna: columna + "_fuente" for columna in self.resultados}
def _vacio(valor) -> bool:
return valor is None or (isinstance(valor, str) and not valor.strip())
def _con_valor(estructurado, leido):
return leido if _vacio(estructurado) else estructurado
+43 -9
View File
@@ -24,6 +24,7 @@ import os
import signal
import threading
import time
from contextlib import contextmanager
from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any
@@ -48,6 +49,23 @@ def _short(value: Any) -> str:
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
@contextmanager
def _cluster_override(cluster: dict | None):
"""Applies a cluster choice to this process's environment while a run lasts, then restores it."""
if not cluster:
yield
return
from webapi.detached_jobs import cluster_environment
saved = dict(os.environ)
try:
cluster_environment({"cluster": cluster}, os.environ)
yield
finally:
os.environ.clear()
os.environ.update(saved)
class RecomputationQueue:
"""Marker-file queue and status of the indicator recomputations."""
@@ -62,11 +80,20 @@ class RecomputationQueue:
def _status_path(self) -> Path:
return self.base / "estado.json"
def request_run(self, dominio: str) -> None:
def request_run(self, dominio: str, cluster: dict | None = None) -> None:
"""Queues a run; `cluster` (`{mode, scheduler?}`) picks where the EEG analysis of that run executes."""
if dominio not in DOMAINS:
raise ValueError(f"dominio desconocido: {dominio!r}")
self._pending.mkdir(parents=True, exist_ok=True)
(self._pending / dominio).write_text(_now(), encoding="utf-8")
(self._pending / dominio).write_text(json.dumps({"at": _now(), "cluster": cluster}), encoding="utf-8")
def requested_cluster(self, dominio: str) -> dict | None:
"""The cluster choice of the queued request, or none for a plain one."""
try:
marker = json.loads((self._pending / dominio).read_text(encoding="utf-8"))
except (FileNotFoundError, json.JSONDecodeError):
return None
return marker.get("cluster") if isinstance(marker, dict) else None
def pending(self) -> list[str]:
if not self._pending.exists():
@@ -103,10 +130,12 @@ class RecomputationQueue:
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
tmp.replace(self._status_path)
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)."""
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None,
cluster: dict | None = None) -> dict[str, Any]:
"""Runs the domain's graph (without `migrate`: the API migrates on startup). `cluster` overrides where the
EEG analysis runs, for this run only."""
from webapi.orchestration import Context, run, steps_of
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
@@ -116,13 +145,17 @@ 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))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
with _cluster_override(cluster):
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
ados2_scoring=live_ados2_scoring(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",
pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos],
)
entrada["pasos"].append(_answer_measures(dominio))
entrada["pasos"].append(_warm_models(dominio))
except Exception as exc: # the worker must survive a failing domain
log.exception("recálculo de %s falló", dominio)
entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))})
@@ -138,8 +171,9 @@ class RecomputationQueue:
"""Runs every pending domain once; returns the ones it ran."""
ran = []
for dominio in self.pending():
choice = self.requested_cluster(dominio)
if self.take(dominio):
self.run(dominio)
self.run(dominio, cluster=choice)
ran.append(dominio)
return ran
+1
View File
@@ -0,0 +1 @@
"""TEA governance storage services."""
+100
View File
@@ -0,0 +1,100 @@
"""Detached analysis jobs for stored TEA EEGs."""
import fcntl
import json
import os
import sys
from pathlib import Path
from webapi import detached_jobs
SUMMARY_FIELDS = {"pending", "valid", "not_valid", "failed"}
class AnalysisRunning(RuntimeError):
"""An EEG analysis job is already running."""
class AnalyzeJobs:
"""Launch and read EEG analysis jobs from the indicator directory."""
def __init__(self):
self.base = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "analisis_eeg"
def start(self, body: dict) -> dict:
"""Validate analysis options and launch one job at a time."""
if not isinstance(body, dict) or body.keys() - {"all", "limit", "ids", "cluster"}:
raise ValueError("El cuerpo debe ser un objeto JSON con opciones de análisis válidas.")
everything = body.get("all", False)
limit = body.get("limit")
ids = body.get("ids")
if type(everything) is not bool:
raise ValueError("all debe ser un valor booleano.")
if "limit" in body and (type(limit) is not int or limit < 1):
raise ValueError("limit debe ser un entero positivo.")
if "ids" in body:
if (not isinstance(ids, list) or not ids
or any(type(value) not in (int, str) or not str(value).strip() or len(str(value)) > 64
or any(mark in str(value) for mark in ",\0") for value in ids)):
raise ValueError("ids debe ser una lista no vacía de identificadores de EEG.")
ids = [str(value).strip() for value in ids]
if sum((everything, limit is not None, ids is not None)) > 1:
raise ValueError("Elija solo una opción entre all, limit e ids.")
env = os.environ.copy()
cluster = detached_jobs.cluster_environment(body, env)
argv = [sys.executable, "-m", "models", "tea", "analyze"]
if everything:
argv.append("--all")
elif limit is not None:
argv.extend(("--limit", str(limit)))
elif ids is not None:
argv.extend(("--ids", ",".join(map(str, ids))))
argv.extend(("--cluster", cluster["mode"] if cluster else "auto"))
self.base.mkdir(parents=True, exist_ok=True)
with (self.base / ".start.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
if any(self._state(folder)["estado"] == "en_curso" for folder in detached_jobs.folders(self.base)):
raise AnalysisRunning("Ya hay un análisis de EEG en curso.")
if ids is not None:
from models.eeg_analysis import selected_ids
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
selected_ids(session, ids)
folder = detached_jobs.launch(self.base, argv, env, {"cluster": cluster, "ids": ids},
precise_id=True, cwd=Path.cwd())
return self._state(folder)
def get(self, job_id: str) -> dict:
"""Read one analysis job by ID."""
folder = self.base / job_id
if "/" in job_id or not (folder / "job.json").is_file():
raise LookupError(f"No se encontró el análisis de EEG {job_id}.")
return self._state(folder)
def jobs(self) -> list[dict]:
"""List analysis jobs newest first."""
return [self._state(folder) for folder in detached_jobs.folders(self.base)]
@staticmethod
def _state(folder: Path) -> dict:
job = detached_jobs.state(folder)
job.pop("pid", None)
job.setdefault("cluster", None)
job.setdefault("ids", None)
job["summary"] = None
if job["codigo"] is not None:
for line in reversed(job["salida"].splitlines()):
if line.startswith("summary:"):
try:
summary = json.loads(line.removeprefix("summary:"))
except ValueError:
break
if (isinstance(summary, dict) and summary.keys() == SUMMARY_FIELDS
and all(type(value) is int and value >= 0 for value in summary.values())):
job["summary"] = summary
break
return job
+44
View File
@@ -0,0 +1,44 @@
"""Transfer trained EEG baselines between registries."""
import hashlib
import shutil
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import BinaryIO
from zipfile import BadZipFile
from models.tea.eeg import bundle
from models.tea.eeg.bundle import BundleError
from models.tea.eeg.settings import settings
class BaselineConflict(BundleError):
"""Every baseline in the bundle already exists in the registry."""
class BaselineBundles:
"""Export and register bundles using the configured EEG scenarios."""
def export(self, path: Path, *, environment: str, production: bool) -> bundle.Exported:
return bundle.export(settings(), path, environment=environment.upper(), production=production)
def import_(self, stream: BinaryIO) -> dict:
config = settings()
with NamedTemporaryFile(suffix=".zip") as upload:
shutil.copyfileobj(stream, upload, length=1024 * 1024)
upload.flush()
upload.seek(0)
sha256 = hashlib.file_digest(upload, "sha256").hexdigest()
try:
versions = bundle.import_(config, upload.name)
except (BadZipFile, KeyError, TypeError, AttributeError, FileNotFoundError) as error:
raise BundleError(f"Paquete de baselines inválido: {error}") from error
imported = [
{"scenario": scenario, "version": int(version)}
for scenario, (version, new) in versions.items() if new
]
if versions and not imported:
existing = ", ".join(f"{scenario}: {version}" for scenario, (version, _) in versions.items())
raise BaselineConflict(f"Las versiones ya están registradas: {existing}")
return {"sha256": sha256, "imported": imported}
+70
View File
@@ -0,0 +1,70 @@
"""Add an EEG recording to TEA through the import pipeline.
The recording goes through the `edf` connector and the `tea.Eeg` target, the same path an import takes, so the
validation, the natural key (`eeg_id_registro_laboratorio`) and the audit trail are the import's own.
"""
import base64
from sqlalchemy import select
from persistance.tea import eeg_repository
from webapi.imports import audit as import_audit
from webapi.imports.services.import_service import ImportRequestError, ImportSource, commit_sources
TARGET = "tea.Eeg"
COLUMNS = {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"fecha_estudio": "eeg_fecha_estudio",
"canales": "eeg_canales",
"duracion_min": "eeg_duracion_min",
"estudio": "eeg_estudio",
}
class EdfIntake:
"""Registers one EDF file as an EEG, optionally linked to a patient."""
def add(self, filename: str, raw: bytes, patient_id: int | None = None) -> dict:
"""`ImportRequestError` for a file that is not a readable EDF or that the import rejects."""
source = {
"source_type": "edf",
"target": TARGET,
"payload": {"file_base64": base64.b64encode(raw).decode("ascii"), "options": {"file_name": filename}},
"column_mapping": COLUMNS,
"defaults": {} if patient_id is None else {"eeg_pac_id": patient_id},
"label": filename,
}
lab_id = self._lab_id(source)
audit = import_audit.ImportAudit("carga", {"on_conflict": "upsert", "merge_duplicates": False})
try:
(result,) = commit_sources([source], on_conflict="upsert", audit=audit)
except Exception as exc:
audit.fail(exc, "solicitud_invalida" if isinstance(exc, ImportRequestError) else "fallida")
raise
else:
audit.succeed()
finally:
import_audit.record(audit)
if result.rejected:
raise ImportRequestError("; ".join(error["message"] for error in result.errors) or "el EEG fue rechazado")
return {"eeg_id": self._eeg_id(lab_id), "lab_id": lab_id, "created": bool(result.created)}
@staticmethod
def _lab_id(source: dict) -> str | None:
(row,) = ImportSource.parse(source).rows()
return row.get("eeg_id_registro_laboratorio")
@staticmethod
def _eeg_id(lab_id: str | None):
if lab_id is None:
return None
model = eeg_repository.model
session = eeg_repository.open_session()
try:
found = session.execute(
select(model.eeg_id).where(model.eeg_id_registro_laboratorio == lab_id)
).scalars().first()
finally:
session.close()
return found
+161
View File
@@ -0,0 +1,161 @@
"""Analyse one EDF, and read its ADOS-2 report, in memory: the answer is a patient summary bundle and nothing is stored.
The recording goes through the same measurement and baselines as a stored EEG, and its rows are turned into the
dicts the FHIR summary builders take, so the web app draws it with the view it uses for a patient. No session is
opened, no row is added and no registry entry is written; the uploaded bytes live in this call only.
"""
from datetime import date
from webapi.fhir import tea as fhir
from webapi.fhir.eeg_curves import baseline_curves
PSEUDONYM = "vista-previa"
EEG_ID = "vista-previa"
ADOS2_ID = "vista-previa"
class PreviewError(ValueError):
"""The file cannot be analysed at all (the EDF cannot be read, or the report is not a PDF)."""
def _item_labels() -> dict[str, str]:
"""Each item's printed caption, from the score-table vocabulary the extraction reads reports with."""
from extraction.nlp.vocabulary import SCORE_TABLES
labels: dict[str, str] = {}
for captions in SCORE_TABLES["ados2"]["variants"].values():
for caption, field in captions.items():
labels.setdefault(field.removeprefix("ado_"), caption)
return labels
def _recording_date(edf: bytes) -> date:
from extraction import ExtractionError
from extraction.signals import EegRecording
try:
start = EegRecording.read(edf).start
except ExtractionError as error:
raise PreviewError(f"El archivo no es un EDF legible: {error}") from error
return start.date() if start else date.today()
class EegPreview:
"""Builds the summary of one EDF and, optionally, of the child's ADOS-2 report."""
def __init__(self, settings=None, baselines=None, measure_fn=None, curves=None):
self._settings, self._baselines, self._measure, self._curves = settings, baselines, measure_fn, curves
def run(self, edf: bytes, ados2: bytes | None = None) -> dict:
from models.eeg_analysis import checked_settings, rows
from models.tea.eeg.analyze import measure
from models.tea.eeg.baselines import Baselines
settings = self._settings or checked_settings()
baselines = self._baselines or Baselines(settings.domain)
taken = _recording_date(edf)
measured = (self._measure or measure)(EEG_ID, edf, None, settings)
if measured.error and measured.valid is None and not measured.checks:
raise PreviewError(f"No se pudo analizar el EDF: {measured.error}")
result = rows(measured, settings, baselines)
avisos: list[str] = []
resources = []
if ados2 is not None:
observation = self._ados2(ados2, measured.age_months, taken, avisos)
if observation is not None:
resources.append(observation)
if measured.error:
avisos.append(f"El análisis del EEG terminó con un error: {measured.error}")
resources += self._eeg(measured, result, taken)
return {"bundle": {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]},
"avisos": avisos}
def _eeg(self, m, result, taken: date) -> list[dict]:
valid = result.eeg.get("eeg_valido")
quality = "SIN_ANALIZAR" if valid is None else "BUENO" if valid == 1 else "MALO"
eeg = {"procedimiento_id": EEG_ID, "fecha_eeg": taken, "calidad": quality, "valido": valid,
"nivel": result.eeg.get("eeg_nivel"), "duracion_min": result.eeg.get("eeg_duracion_min"),
"edad_meses": result.eeg.get("eeg_edad_meses"), "canales": result.eeg.get("eeg_canales")}
age_group = f"{round(m.age_months)} meses" if m.age_months is not None else "sin dato"
codes = {metric.met_id: metric.met_codigo for metric in result.metrics}
metrics = [{"procedimiento_id": EEG_ID, "metrica": x.met_codigo, "valor": x.met_valor, "grupo_edad_eeg": age_group,
"ref_min": x.met_p5, "ref_mediana": x.met_mediana, "ref_max": x.met_p95, "modelo": x.met_modelo,
"valor_z": x.met_z,
"estado": "no_evaluable" if x.met_z is None else
"aumentado" if x.met_fuera == 1 else "disminuido" if x.met_fuera == -1 else "normal"}
for x in result.metrics]
electrodes = [{"procedimiento_id": EEG_ID, "metrica": codes[x.mel_met_id], "electrodo": x.mel_electrodo,
"valor": x.mel_valor, "valor_z": x.mel_z} for x in result.electrodes]
checks = [{"procedimiento_id": EEG_ID, "criterio": c.cri_codigo, "electrodo": c.cri_electrodo,
"valor": c.cri_valor, "valor_texto": c.cri_valor_texto, "bajo": c.cri_bajo, "alto": c.cri_alto,
"anormal": c.cri_anormal, "decisivo": c.cri_decisivo, "etiqueta": c.cri_codigo,
"unidad": c.cri_unidad} for c in result.criteria]
return fhir.eeg_resources(eeg, PSEUDONYM, metrics, electrodes, True, checks,
curves=self._curves or baseline_curves(), show_alterations=True)
def _ados2(self, raw: bytes, age_months: float | None, taken: date, avisos: list[str]) -> dict | None:
try:
row = self._report_row(raw)
items, module, algorithm = self._items(row), row.get("ado_modulo"), row.get("ado_algoritmo")
score = self._score(module, items, age_months, algorithm)
except PreviewError:
raise
except Exception as error: # noqa: BLE001
avisos.append(f"No se pudo leer el ADOS-2 del PDF: {error}")
return None
css = row.get("ado_css") or (score.css if score else None)
classification = row.get("ado_clasificacion") or (score.classification if score else None)
if not items or not module:
avisos.append("No se pudo leer el ADOS-2 del PDF: faltan el módulo o los puntajes de los reactivos.")
return None
if css is None:
avisos.append("No se pudo calcular el CSS del ADOS-2: el informe no lo trae y el EDF no da la edad del niño.")
return None
labels = _item_labels()
lines = [{"procedimiento_id": ADOS2_ID, "fecha_ados2": _date(row.get("ado_fecha")) or taken,
"modulo": module, "algoritmo": algorithm, "css": int(css), "clasificacion": classification,
"dominio": "SA" if code.startswith("sa_") else "RRB", "reactivo": f"ados2.{code}",
"etiqueta": labels.get(code, code.replace("_", " ").upper()), "puntaje": value,
"puntaje_algoritmo": 2 if value == 3 else 0 if value in (7, 8, 9) else value}
for code, value in items.items()]
return fhir.ados2_observation(lines, PSEUDONYM, True)
@staticmethod
def _report_row(raw: bytes) -> dict:
if not raw.lstrip()[:5].startswith(b"%PDF"):
raise PreviewError("El informe del ADOS-2 debe ser un PDF.")
from webapi.imports.connectors.document import DocumentConnector
records, _ = DocumentConnector([("ados2.pdf", raw)], target="tea.Ados2")._extract()
if not records:
raise ValueError("el PDF no contiene una evaluación ADOS-2")
row = records[0].row()
return {k: (None if v in ("", None) else v) for k, v in row.items()}
@staticmethod
def _items(row: dict) -> dict[str, int]:
from core.tea.models import ADOS2_ITEMS
out = {}
for code in ADOS2_ITEMS:
value = row.get(f"ado_{code}")
if value is not None:
out[code] = int(float(value))
return out
@staticmethod
def _score(module, items, age_months, algorithm):
from tea.scoring import score
return score(module, items, age_months=age_months, algorithm=algorithm) if module and items else None
def _date(value) -> date | None:
if value is None:
return None
if isinstance(value, date):
return value
try:
return date.fromisoformat(str(value)[:10])
except ValueError:
return None
+112
View File
@@ -0,0 +1,112 @@
"""Read EEG analysis results and registered baseline curves for governance."""
from core.tea.models import Eeg, EegMetrica
from sqlalchemy import case, func, inspect, or_, select
from webapi.fhir.eeg_curves import baseline_curves
from webapi.fhir.tea import EEGS, METRICS
class BaselineQueries:
"""Use the analysis metric catalog to find drawable curves."""
def __init__(self, scenario: str, version: int):
self.scenario = scenario
self.version = version
self.label = f"tea-{scenario}/{version}"
self.curves = baseline_curves()
def metrics(self) -> list[str]:
from models.tea.eeg.settings import settings
candidates = {metric.code.lower() for metric in settings().metrics if metric.scenario == self.scenario}
return [name for name in sorted(candidates) if self.curves.curve(self.label, name) is not None]
def curve(self, metric: str) -> dict:
curve = self.curves.curve(self.label, metric)
if curve is None:
raise LookupError("No se encontró una curva para la métrica y la versión solicitadas.")
return {"scenario": self.scenario, "version": self.version, "metric": metric, **curve}
def _public_id(key: str) -> int | str:
if key.isascii() and key.isdecimal() and str(int(key)) == key:
return int(key)
return key
def _valid(value: int | None) -> bool | None:
return None if value is None else value == 1
def _count_where(condition):
return func.count(case((condition, 1)))
class EegQueries:
"""Read projected EEG fields and aggregate counts from the TEA database."""
def __init__(self):
from persistance.tea import eeg_repository
self.repository = eeg_repository
def recordings(self, limit: int, offset: int) -> list[dict]:
query = select(
Eeg.eeg_id, Eeg.eeg_id_registro_laboratorio, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio,
Eeg.eeg_valido, case((Eeg.eeg_error.is_not(None), 1), else_=0),
).order_by(func.length(Eeg.eeg_id).desc(), Eeg.eeg_id.desc()).limit(min(limit, 500)).offset(offset)
with self.repository.open_session() as session:
return [
{"id": _public_id(key), "lab_id": lab_id, "patient_id": patient_id,
"study_date": study_date.isoformat() if study_date is not None else None,
"valid": _valid(valid), "analysed": valid is not None or bool(failed)}
for key, lab_id, patient_id, study_date, valid, failed in session.execute(query)
]
def metrics(self, eeg_id: str) -> dict:
header = select(Eeg.eeg_valido, Eeg.eeg_nivel, Eeg.eeg_edad_meses).where(Eeg.eeg_id == eeg_id)
metrics = select(
EegMetrica.met_codigo, EegMetrica.met_valor, EegMetrica.met_z, EegMetrica.met_fuera, EegMetrica.met_modelo,
).where(
EegMetrica.met_eeg_id == eeg_id, EegMetrica.met_codigo.is_not(None), EegMetrica.met_valor.is_not(None),
).order_by(EegMetrica.met_codigo, EegMetrica.met_id)
with self.repository.open_session() as session:
row = session.execute(header).one_or_none()
if row is None:
raise LookupError(f"No se encontró el EEG {eeg_id}.")
valid, level, age_months = row
return {
"eeg_id": _public_id(eeg_id), "valid": _valid(valid), "level": level, "age_months": age_months,
"metrics": [
{"name": code.lower(), "value": value, "z": z, "outside": outside, "model": model}
for code, value, z, outside, model in session.execute(metrics)
],
}
def summary(self) -> dict:
failed = Eeg.eeg_error.is_not(None)
eeg_counts = select(
func.count().label("eegs"),
_count_where(or_(Eeg.eeg_valido.is_not(None), failed)).label("analysed"),
_count_where(Eeg.eeg_valido == 1).label("valid"),
_count_where(Eeg.eeg_valido == 0).label("not_valid"),
_count_where(failed).label("failed"),
).select_from(Eeg)
metric_counts = select(
func.count().label("metrics"),
_count_where(EegMetrica.met_z.is_not(None)).label("metrics_with_z"),
_count_where(EegMetrica.met_fuera == 1).label("high"),
_count_where(EegMetrica.met_fuera == -1).label("low"),
).select_from(EegMetrica)
with self.repository.open_session() as session:
relations = inspect(session.connection())
return {
**session.execute(eeg_counts).mappings().one(),
**session.execute(metric_counts).mappings().one(),
**{
name: session.scalar(select(func.count()).select_from(view))
if relations.has_table(view.name) else 0
for name, view in (("fhir_eegs", EEGS), ("fhir_metrics", METRICS))
},
}
+74
View File
@@ -0,0 +1,74 @@
"""Store reference cohorts on the local filesystem."""
import re
import shutil
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import BinaryIO
COHORT_NAME = re.compile(r"[A-Za-z0-9._-]{1,64}")
AGES_FILE = "edades.csv"
def _safe_component(value: str) -> bool:
return bool(value) and value != "." and not any(char in value for char in ("/", "\\", "..", "\0", ":"))
class ReferenceCohortStore:
"""List cohorts and atomically publish uploads under a configured root."""
def __init__(self, root: str | Path):
self.root = Path(root).resolve()
def list_cohorts(self) -> list[dict]:
if not self.root.exists():
return []
cohorts = []
for folder in sorted(self.root.iterdir()):
if (not COHORT_NAME.fullmatch(folder.name) or not _safe_component(folder.name)
or folder.is_symlink() or not folder.is_dir()):
continue
edfs = [
path for path in folder.rglob("*")
if path.suffix.lower() == ".edf" and not path.is_symlink() and path.is_file()
]
ages = folder / AGES_FILE
has_ages = not ages.is_symlink() and ages.is_file()
size = sum(path.stat().st_size for path in edfs)
if has_ages:
size += ages.stat().st_size
cohorts.append({
"name": folder.name,
"edfs": len(edfs),
"size_bytes": size,
"has_ages": has_ages,
"path": str(folder),
})
return cohorts
def save_file(self, name: str, filename: str, stream: BinaryIO) -> dict:
if not COHORT_NAME.fullmatch(name) or not _safe_component(name):
raise ValueError("Nombre de cohorte inválido.")
if not _safe_component(filename):
raise ValueError("Nombre de archivo inválido.")
if filename != AGES_FILE and Path(filename).suffix.lower() != ".edf":
raise ValueError("Solo se admite un archivo EDF o edades.csv.")
folder = self.root / name
target = folder / filename
if folder.is_symlink() or target.is_symlink():
raise ValueError("Ruta de archivo inválida.")
folder.mkdir(parents=True, exist_ok=True)
temporary = None
try:
with NamedTemporaryFile(dir=folder, suffix=".tmp", delete=False) as output:
temporary = Path(output.name)
shutil.copyfileobj(stream, output, length=1024 * 1024)
size = output.tell()
temporary.replace(target)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
return {"name": name, "file": filename, "size_bytes": size}
+99 -52
View File
@@ -7,16 +7,21 @@ worker of the server answers for any job and a restart does not lose them. A job
code is `interrumpido`.
"""
import json
import os
import subprocess
import re
import subprocess as subprocess
import sys
import tomllib
import uuid
from datetime import datetime, timezone
from pathlib import Path
TAIL_CHARS = 4000
from webapi import detached_jobs
from webapi.detached_jobs import cluster_environment as _training_cluster
REFERENCE_ENV = {
"reference_name": "TEA_REFERENCE_NAME",
"reference_dir": "TEA_REFERENCE_DIR",
"reference_ages": "TEA_REFERENCE_AGES",
"line_hz": "TEA_REFERENCE_LINE_HZ",
}
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build; a scenario that says `external` in its
# `model.toml` does too, whatever its domain.
OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."}
@@ -36,7 +41,7 @@ def catalog() -> list[dict]:
domain = spec.get("domain")
if domain is None:
continue
own = domain in OWN_STEPS or bool(spec.get("external"))
own = domain in OWN_STEPS
if not own and "scenario" not in spec:
continue
found.append({
@@ -51,68 +56,111 @@ def _base() -> Path:
return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos"
def _command(domain: str, scenario: str) -> list[str]:
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"]
def _tea_parameters(body: dict, env: dict[str, str]) -> dict:
parameters = {key: body.get(key, env.get(variable) or None) for key, variable in REFERENCE_ENV.items()}
if not parameters["reference_dir"]:
for key in ("reference_ages", "line_hz"):
if key not in body:
parameters[key] = None
for key in ("reference_name", "reference_dir", "reference_ages"):
if key in body and (not isinstance(body[key], str) or not body[key] or "\0" in body[key]):
raise ValueError(f"{key} debe ser texto no vacío.")
name = parameters["reference_name"]
if name is not None and not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", name):
raise ValueError("reference_name debe tener de 1 a 64 caracteres de A-Z, a-z, 0-9, punto, guion o guion bajo.")
if "reference_dir" in body and not Path(body["reference_dir"]).is_absolute():
raise ValueError("reference_dir debe ser una ruta absoluta.")
if "line_hz" in body and (type(body["line_hz"]) not in (int, float) or body["line_hz"] not in (50, 60)):
raise ValueError("line_hz debe ser 50 o 60.")
promote = body.get("promote", True)
if not isinstance(promote, bool):
raise ValueError("promote debe ser un valor booleano.")
return {**parameters, "promote": promote}
def _resolve_cohort(parameters: dict, body: dict, root: str) -> None:
"""Point a named cohort at its folder (and ages table) under `root`, when the request gave no directory."""
name = parameters["reference_name"]
if "reference_dir" in body or not name or not root:
return
folder = Path(root) / name
if not folder.is_dir():
return
parameters["reference_dir"] = str(folder)
ages = folder / "edades.csv"
if "reference_ages" not in body and ages.is_file():
parameters["reference_ages"] = str(ages)
def _check_reference_paths(parameters: dict, root: str) -> None:
for key in ("reference_dir", "reference_ages"):
value = parameters[key]
if value is None:
continue
try:
path = Path(value).resolve()
inside_root = path.is_relative_to(Path(root).resolve())
except (OSError, RuntimeError, ValueError):
raise ValueError(f"No se pudo resolver la ruta de {key}.") from None
if not inside_root:
raise ValueError(f"{key} debe estar dentro de TEA_REFERENCE_ROOT.")
parameters[key] = str(path)
def _command(domain: str, scenario: str, parameters: dict | None = None) -> list[str]:
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train"]
if domain == "tea" and parameters is None:
parameters = _tea_parameters({}, os.environ)
if parameters is None or parameters["promote"]:
argv.append("--promote")
external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario))
if not external:
argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]]
elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"):
# A reference cohort on this machine's disk, instead of the configured one in the cluster's storage.
argv += ["--reference-dir", os.environ["TEA_REFERENCE_DIR"]]
if os.environ.get("TEA_REFERENCE_AGES"):
argv += ["--reference-ages", os.environ["TEA_REFERENCE_AGES"]]
if os.environ.get("TEA_REFERENCE_LINE_HZ"):
argv += ["--line-hz", os.environ["TEA_REFERENCE_LINE_HZ"]]
elif parameters is not None:
for key in ("reference_dir", "reference_ages", "line_hz", "reference_name"):
if parameters[key] is not None:
argv += [f"--{key.replace('_', '-')}", str(parameters[key])]
return argv
def _alive(pid: int) -> bool:
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def _tail(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else ""
def _state(folder: Path) -> dict:
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
exit_file = folder / "exit"
if exit_file.exists():
code = int(exit_file.read_text().strip() or 1)
state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido")
elif _alive(job["pid"]):
code, state = None, "en_curso"
else:
code, state = None, "interrumpido"
return {**job, "estado": state, "codigo": code, "salida": out, "error": err}
job = detached_jobs.state(folder)
if job["estado"] == "fallido" and "not promoted, missing" in job["error"]:
job["estado"] = "entrenado_sin_promover"
job.pop("parameters", None)
job.setdefault("cluster", None)
return job
def running(domain: str, scenario: str) -> dict | None:
return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None)
def start(domain: str, scenario: str) -> dict:
def start(domain: str, scenario: str, body: dict | None = None) -> dict:
"""Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest."""
if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}:
raise LookupError(f"no such model: {domain}/{scenario}")
if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"):
raise RuntimeError("No hay un manifest de dbt configurado.")
job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}"
folder = _base() / job_id
folder.mkdir(parents=True)
shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }'
process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid,
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
(folder / "job.json").write_text(json.dumps(job), encoding="utf-8")
env = os.environ.copy()
cluster = None
if domain == "tea":
body = {} if body is None else body
cluster = _training_cluster(body, env)
parameters = _tea_parameters(body, env)
if env.get("TEA_REFERENCE_ROOT") and (cluster is None or cluster["mode"] != "remote"):
_resolve_cohort(parameters, body, env["TEA_REFERENCE_ROOT"])
_check_reference_paths(parameters, env["TEA_REFERENCE_ROOT"])
argv = _command(domain, scenario, parameters)
if parameters["line_hz"] is None and parameters["reference_dir"]:
parameters["line_hz"] = 60
else:
parameters = None
argv = _command(domain, scenario)
folder = detached_jobs.launch(_base(), argv, env, {
"domain": domain, "scenario": scenario, "cluster": cluster, "parameters": parameters,
})
return _state(folder)
@@ -125,5 +173,4 @@ def get(job_id: str) -> dict:
def jobs(limit: int = 50) -> list[dict]:
"""The latest jobs, newest first."""
folders = sorted((p for p in _base().glob("*") if (p / "job.json").exists()), reverse=True) if _base().exists() else []
return [_state(p) for p in folders[:limit]]
return [_state(folder) for folder in detached_jobs.folders(_base())[:limit]]