Compare commits

...

75 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: #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: #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
edgar 2fe4101982 Cycle: estimate with every scenario in production, one batch per model
The scenarios come from the registry instead of a fixed list, and a cohort can carry several estimators.
2026-11-22 20:34:38 -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
edgar e0967d0175 Follow-up status: a case is a carcinoma, invasive or in situ 2026-11-22 19:16:44 -06:00
edgar 377882edd0 Follow-up list: a case's survival is 1 at 0 years, at the index date 2026-11-22 18:40:53 -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 c51402510a Follow-up list: each patient's latest biopsy and probabilities, ordered by one of them
Each row carries the patient's latest biopsy reported by the cut-off and her current probability of LIEAG+, of cancer
and, for a case, of surviving (the complement of the survival model's death, interval swapped) at every horizon, from
the confirmed batches her record shows. `orden` sorts the whole list, not a page, by the most recent study or by one
of those probabilities at `horizonte`; `horizontes_disponibles` names the horizons the models give.
2026-11-22 15:03:49 -06:00
edgar 7640486852 Follow-up status: CASO, a patient with a cancer biopsy
A biopsy reported with a grade of `cacu.seguimiento.caso.grados` (CARCINOMA, provisional) by the reference makes the
patient a case: the status wins over every other, and what is followed for her is survival. Only the follow-up list
reads this rule; the measures' stratum in dbt is unchanged.
2026-11-22 15:03:31 -06:00
edgar 4a61bd8d33 CaCu import: a patient's date of death
`pac_fecha_defuncion` was dropped on import, so `persona.fecha_defuncion` and the timeline's `defuncion` fact were
always empty in CaCu and the survival scenario trained with no deaths. CaMa's schema already carried it.
2026-11-22 15:03:22 -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: #17
2026-11-22 13:47:01 -06:00
edgar e2732f5e8a Risk batches: a decision that collides with another of the same batch is a 409
Two decisions of one batch at the same moment (a double click reaching both workers) wrote the same evaluation
version and the second surfaced as a server error.
2026-11-22 09:34:49 -06:00
edgar b9795c02ca FHIR: CaCu's risk names the results of its index cytology
The cytology sampled on the risk's index date gives its squamous, glandular and HPV results in the extension
`resultados-indice`, which the record words its sentence with. CaCu's outcome codes `cin2` and `cancer` get labels.
2026-11-22 09:34:49 -06:00
edgar b63a253b19 FHIR: one RiskAssessment per outcome, and one with no prediction for a model that didn't score her
The patient's Bundle holds the current batch of each outcome (`CohortRepository.current_risks`), so a CIN2+ and a
cancer model are both shown. For a patient with some risk, each current model of another outcome that didn't score
her (`current_batches`) gives a RiskAssessment with no prediction and the extension `sin-estimacion` (its outcome and
why it may be so), so the record can tell "no model" from "not estimated for her".
2026-11-22 09:34:49 -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
edgar f002e24811 FHIR: the patient's RiskAssessment says what the model's number is
The registered model's scenario (`[estimand]` of its `model.toml`) goes in the extension `estimando`, one
`valueString` per key, and its quantity as `method.text`. A model whose scenario can't be read has neither.
2026-11-22 07:47:05 -06:00
edgar a04ceb6301 Cycle: score with the models package's scored_frame, so a model's risk intervals reach the batch
The cycle read the run's horizons and called the model itself; `models.dags.estimation.scored_frame` does both, and
also reads whether the run gives each risk's interval.
2026-11-22 07:47:05 -06:00
edgar 03be05fb17 Docker: Graphviz in the image, so each model version stores its dataflow's drawing as SVG 2026-11-22 07:47:05 -06:00
edgar 0c69140d2e Tests: the windows from the sample to the diagnosis (120) and to the treatment (180)
The 161-day diagnosis of the fixture is out of the 120-day window, and the sample-to-treatment horizon (180) leaves the
August and October samples pending. The comparison with the kit's oracle (180 days to the diagnosis) is marked as an
expected divergence until the oracle is regenerated with the project's horizon.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:37:22 -06:00
edgar 1d52da79e4 FHIR: every URL the API emits hangs from one base, set by FHIR_BASE_URL
The code systems, value sets and the extensions (cut-offs, report id, interval, quartiles) each wrote the domain by
hand. They now derive from webapi.fhir_base, a leaf module so metrics and durations can use it without a cycle. The
default is unchanged; the WebApp still reads the same URLs by exact match, so changing the domain goes to both.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 02:54:23 -06:00
edgar 6d01742a85 Merge pull request 'CaCu indicators: times along the screening route, proportion intervals and survival notebooks' (#16) from integration/cacu-indicadores into dev
Reviewed-on: #16
2026-11-22 01:01:07 -06:00
edgar 8e5a7e3b81 test(cacu): the timeline's birth and death rows come from persona
CaCu's timeline now holds the patient's birth and death like CaMa's, so the comparison with the kit's rows leaves them
out along with the inferred procedures.
2026-11-22 00:28:43 -06:00
edgar d156bf3c99 test(cacu): cover the times along the screening route
The CaCu catalog holds fourteen measures. A fixture adds H-007, who goes the whole route in order, and a test pins the
population, the cases and the median of each of the five new times.
2026-11-22 00:23:23 -06:00
edgar 9461dfbd20 test(cacu): cover the two times to treatment
The CaCu catalog holds nine measures. A fixture adds H-004's colposcopy and treatment on top of the shared data, and a
test pins the days of both intervals with a 60-day horizon.
2026-11-22 00:23:17 -06:00
edgar 0a8e3577a1 feat(fhir): publish the Wilson interval of a proportion's score
A proportion's measureScore now carries its 95 % Wilson interval in the ic-bajo and ic-alto extensions,
as proportions, the way durations carry their quartiles. Nothing is published without a denominator.
2026-11-22 00:23:09 -06:00
edgar e44f0c84b3 Governance: run the notebooks kept in the code; plotly in the lock for the survival reports
GET /governance/notebook-templates?domain= lists the notebooks under models/<domain>/<scenario>/notebooks/ with the
scenarios each can run for (models.reports.templates: its folder's and any whose model.toml lists a module of it, so
CaCu's PIM subgroup report serves cin2_pim and its post-colposcopy and post-treatment scenarios). POST
/governance/experiments takes `template` (that id) instead of `file`: the notebook is read from the code, never from
the request, and runs like an upload (its page sandboxed, its hash on the run). A template for a scenario it doesn't
serve, an id outside the templates, or a file and a template together are refused.

uv.lock adds plotly 7.1.0: models' `survival-curves` extra now draws the CaCu subgroup reports (models:
cacu-survival/integration).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-22 00:23:04 -06:00
edgar 4840bd3dc8 Tests: a version declared over the API is blocked only by ML-01b
models dev (feb934d) relaxed ML-01a: not every model has the five routine records (a prevalence-incidence mixture
such as CaCu's PIM has no class balance or classifier calibration), so requiring all of them blocked the promotion
of models whose training run is in order. ML-01a now passes when the version comes from its training run, and its
detail reports which routine records that run holds. A version registered over HTTP still has a run, so it passes
ML-01a too; what keeps it from production is that it carries no saved model (ML-01b). This test expected both checks
to fail and would break as soon as the WebApi runs on that models dev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 19:22:32 -06:00
angel b7ce3e7ddd Merge pull request 'CaMa: FHIR risk, live survival and recurrence figures, governance training jobs, lesion-size extraction' (#14) from feature/cama-roundtrip into dev
Reviewed-on: #14
2026-11-21 15:02:47 -06:00
rockdrigo 4cc2ce83ac CaMa: scenario menus and risk-factor rows for the survival and recurrence analyses 2026-11-21 14:43:46 -06:00
rockdrigo d185aba364 Merge remote-tracking branch 'origin/dev' into dev-mvp 2026-11-21 13:53:57 -06:00
rockdrigo 0edac6d0e2 Lock: lifelines in the models dev group 2026-11-21 13:35:23 -06:00
rockdrigo 2c4bfa5691 Recurrence figures for a patient; governance trains scenarios with external data; lifelines in the lock 2026-11-21 13:34:56 -06:00
rockdrigo a53179aa2e Live survival: the scenarios of a patient and the figure of one scenario 2026-11-21 13:14:06 -06:00
rockdrigo 3b192207fd Live survival: no options route 2026-11-21 13:03:19 -06:00
angel 69d2d0e175 Merge pull request 'Integration/tea eeg analysis into dev' (#13) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: #13
2026-11-21 12:35:31 -06:00
Angel Capetillo Zavala 26631bd564 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:28 -06:00
rockdrigo 57947d4131 Live survival: score with the rehydrated production model 2026-11-21 12:15:22 -06:00
rockdrigo eeb4c1fbd5 CaMa survival: live options and selection routes over the production model 2026-11-21 12:07:21 -06:00
alberto 31ab347347 feat(tea): import the ADOS-2 association model and serve it as a RiskAssessment in the patient summary 2026-11-21 11:17:58 -06:00
alberto 46473bb106 feat(tea): each EEG metric's age-norm curve and the age at the EEG in the patient summary 2026-11-21 11:17:48 -06:00
rockdrigo 8b379db28b Governance trains TEA's EEG on a local reference folder when one is configured 2026-11-21 04:48:43 -06:00
rockdrigo dab78ad55e Merge remote-tracking branch 'origin/dev' into dev-mvp 2026-11-21 04:00:00 -06:00
rockdrigo 1a6db9cf6b Merge origin/feature/cohorts-dbt-canonical 2026-11-21 04:00:00 -06:00
rockdrigo e33eaafb08 Live estimators test says what it checks for CaMa 2026-11-21 03:33:44 -06:00
rockdrigo 2d71fe1103 Lesion size extracted from pathology reports; development record route; scenario catalog and background training jobs in governance 2026-11-21 03:28:13 -06:00
rockdrigo fae6b2232f The CaCu timeline fixture knows the biopsy order, and the rare-type wording test uses the ICD-O-3 codes 2026-11-21 02:57:36 -06:00
edgar 2ee95576a8 Tests: the cycle builds every dbt cohort of each project, CaMa's survival cohort included
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 02:14:26 -06:00
rockdrigo 6b011df0fd Merge the CaMa survival cohort support 2026-11-21 02:07:54 -06:00
rockdrigo 58d3291804 Merge CaMa risk, curves and generic estimators 2026-11-21 02:07:54 -06:00
rockdrigo e2ecaa027c CaMa: individual risk and population curves served, and the cycle estimates with any scenario in production
webapi/fhir/risk.py builds a patient's RiskAssessment for CaCu and CaMa; GET /cama/modelo/curvas serves the production
version's survival curves; the cycle's estimator is generic by scenario; silver persona carries the date of death for CaMa;
the import schema accepts it; the CaMa risk batches can be confirmed and voided.
2026-11-21 02:07:34 -06:00
edgar f34c2b5116 Merge remote-tracking branch 'origin/feature/163-cama-risk-curves' into feature/cohorts-dbt-canonical 2026-11-21 02:06:26 -06:00
rockdrigo 9b617db9d0 CaMa: two clinical scenarios, post-treatment and under observation, with the follow-up list's scenario column and filter 2026-11-21 01:55:04 -06:00
Angel Capetillo Zavala c2b18d9969 feat(fhir): publish optional category groups and stratum captions of compositions 2026-11-21 01:29:31 -06:00
rockdrigo d1e06798c9 Tests: no CaMa measure is served by clinical stage or tumour size; the stratifiers view is built in its own test 2026-11-20 23:28:33 -06:00
rockdrigo 8130f86f3a Silver persona carries the date of death in CaCu and CaMa; tests for it and for CaMa's birth and death on the timeline 2026-11-20 18:46:40 -06:00
rockdrigo 028f774400 Tests: CaMa's clinical scenarios as a hierarchy, with discharge notes starting post-treatment 2026-11-20 17:03:38 -06:00
rockdrigo ca0f02aa0c A coded catalog result may name the code system of its values; the histological type comes out as its ICD-O-3 code 2026-11-20 17:03:38 -06:00
rockdrigo 7a84cb19c9 Tests: each CaMa patient's scenario and the evidence that starts it 2026-11-20 17:03:38 -06:00
rockdrigo 5a4baeb33e Tests: CaMa's stage and size measures of invasive cancers, and the measure counts 2026-11-20 17:03:38 -06:00
111 changed files with 6543 additions and 520 deletions
+5 -2
View File
@@ -19,9 +19,10 @@ RUN uv sync --group sqlite --group sqlserver --group postgres \
FROM python:3.12-slim
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary. Graphviz's `dot` draws each
# trained version's dataflow (`diagramas/pipeline.svg`); without it only the `.dot` source is stored.
RUN apt-get update && apt-get install -y --no-install-recommends \
tesseract-ocr tesseract-ocr-spa \
tesseract-ocr tesseract-ocr-spa graphviz \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
@@ -49,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 -1
View File
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
dependencies = [
"flask>=3.0",
"persistance",
"models[notebooks,seer-survival]",
"models[notebooks,survival-curves,seer-survival]",
"extraction",
"apache-hamilton>=1.90",
"pandas>=2.0",
+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")
+217
View File
@@ -0,0 +1,217 @@
"""What this module covers: the publication metadata of CaCu's FHIR `Measure`s (figures, category captions and the
optional category groups) read from dbt's manifest alone, and the checks that keep a composition's groups consistent.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
reference parameters, whose CaCu catalogs and lists hold the captions, colours and memberships the dbt definitions
repeat; Transformation's `dbt_project.yml` next to the manifest, whose variables repeat the same lists.
"""
import os
import tomllib
from datetime import date, datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import pytest
from fhir.resources.R4B import get_fhir_model_class
from webapi.compositions import CompositionAnswer, InvalidCategoryGroups, category_groups
from webapi.fhir.measures import CATEGORY_GROUP, CATEGORY_LABEL, FIGURES, labels, measure_report, measure_resource
from webapi.kpis import definitions_of
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
GROUPED = {"CACU-EU7": "citologia_anomala", "CACU-CONFIRMACION-CITOLOGIA": "deteccion_grados"}
@pytest.fixture(scope="module")
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
def _measures(domain: str, manifest: Path) -> dict[str, dict]:
titles = labels(manifest)
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
for d in definitions_of(domain, manifest).values()}
@pytest.fixture(scope="module")
def measures(manifest):
"""Each CaCu measure as the API serves it, by its FHIR id."""
return _measures("cacu", manifest)
def reference(*keys: str):
with REFERENCE.open("rb") as f:
node = tomllib.load(f)
for key in keys:
node = node[key]
return node["valor"]
def figures(measure: dict) -> list[str]:
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
def categories(measure: dict) -> dict[str, dict[str, str]]:
"""The measure's declared categories, in order: code -> its parts (etiqueta, color and, if any, grupo)."""
return {part["codigo"]: part for part in (
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
for e in measure["extension"] if e["url"] == CATEGORY_LABEL)}
def groups(measure: dict) -> dict[str, str]:
"""The measure's category groups, in order: code -> caption."""
return {part["codigo"]: part["etiqueta"] for part in (
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
for e in measure["extension"] if e["url"] == CATEGORY_GROUP)}
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
"""Pins down: the two distributions offer the donut and the bars and the nine durations their box plot; the C1
proportions and the risk bands none, because no figure is approved for them yet. Fails if a figure is declared
that the page has no builder for, or one is dropped."""
assert {i: figures(m) for i, m in measures.items()} == {
"CACU-EU7": ["fig_c2_donas", "fig_c2_barras"], "CACU-CONFIRMACION-CITOLOGIA": ["fig_c2_donas", "fig_c2_barras"],
"CACU-EU-TIEMPO-REPORTE": ["fig_c3r_caja"], "CACU-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-DIAS-TOMA-TRATAMIENTO": ["fig_c3r_caja"], "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO": ["fig_c3r_caja"],
"CACU-DIAS-TOMA-COLPOSCOPIA": ["fig_c3r_caja"], "CACU-DIAS-TOMA-BIOPSIA": ["fig_c3r_caja"],
"CACU-DIAS-RESULTADO-COLPOSCOPIA": ["fig_c3r_caja"], "CACU-DIAS-COLPOSCOPIA-BIOPSIA": ["fig_c3r_caja"],
"CACU-DIAS-BIOPSIA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-EU13": [], "IND1": [], "CACU-RIESGO-BANDA": []}
def test_the_category_captions_are_the_reference_catalogs(measures):
"""Pins down: the captions, colours and order of the cytology distribution equal `cacu.catalogos.citologia` plus
`cacu.catalogos.sin_dato`, and the confirmation's grades `cacu.catalogos.biopsia`. Fails if either side is edited
without the other."""
sin_dato = reference("cacu", "catalogos", "sin_dato")
citologia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "citologia")}
eu7 = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-EU7"]).items()}
assert eu7 == {**citologia, "SIN_DATO": (sin_dato["etiqueta"], sin_dato["color"])}
biopsia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "biopsia")}
confirmacion = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-CONFIRMACION-CITOLOGIA"]).items()}
assert list(confirmacion)[:len(biopsia)] == list(biopsia)
assert {c: confirmacion[c] for c in biopsia} == biopsia
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
def test_the_anomalous_group_is_the_reference_list(measures, manifest, fhir_id):
"""Pins down: a grouped composition's ANORMAL members are exactly the parameter list the grouping is defined by
(`cacu.citologia_anomala` for EU7, `cacu.deteccion_grados` for the confirmation) and the dbt variable of the same
name; the other declared categories are NO_ANORMAL, «Sin dato» its own group and «Sin biopsia aún» none. Fails if
a membership drifts from the lists the measures count with."""
yaml = pytest.importorskip("yaml")
lista = GROUPED[fhir_id]
project = manifest.parent.parent / "dbt_project.yml"
dbt_vars = yaml.safe_load(project.read_text(encoding="utf-8"))["vars"] if project.exists() else None
parts = categories(measures[fhir_id])
anomalous = sorted(c for c, p in parts.items() if p.get("grupo") == "ANORMAL")
assert anomalous == sorted(reference("cacu", lista))
if dbt_vars is not None:
assert anomalous == sorted(dbt_vars[lista])
assert all(p.get("grupo") == "NO_ANORMAL" for c, p in parts.items()
if c not in anomalous and c not in ("SIN_DATO", "SIN_BIOPSIA"))
assert parts["SIN_DATO"]["grupo"] == "SIN_DATO"
assert "grupo" not in parts.get("SIN_BIOPSIA", {})
def test_the_group_captions_are_the_reference_ones(measures):
"""Pins down: EU7's groups are `cacu.catalogos.resultado_anormal` plus «Sin dato», and the confirmation's
«Menor que LIEAG» / «LIEAG o más» plus its no-data category's caption, in that order. Fails if a caption drifts."""
resultado = {e["clave"]: e["etiqueta"] for e in reference("cacu", "catalogos", "resultado_anormal")}
assert groups(measures["CACU-EU7"]) == {**resultado, "SIN_DATO": "Sin dato"}
assert groups(measures["CACU-CONFIRMACION-CITOLOGIA"]) == {
"NO_ANORMAL": "Menor que LIEAG", "ANORMAL": "LIEAG o más", "SIN_DATO": "Biopsia sin grado"}
def test_measures_without_groups_publish_none(manifest, measures):
"""Pins down: groups are opt-in. CaCu's other measures and every CaMa and TEA measure publish neither a
`categoria-grupo` nor a `grupo` inside a category. Fails if the new extensions leak onto measures that don't
declare them (their clients see exactly what they see without groups)."""
others = {**{i: m for i, m in measures.items() if i not in GROUPED},
**_measures("cama", manifest), **_measures("tea", manifest)}
for fhir_id, measure in others.items():
assert not groups(measure), fhir_id
assert all("grupo" not in part for part in categories(measure).values()), fhir_id
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
def test_a_grouped_measure_is_valid_fhir_r4b(measures, fhir_id):
"""Pins down: the nested `grupo` and the `categoria-grupo` extensions keep the Measure valid FHIR R4B. Fails if
the extensions are shaped in a way FHIR's models reject."""
get_fhir_model_class("Measure").model_validate(measures[fhir_id])
def test_a_composite_stratum_carries_its_caption(manifest):
"""Pins down: in a composition's report, a stratum value of a crossed stratifier (status by result) carries the
caption of `meta.etiquetas_estrato` as its display, and a value without one (an age group) keeps the code alone.
Fails if the captions stop reaching the report or start replacing codes."""
definition = next(d for d in definitions_of("cacu", manifest).values() if d.measure_id == "CACU_EU7")
result = CompositionAnswer(report_id=1, categories={"NORMAL": 2, "ASC-US": 1}, stored_before=True, strata={
"estatus_seguimiento": {"PRE_COLPOSCOPIA": {"NORMAL": 2}, "POST_COLPOSCOPIA": {"ASC-US": 1}},
"grupo_edad": {"25-34": {"NORMAL": 2, "ASC-US": 1}}})
question = SimpleNamespace(event_cutoff=None, knowledge_cutoff=None)
period = SimpleNamespace(inicio=date(2025, 7, 1), fin=date(2026, 1, 1))
report = measure_report(definition, question, result, period, datetime(2026, 1, 2, tzinfo=timezone.utc))
shown = {}
for stratifier in report["group"][0]["stratifier"][1:]:
for stratum in stratifier["stratum"]:
value = stratum["component"][0]["value"]["coding"][0]
shown[value["code"]] = value.get("display")
assert shown == {"PRE_COLPOSCOPIA": "Pre colposcopia", "POST_COLPOSCOPIA": "Post colposcopia", "25-34": None}
get_fhir_model_class("MeasureReport").model_validate(report)
RULE = {"sin_dato": "SIN_DATO", "etiquetas": {
"A": {"etiqueta": "A", "color": "#000000", "grupo": "G1"}, "B": {"etiqueta": "B", "color": "#000000", "grupo": "G2"},
"APARTE": {"etiqueta": "Aparte", "color": "#000000"},
"SIN_DATO": {"etiqueta": "Sin dato", "color": "#000000", "grupo": "SIN_DATO"}},
"grupos": {"G1": "Uno", "G2": "Dos", "SIN_DATO": "Sin dato"}}
def _with(**changes) -> dict:
rule = {**RULE, "etiquetas": {k: dict(v) for k, v in RULE["etiquetas"].items()}, "grupos": dict(RULE["grupos"])}
for path, value in changes.items():
*parents, last = path.split("__")
node = rule
for p in parents:
node = node[p]
if value is None:
node.pop(last, None)
else:
node[last] = value
return rule
def test_valid_groups_are_returned_in_order_and_a_category_may_stay_apart():
"""Pins down: declared and used groups come back in their declared order, and a category without `grupo` (one kept
apart) is allowed. Fails if a valid declaration is rejected or reordered."""
assert list(category_groups("x", RULE).items()) == [("G1", "Uno"), ("G2", "Dos"), ("SIN_DATO", "Sin dato")]
def test_a_composition_without_groups_has_none():
"""Pins down: groups are optional; neither `grupos` nor any `grupo` means none. Fails if declaring groups becomes
mandatory (CaMa's and TEA's compositions declare none)."""
rule = {k: v for k, v in RULE.items() if k != "grupos"}
rule["etiquetas"] = {c: {k: v for k, v in s.items() if k != "grupo"} for c, s in RULE["etiquetas"].items()}
assert category_groups("x", rule) == {}
@pytest.mark.parametrize("rule, message", [
(_with(grupos=None), "`grupos` is missing"),
(_with(etiquetas__A__grupo="G9"), "undeclared groups"),
(_with(grupos__G3="Tres"), "groups without categories"),
(_with(grupos__G1=" "), "non-empty caption"),
(_with(etiquetas__SIN_DATO__grupo="G1", grupos__SIN_DATO=None), "goes alone"),
(_with(etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "goes alone"),
(_with(etiquetas__SIN_DATO__grupo=None, etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "no-data category's own"),
])
def test_invalid_groups_fail_the_load(rule, message):
"""Pins down: each way a declaration can't be read as a partition fails with its reason (a group named but
missing, one declared but unused, an empty caption, the no-data category mixed with others or without its own
group). Fails if one of them is accepted, because the page would draw a wrong or incomplete grouping."""
with pytest.raises(InvalidCategoryGroups, match=message):
category_groups("x", rule)
+100 -4
View File
@@ -8,6 +8,7 @@ invented patients with the cases below; their names (`P01`...) are the source id
Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6):
BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day.
P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it.
No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some.
"""
import json
@@ -151,14 +152,17 @@ def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app):
"""Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data
doesn't support is added, or the hospital's identifier leaks."""
date, 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"} for i in cuerpo["items"])
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
"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"]
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
assert respuesta.headers["Cache-Control"] == "no-store"
@@ -368,3 +372,95 @@ def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_
with Session(base.motor) as sesion:
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")]
@pytest.fixture
def con_postratamiento(tmp_path):
"""The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on
2025-11-01 and P06 on 2026-01-15, after the cut-off."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
from sqlalchemy import text
base = base_de("cama", tmp_path, datos=insertar)
base.run(*UNTIL_MODELS, allow_undecided=True)
hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"}
with base.motor.begin() as c:
for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"):
try:
with c.begin_nested():
c.execute(text(drop))
except Exception:
pass
c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)"))
for hospital, fecha in hechos.items():
c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente "
"where pac_id_hospital = :h"), {"f": fecha, "h": hospital})
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
yield base, flask.test_client()
base.motor.dispose()
def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento):
"""Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the
cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it
and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from
something other than the timeline, or if the filter stops being offered."""
base, app = con_postratamiento
nombres = hospital_de(base)
escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"]
for i in get(app, corte=corte, page_size=200).get_json()["items"]}
al_corte = escenario(CORTE)
assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"}
assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"}
assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO"
filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200)
assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"}
filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico")
assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"},
{"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}]
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"]
+78
View File
@@ -0,0 +1,78 @@
"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`,
rules in `cama.escenarios`): post-treatment from a discharge note after a malignant breast tumour's diagnosis, carried by
her timeline as an `escenario_postratamiento` fact with the evidence that started it; every other patient is under
observation ("en observación"), which has no fact.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30,
H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30),
H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a
type: the tests that need a discharge write `nota_medica.tipo_nota` themselves.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture
def base(tmp_path, manifest):
base = base_de("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
yield base
base.motor.dispose()
def scenarios(base) -> dict[str, set[tuple[str, date, str]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence)."""
with base.motor.connect() as con:
rows = con.execute(text(
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l "
"join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all()
found: dict[str, set[tuple[str, date, str]]] = {}
for r in rows:
found.setdefault(r.pac_id_hospital, set()).add((r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo))
return found
def discharge(base, hospital_id: str) -> None:
"""Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would."""
with base.motor.begin() as con:
con.execute(text(
"insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) "
"select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' "
"from procedimiento p join paciente x on x.pac_id = p.pac_id "
"where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id})
def test_without_a_discharge_every_patient_is_under_observation(base):
"""Pins down: a mammogram, a malignant ICD-10 note (H-003, H-102, H-103) or an invasive biopsy (H-003) alone start
no scenario: with no discharge note nobody is in post-treatment and the timeline has no scenario fact, which reads as
under observation. Fails if screening or a diagnosis go back to being scenarios of their own."""
assert scenarios(base) == {}
def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base):
"""Pins down: a discharge note that carries a malignant tumour's ICD-10 puts H-003 in post-treatment from its date,
and only her. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops reading the note's type."""
discharge(base, "H-003")
assert scenarios(base) == {"H-003": {("escenario_postratamiento", date(2025, 8, 4), "egreso")}}
def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base):
"""Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her
under observation: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it."""
discharge(base, "H-101")
assert scenarios(base) == {}
+31 -60
View File
@@ -1,13 +1,13 @@
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
labels a timeline stratum's values carry into FHIR.
"""What this module covers: CaMa's tumour characteristics read from reports. dbt's `cama_estratificadores` (stage
group, early or advanced stage, T by size) as timeline facts; that no measure is served by clinical stage or tumour
size; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into FHIR.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
2025-07-28 from her BI-RADS 4A mammogram (14 mm), and a note of 2025-08-04 with stage IIA.
"""
import json
import os
from dataclasses import replace
from datetime import date
@@ -20,7 +20,7 @@ from webapi.compositions import answer_composition, composition_definitions
from webapi.fhir.measures import _label
from webapi.metrics import Question
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
BIRADS = "cama/CAMA_BIRADS_CANCER_INVASOR"
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
@@ -40,72 +40,43 @@ def base(tmp_path, sin_supresion, manifest):
base.motor.dispose()
def answered(base, manifest, period: str, event_cutoff: date | None = None):
def answered(base, manifest, url: str, period: str, event_cutoff: date | None = None):
d = base.dominio
definition = composition_definitions(manifest)[URL]
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
definition = composition_definitions(manifest)[url]
return answer_composition("cama", definition, Question(url, period, event_cutoff=event_cutoff),
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
def stratifiers(base) -> set[str]:
def stratifiers(base, manifest) -> set[str]:
"""The stratifiers' `tipo`s, from the view built here: no served measure reads it, so the cycle doesn't."""
node = next(n for n in json.loads(manifest.read_text(encoding="utf-8"))["nodes"].values()
if n["resource_type"] == "model" and n["name"] == "cama_estratificadores")
with base.motor.connect() as con:
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
return set(con.execute(text(f"select tipo from ({node['compiled_code']}) e")).scalars())
def test_the_stratifiers_come_from_h003_s_reports(base):
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
def test_the_stratifiers_come_from_h003_s_reports(base, manifest):
"""Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and
nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads
changes, or a subtype comes back."""
assert stratifiers(base, manifest) == {"estadio_ii", "etapa_temprana", "tamano_t1"}
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
category or a stratum's values drift."""
assert answered(base, manifest, "2025-S1").categories == {}
result = answered(base, manifest, "2025-S2")
assert result.categories == {"B4A": 1}
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
"tamano": {"T1": {"B4A": 1}}}
def test_no_measure_is_served_by_stage_or_tumour_size(manifest):
"""Pins down: clinical stage and tumour size aren't served as measures; they come from reports read by text, not
yet validated. Fails if a measure on them is published again."""
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
urls = {m["config"].get("meta", {}).get("measure_url") for m in metrics} - {None}
assert BIRADS in urls and BIRADS in composition_definitions(manifest)
assert not {u for u in urls if "ESTADIO" in u or "TAMANO" in u}
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
SUBTIPOS = [
({"her2": "H3"}, "subtipo_her2"),
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
({"her2": "H0", "ki67_pct": None}, None),
({"her2": "H2"}, None),
]
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
valores = {"receptor_progesterona": "POSITIVO", **cambios}
with base.motor.begin() as con:
for nombre, valor in valores.items():
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
{"v": valor, "r": f"biopsia.{nombre}"})
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest):
"""Pins down: the BI-RADS of the mammogram before an invasive cancer isn't broken down by the tumour's
characteristics, which describe the cancer and not that mammogram. Fails if tumour strata come back."""
result = answered(base, manifest, BIRADS, "2025-S2")
assert (result.categories, result.strata) == ({"B4A": 1}, {})
def test_a_timeline_stratum_s_values_carry_their_labels():
+62
View File
@@ -0,0 +1,62 @@
"""What this module covers: a patient's date of death, from staging (`paciente.pac_fecha_defuncion`) to silver's
`persona.fecha_defuncion` in CaCu and CaMa, and in CaMa onto her timeline as a `defuncion` fact next to her birth.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base_con_defuncion`, the domain's
fixture database (`staging/<domain>.py`) with one patient given a date of death before it's loaded.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
DEATH = date(2026, 2, 1)
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
def with_death(domain: str, tmp_path):
"""The domain's fixture database with its first patient (lowest `pac_id`) dead on `DEATH`, loaded to silver."""
base = base_de(domain, tmp_path)
with base.motor.begin() as con:
con.execute(text("update paciente set pac_fecha_defuncion = :d where pac_id = (select min(pac_id) from paciente)"),
{"d": DEATH})
return base
@pytest.mark.parametrize("domain", ["cacu", "cama"])
def test_silver_persona_carries_the_date_of_death(domain, tmp_path, manifest):
"""Pins down: the dead patient's `persona` has her date of death and everyone else's is null. Fails if the
staging-to-silver copy (`persons.de_derechohabiente`) stops carrying `pac_fecha_defuncion`."""
base = with_death(domain, tmp_path)
base.run("catalogs", "load")
with base.motor.connect() as con:
rows = con.execute(text("select pac_id, fecha_defuncion from persona order by pac_id")).all()
base.motor.dispose()
assert [date.fromisoformat(str(rows[0].fecha_defuncion)[:10])] + [r.fecha_defuncion for r in rows[1:]] \
== [DEATH] + [None] * (len(rows) - 1)
def test_cama_timeline_has_birth_for_everyone_and_death_for_the_dead(tmp_path, manifest):
"""Pins down: every CaMa patient has a `nacimiento` fact and only the dead one a `defuncion` fact, on her date of
death, with class `persona`. Fails if the timeline stops reading `persona` or reads a null date as a death."""
base = with_death("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
with base.motor.connect() as con:
people = con.execute(text("select count(*) from persona")).scalar_one()
facts = con.execute(text(
"select tipo, pac_id, fecha, clase from cama_linea_de_tiempo where tipo in ('nacimiento', 'defuncion')")).all()
first = con.execute(text("select min(pac_id) from persona")).scalar_one()
base.motor.dispose()
assert sum(f.tipo == "nacimiento" for f in facts) == people
assert [(f.pac_id, date.fromisoformat(str(f.fecha)[:10]), f.clase) for f in facts if f.tipo == "defuncion"] \
== [(first, DEATH, "persona")]
+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")
+3 -3
View File
@@ -121,14 +121,14 @@ def test_a_stage_is_found_in_a_note_without_a_caption():
def test_a_pathology_pdf_s_text_layer_gives_its_results():
"""Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop
"""Pins down: a PDF's text layer is read without OCR and every result on it comes out (the size, which the fixture report does not state, as nothing). Fails if bytes stop
going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor."""
leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1])))
assert {r: v for r, (v, _) in leido.items()} == {
"biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2",
"biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2",
"biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0,
"biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0,
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0,
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, "biopsia.tamano_tumor_mm": None,
}
+39
View File
@@ -0,0 +1,39 @@
"""Every FHIR URL the API emits hangs from one base, which FHIR_BASE_URL sets (issue 199)."""
import importlib
import sys
from webapi import durations, fhir_base, metrics
from webapi.fhir import common
POR_DEFECTO = "https://isssteleon.org/fhir"
def test_todas_las_urls_cuelgan_de_la_misma_base():
estructuras = [metrics.EVENT_CUTOFF, metrics.KNOWLEDGE_CUTOFF, metrics.HISTORY_ENTRY, metrics.INTERVAL_LOW, metrics.INTERVAL_HIGH]
assert all(u.startswith(f"{common.STRUCTURE}/") for u in estructuras)
assert common.STRUCTURE == f"{common.BASE}/StructureDefinition" == fhir_base.STRUCTURE
assert common.CODE_SYSTEM.startswith(common.BASE) and common.VALUE_SET.startswith(common.BASE)
def test_no_quedan_dominios_escritos_a_mano_fuera_de_la_base():
import pathlib
raiz = pathlib.Path(fhir_base.__file__).parent
escritos = [p.name for p in raiz.rglob("*.py") if "isssteleon.org" in p.read_text() and p.name != "fhir_base.py"]
assert escritos == []
def test_la_base_se_puede_cambiar_por_ambiente(monkeypatch):
monkeypatch.setenv("FHIR_BASE_URL", "https://fhir.ejemplo.test/base/")
try:
importlib.reload(fhir_base)
assert fhir_base.BASE == "https://fhir.ejemplo.test/base"
assert fhir_base.STRUCTURE == "https://fhir.ejemplo.test/base/StructureDefinition"
finally:
monkeypatch.delenv("FHIR_BASE_URL")
importlib.reload(fhir_base)
assert fhir_base.BASE == POR_DEFECTO
def test_los_q1_y_q3_de_los_tiempos_usan_la_misma_base():
assert durations.STRUCTURE == metrics.INTERVAL_LOW.rsplit("/", 1)[0]
+52
View File
@@ -107,3 +107,55 @@ def test_the_capability_statement_declares_the_search(client):
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
def test_each_outcome_is_its_own_risk_assessment(client, seeded):
"""Pins down: with a confirmed cancer batch next to the CIN2+ one, the patient's Bundle holds one RiskAssessment
per outcome, the newest first, each with its own outcome code. Fails if the route goes back to one batch, which
hides the other outcome's risk. Runs last: it adds a batch to the module's database."""
from persistance import cacu
scored, _, batch = seeded
cancer, _ = cacu.cohort_repository.save_batch(
_build_of(batch),
{"modelo_nombre": "cacu-cancer_pim", "modelo_version": "1", "mlflow_run_id": "r2", "modelo_sha": "s2"},
"cancer", [(scored, MODEL_INDEX, 3.0, 0.02, 0.01, 0.04)], ahora=datetime(2026, 10, 2, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(cancer, "final", "revisado")
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()
found = [e["resource"] for e in bundle["entry"]]
assert bundle["total"] == 2 and [r["id"] for r in found] == [f"{cancer}-{scored}", f"{batch}-{scored}"]
assert [r["prediction"][0]["outcome"]["coding"][0]["code"] for r in found] == ["cancer", "cin2_mas"]
def _build_of(batch: int) -> int:
from core.cacu.indicadores.models import EvaluacionRiesgoLote
from persistance.db import get_cacu_session
with get_cacu_session() as session:
return session.get(EvaluacionRiesgoLote, batch).armado_id
def test_a_current_model_that_did_not_score_her_says_so(client, seeded):
"""Pins down: a confirmed batch of another outcome that scored only another patient gives the scored patient a
RiskAssessment with no prediction and the `sin-estimacion` extension, while a patient with no risk at all still
gets an empty Bundle. Fails if the record can't tell "no model" from "not estimated for her", or a patient with
no risk gets one. Runs after the cancer test: it adds another batch to the module's database."""
from persistance import cacu
from webapi.fhir.risk import NOT_SCORED
scored, unscored, batch = seeded
other, _ = cacu.cohort_repository.save_batch(
_build_of(batch), {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r3",
"modelo_sha": "s3"},
"muerte", [(unscored, MODEL_INDEX, 1.0, 0.1, None, None)], ahora=datetime(2026, 10, 3, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(other, "final", "revisado")
found = {e["resource"]["id"]: e["resource"] for e in
client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()["entry"]}
missing = found[f"{other}-{scored}"]
marker = next(e for e in missing["extension"] if e["url"] == NOT_SCORED)
assert "prediction" not in missing and {"url": "desenlace", "valueCode": "muerte"} in marker["extension"]
assert len(found) == 3
+109
View File
@@ -0,0 +1,109 @@
"""What this module covers: `GET /cama/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cama`, built by
`webapi.fhir.risk` as CaCu's is): a patient's current mortality risk as a FHIR R4 `RiskAssessment` in a `searchset`
Bundle: its shape (status, subject, method, one prediction per horizon from the model's own index date, the interval
extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the
`CapabilityStatement` entry. The reads behind it are Persistance's, tested there.
Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaMa demonstration
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a total-cohort build with two of its patients, one
with a confirmed batch whose risks, at 0.5 and 1.5 years, have the model's index date.
"""
import os
from datetime import date, datetime, timezone
import pytest
from conftest import cliente_de
MODEL_INDEX = date(2026, 6, 1)
@pytest.fixture(scope="module")
def client(tmp_path_factory):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
with pytest.MonkeyPatch.context() as mp:
mp.setenv("DEV_REVISION", "pruebas")
yield from cliente_de("cama", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0.5 and 1.5 years, the
1.5-year one with an interval. Returns (scored patient, member without risks)."""
from core.cama.indicadores.models import CohorteArmado, CohorteMiembro
from persistance import cama
from persistance.db import get_cama_session
scored, unscored = [p.pac_id for p in cama.persona_repository.list(limit=2)]
with get_cama_session() as session:
build = CohorteArmado(url="cama/cohorte_total", version="0.1.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk-cama", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
session.add(build)
session.flush()
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
indice_fuente_tabla="biopsiamama", indice_fuente_id=str(p))
for p in (scored, unscored)])
session.commit()
build_id = build.armado_id
batch, _ = cama.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cama-survival", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
"muerte", [(scored, MODEL_INDEX, 1.5, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.5, 0.08, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cama.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, batch
def test_a_scored_patient_gets_her_risk_assessment(client, seeded):
"""Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/<pac_id>`, evaluated
when the batch was, by the registered model and version, with one prediction per horizon whose period starts at
the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension;
tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere."""
scored, _, batch = seeded
response = client.get(f"/cama/fhir/RiskAssessment?subject=Patient/{scored}")
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
bundle = response.get_json()
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1)
risk = bundle["entry"][0]["resource"]
assert bundle["entry"][0]["fullUrl"].endswith(f"/cama/fhir/RiskAssessment/{batch}-{scored}")
assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"})
assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z"
assert risk["method"]["coding"][0]["code"] == "cama-survival" and risk["method"]["coding"][0]["version"] == "3"
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["muerte", "muerte"]
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
(0.08, {"start": "2026-06-01", "end": "2026-12-01"}), (0.21, {"start": "2026-06-01", "end": "2027-12-01"})]
assert "extension" not in risk["prediction"][0]
assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}}
assert any(t["code"] == "simulado" for t in risk["meta"]["tag"])
def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded):
"""Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error.
Fails if a missing risk becomes a 404 or a resource with no predictions."""
_, unscored, _ = seeded
for subject in (f"Patient/{unscored}", "Patient/987654321"):
bundle = client.get(f"/cama/fhir/RiskAssessment?subject={subject}").get_json()
assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry`
@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"])
def test_the_risk_is_searched_by_patient(client, query):
"""Pins down: without `subject=Patient/<pac_id>` the answer is a 400 `OperationOutcome`. Fails if the route lists
every patient's risk."""
response = client.get(f"/cama/fhir/RiskAssessment{query}")
assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome"
def test_the_capability_statement_declares_the_search(client):
"""Pins down: CaMa's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient
resources stay TEA's. Fails if the route exists without being declared, or the other way round."""
resources = client.get("/cama/fhir/metadata").get_json()["rest"][0]["resource"]
risk = [r for r in resources if r["type"] == "RiskAssessment"]
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
+291
View File
@@ -0,0 +1,291 @@
"""What this module covers: the EEG metrics' age-norm curves in TEA's FHIR answers — how `BaselineCurves`
(`webapi.fhir.eeg_curves`) resolves the baseline label the analysis pinned (`eeg_metrica.met_modelo`,
`tea-<scenario>/<version>`, carried by `tea_paciente_eeg_metricas` as `modelo`) to its registered artifact's centile
curve, caching per label and omitting the curve on any failure; and how `webapi.fhir.tea` serves it: the curve as a
nested extension on each metric observation (`fuente`, `estado` tied to `TEA_ALTERACIONES_VALIDADAS`, then the
series) and the analysis's age (`eeg.eeg_edad_meses`) as an extension on the EEG's `DiagnosticReport`.
Fixtures: fakes for the registry, the module loader and the curve loader (no model registry is touched); `loaded`,
a TEA database (`base_de`) with one child and one analysed EEG whose posterior rhythm names a baseline, loaded
through the cycle up to `event_models`; needs `DBT_MANIFEST`.
"""
import os
from datetime import date
from types import SimpleNamespace
import pandas as pd
import pytest
from fhir.resources.R4B import get_fhir_model_class
from webapi.fhir import tea
from webapi.fhir.eeg_curves import BaselineCurves
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
CURVE = {"edad_meses": [16.0, 24.0, 36.0], "p5": [4.0, 5.0, 6.0], "p25": [4.5, 5.5, 6.5],
"mediana": [5.0, 6.0, 7.0], "p75": [5.5, 6.5, 7.5], "p95": [6.0, 7.0, 8.0]}
LABEL = "tea-eeg-posterior-rhythm/3"
class FakeRegistry:
"""Stands in for `models.io.registry.registry`: records the resolutions and answers or fails them."""
def __init__(self, error: Exception | None = None):
self.calls: list[tuple[str, str, str]] = []
self._error = error
def resolve(self, domain: str, scenario: str, version: str):
self.calls.append((domain, scenario, version))
if self._error is not None:
raise self._error
return SimpleNamespace(model_uri=f"models:/{domain}-{scenario}/{version}")
def module_with(curva: pd.DataFrame | None):
"""A loaded biomarker module as `models.tea.eeg.baselines` reads it: one baseline, maybe with a curve."""
return SimpleNamespace(baseline=SimpleNamespace(curva=curva))
class FakeCurves:
"""Stands in for `BaselineCurves` at the FHIR layer: answers per (label, metric), records what was asked."""
def __init__(self, curves: dict):
self._curves = curves
self.calls: list[tuple[str, str]] = []
def curve(self, label: str, metric: str):
self.calls.append((label, metric))
return self._curves.get((label, metric))
def test_the_label_resolves_to_the_pinned_version_s_curve():
"""Pins down: `curve(label, metric)` resolves the label to (domain, scenario, version), loads that version's
module and returns its baseline's centiles with the ages and the five percentiles. Fails if the label parsing,
the resolution arguments or the series extraction drift from `eeg_metrica.met_modelo`'s shape."""
registry = FakeRegistry()
loads: list[str] = []
curves = BaselineCurves(registry=registry, loader=lambda uri: loads.append(uri) or module_with(pd.DataFrame({
"edad_meses": CURVE["edad_meses"], "n_efectivo": [50.0, 60.0, 40.0],
**{p: CURVE[p] for p in ("p5", "p25", "mediana", "p75", "p95")}})))
assert curves.curve(LABEL, "ritmo_posterior") == CURVE
assert registry.calls == [("tea", "eeg-posterior-rhythm", "3")]
assert loads == ["models:/tea-eeg-posterior-rhythm/3"]
def test_the_module_loads_once_per_label():
"""Pins down: repeated asks of one curve reuse the module loaded for its label instead of reloading it, and a
second label loads its own. Fails if the caching moves from per label to per call."""
registry = FakeRegistry()
loads: list[str] = []
frame = pd.DataFrame(CURVE)
curves = BaselineCurves(registry=registry, loader=lambda uri: loads.append(uri) or module_with(frame))
n2 = "tea-eeg-spindles-n2/2"
first = curves.curve(n2, "husos_sueno_n2")
assert curves.curve(n2, "husos_sueno_n2") is first
assert curves.curve("tea-eeg-spindles-n3/1", "husos_sueno_n3") == CURVE
assert loads == ["models:/tea-eeg-spindles-n2/2", "models:/tea-eeg-spindles-n3/1"]
assert registry.calls == [("tea", "eeg-spindles-n2", "2"), ("tea", "eeg-spindles-n3", "1")]
def test_a_multi_scenario_label_uses_the_metric_s_own_scenario():
"""Pins down: a label that joined the electrode baseline's name (`;`-separated, as the analysis writes when it
also scored electrodes) resolves the metric's own scenario. Fails if the split or the scenario match breaks."""
registry = FakeRegistry()
curves = BaselineCurves(registry=registry, loader=lambda uri: module_with(pd.DataFrame(CURVE)))
label = "tea-eeg-spindles-n2/2;tea-eeg-spindle-topography-n2/5"
assert curves.curve(label, "husos_sueno_n2") == CURVE
assert registry.calls == [("tea", "eeg-spindles-n2", "2")]
def test_a_label_that_doesnt_name_the_metric_s_baseline_draws_no_curve():
"""Pins down: a label without the metric's scenario (another metric's baseline) and a metric the analysis
doesn't map both give None without touching the registry. Fails if the lookup starts resolving the wrong
scenario."""
registry = FakeRegistry()
curves = BaselineCurves(registry=registry, loader=lambda uri: module_with(pd.DataFrame(CURVE)))
assert curves.curve(LABEL, "husos_sueno_n2") is None
assert curves.curve(LABEL, "ritmo_inexistente") is None
assert registry.calls == []
def test_an_unresolvable_label_or_an_unloadable_module_omits_the_curve():
"""Pins down: a registry that can't resolve the version, and a loader that fails, both give None, so answers
keep working without a reachable registry. Fails if a failure starts propagating instead of omitting."""
failing = BaselineCurves(registry=FakeRegistry(LookupError("no version 3")), loader=lambda uri: None)
assert failing.curve(LABEL, "ritmo_posterior") is None
broken = BaselineCurves(registry=FakeRegistry(), loader=lambda uri: (_ for _ in ()).throw(RuntimeError("x")))
assert broken.curve(LABEL, "ritmo_posterior") is None
def test_a_baseline_without_a_curve_or_with_too_few_points_draws_none():
"""Pins down: age-block baselines (no `curva`) and curves with fewer than two complete points give None, and
rows missing a percentile are dropped. Fails if an undrawable curve starts being served."""
registry = FakeRegistry()
no_curve = BaselineCurves(registry=registry, loader=lambda uri: module_with(None))
assert no_curve.curve(LABEL, "ritmo_posterior") is None
sparse = pd.DataFrame({"edad_meses": [16.0, 24.0], "p5": [4.0, None], "p25": [4.5, None], "mediana": [5.0, None],
"p75": [5.5, None], "p95": [6.0, None]})
one_point = BaselineCurves(registry=registry, loader=lambda uri: module_with(sparse))
assert one_point.curve(LABEL, "ritmo_posterior") is None
partial = pd.DataFrame({"edad_meses": [16.0, 24.0, 36.0], "p5": [4.0, None, 6.0], "p25": [4.5, None, 6.5],
"mediana": [5.0, None, 7.0], "p75": [5.5, None, 7.5], "p95": [6.0, None, 8.0]})
dropped = BaselineCurves(registry=registry, loader=lambda uri: module_with(partial))
assert dropped.curve(LABEL, "ritmo_posterior") == {"edad_meses": [16.0, 36.0], "p5": [4.0, 6.0],
"p25": [4.5, 6.5], "mediana": [5.0, 7.0],
"p75": [5.5, 7.5], "p95": [6.0, 8.0]}
def metric_row(**cambios) -> dict:
"""One `tea_paciente_eeg_metricas` row of a scored posterior rhythm, with the analysis's baseline label."""
row = {"procedimiento_id": 7, "pac_id": 1, "metrica": "ritmo_posterior", "valor": 6.8, "valor_z": -4.08,
"grupo_edad_eeg": "16_23", "ref_min": 4.5, "ref_mediana": 5.75, "ref_max": 8.0,
"estado": "disminuido", "modelo": LABEL}
return {**row, **cambios}
def eeg_row(**cambios) -> dict:
"""One `tea_paciente_eegs` row: the study's valid EEG, with the age its analysis compared references at."""
row = {"procedimiento_id": 7, "pac_id": 1, "fecha_eeg": date(2025, 5, 20), "con_sueno": 1, "canales": 19,
"duracion_min": 25.0, "edad_meses": 23.6, "nivel": "completo", "fraccion_limpia": 0.95,
"canales_malos": 0, "ruido_linea_db": -30.0, "calidad": "BUENO", "valido": 1}
return {**row, **cambios}
def sub_series(extension: dict) -> dict:
"""A curve extension's sub-extensions back as series: each name's values in order."""
out: dict[str, list] = {}
for e in extension["extension"]:
out.setdefault(e["url"].rsplit("/", 1)[1], []).append(e.get("valueDecimal", e.get("valueString")))
return out
def test_a_metric_observation_carries_its_curve_as_a_nested_extension(monkeypatch):
"""Pins down: with the alterations validated, a metric row with a baseline label gets one `curva-referencia`
extension whose `fuente` is the label, whose `estado` reads `validada`, and whose series come back as ordered
sub-extensions (`edad-meses`, then p5 to p95). Fails if the extension's shape or the gate tie changes."""
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False,
curves=FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
(curve,) = observation["extension"]
assert curve["url"] == f"{tea.STRUCTURE}/curva-referencia"
series = sub_series(curve)
assert series["fuente"] == [LABEL] and series["estado"] == ["validada"]
expected = {"edad-meses": CURVE["edad_meses"], **{p: CURVE[p] for p in ("p5", "p25", "mediana", "p75", "p95")}}
for name, values in expected.items():
assert series[name] == values
get_fhir_model_class("Observation").model_validate(observation)
def test_the_curve_estado_follows_the_validation_gate(monkeypatch):
"""Pins down: without `TEA_ALTERACIONES_VALIDADAS` the same observation's `estado` reads `pendiente`, the
state the summary's other endpoints report while the references await validation. Fails if `estado` stops
reflecting the gate."""
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False,
curves=FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
(curve,) = observation["extension"]
assert sub_series(curve)["estado"] == ["pendiente"]
def test_an_undrawable_curve_is_omitted():
"""Pins down: a loader that can't resolve the label, and a metric row without a label, both give an
observation with no extension, and the loader isn't even asked without a label. Fails if a failed resolution
starts leaking an empty or partial curve."""
loader = FakeCurves({})
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False, curves=loader)
assert "extension" not in observation and loader.calls == [(LABEL, "ritmo_posterior")]
(unlabeled,) = tea.metric_observations(eeg_row(), [metric_row(modelo=None)], [], "P-X", False, curves=loader)
assert "extension" not in unlabeled and loader.calls == [(LABEL, "ritmo_posterior")]
def test_the_eeg_report_carries_the_analysis_age_as_an_extension():
"""Pins down: the `DiagnosticReport` carries `edad-meses` next to `duracion-min` and `canales`, and drops it
with them when null. Fails if the age stops reaching the report or leaves the extension block the others share."""
(procedure, report, *_) = tea.eeg_resources(eeg_row(), "P-X", [], [], False)
extensions = {e["url"].rsplit("/", 1)[-1]: e for e in report["extension"]}
assert extensions["edad-meses"]["valueDecimal"] == 23.6
assert extensions["duracion-min"]["valueDecimal"] == 25.0 and extensions["canales"]["valueInteger"] == 19
(_, bare, *_) = tea.eeg_resources(eeg_row(edad_meses=None, duracion_min=None, canales=None), "P-X", [], [],
False)
assert "extension" not in bare
for resource in (procedure, report):
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
def _rows(sesion):
from core.tea.models import Eeg, EegMetrica, Mchat, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1,
eeg_nivel="completo", eeg_fraccion_limpia=0.95, eeg_edad_meses=23.6, eeg_con_sueno=1,
eeg_canales=19, eeg_duracion_min=25.0))
sesion.add(EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=-4.08,
met_fuera=-1, met_p5=4.5, met_mediana=5.75, met_p95=8.0, met_modelo=LABEL))
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models: one child whose analysed EEG's rhythm names a baseline."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_curvas"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
@pytest.fixture()
def queries():
"""The domain's dbt query repository, aimed at the `loaded` database by `base_de`'s `point_to`."""
from persistance import tea as dominio
return dominio.dbt_query_repository
def test_the_analysis_age_reaches_the_eegs_view(loaded, queries):
"""Pins down: `eeg.eeg_edad_meses` flows through the silver mapping and `tea_paciente_eegs` as `edad_meses`.
Fails if the silver mapping or the views drop the age again."""
from sqlalchemy import select
from webapi.fhir.tea import EEGS
(row,) = tea._rows(queries, select(EEGS.c.edad_meses))
assert row["edad_meses"] == 23.6
def test_the_metric_view_carries_the_baseline_label(loaded, queries):
"""Pins down: `eeg_metrica.met_modelo` flows through the silver mapping and `tea_paciente_eeg_metricas` as
`modelo`, the only label the FHIR layer reads. Fails if the silver mapping or the views drop the label again."""
from sqlalchemy import select
from webapi.fhir.tea import METRICS
(row,) = tea._rows(queries, select(METRICS).where(METRICS.c.metrica == "ritmo_posterior"))
assert row["modelo"] == LABEL
def test_the_patient_summary_draws_the_curve_and_the_age(loaded, queries, monkeypatch):
"""Pins down `$resumen-tea`: with the alterations validated and a resolvable baseline, the metric observation
carries the curve (`fuente` the stored label) and the report the `edad-meses` extension; with an unresolvable
baseline the same summary answers with no curve. Fails if the summary stops wiring the label, the loader or
the age."""
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
monkeypatch.setattr("webapi.fhir.tea.baseline_curves",
lambda: FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
bundle = tea.patient_summary(queries, 1, date(2025, 12, 31), False)
resources = [e["resource"] for e in bundle["entry"]]
(observation,) = [r for r in resources if r["id"].startswith("ritmo-posterior-")]
(curve,) = observation["extension"]
assert sub_series(curve)["fuente"] == [LABEL]
(report,) = [r for r in resources if r["resourceType"] == "DiagnosticReport"]
assert any(e["url"].endswith("/edad-meses") and e["valueDecimal"] == 23.6 for e in report["extension"])
for resource in resources:
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
monkeypatch.setattr("webapi.fhir.tea.baseline_curves",
lambda: BaselineCurves(registry=FakeRegistry(LookupError("sin registry"))))
bare = tea.patient_summary(queries, 1, date(2025, 12, 31), False)
assert all("extension" not in e["resource"] for e in bare["entry"]
if e["resource"]["resourceType"] == "Observation"
and e["resource"]["id"].startswith("ritmo-posterior-"))
+1 -1
View File
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
domain, client = domain_client
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
assert measures["total"] == {"cacu": 7, "cama": 11}[domain]
assert measures["total"] == {"cacu": 14, "cama": 11}[domain]
for item in measures["entry"]:
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
assert response.status_code in (200, 409), response.get_json()
+155
View File
@@ -0,0 +1,155 @@
"""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 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`.
"""
import os
from datetime import date
import pytest
from test_fhir_tea import get, resources
from conftest import base_de
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
def _rows(sesion):
"""The kit's seven children, plus a fitted model: one item row (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)
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
sesion.add_all([
RelacionAdos2(rel_id="rel-2a", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
rel_resultado="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="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([
RelacionAdos2Paciente(rap_id="rap-2a", rap_rel_id="rel-2a", rap_eeg_id="eeg-1b", rap_valor_z=-4.08,
rap_probabilidad=0.81, rap_probabilidad_referencia=0.22),
RelacionAdos2Paciente(rap_id="rap-2b", rap_rel_id="rel-2b", rap_eeg_id="eeg-1b", rap_valor_z=-4.08,
rap_probabilidad=0.35, rap_probabilidad_referencia=0.4),
])
@pytest.fixture(scope="module")
def client(tmp_path_factory):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
mp = pytest.MonkeyPatch()
mp.setenv("DEV_REVISION", "pruebas")
mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
base = base_de("tea", tmp_path_factory.mktemp("tea_fhir_relacion"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
base.motor.dispose()
mp.undo()
def _extension(resource: dict) -> dict:
return {e["url"].rsplit("/", 1)[-1]: e for e in resource["extension"]}
def test_the_summary_emits_the_model_as_one_risk_assessment(client):
"""Pins down: child 1's summary carries one `RiskAssessment` (tagged simulated) with the model's metadata on
the resource (version, expert validation, level, cohort size), dated at the study's EEG (20 May), based on the
EEG's DiagnosticReport and the ADOS-2 Observation, and with one prediction per association row, the clearest
cohort association (lowest q) first. Fails if the resource loses a metadata extension, changes order, or stops
referencing what it was scored from."""
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
(child_1,) = episodes
bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea")
(riesgo,) = resources(bundle, "RiskAssessment")
assert riesgo["id"] == f"relacion-ados2-{child_1['id']}"
assert riesgo["occurrenceDateTime"] == "2025-05-20"
assert riesgo["meta"]["tag"][0]["code"] == "simulado"
extension = _extension(riesgo)
assert extension["modelo-version"]["valueString"] == "0.2.0"
assert extension["modelo-validado"]["valueBoolean"] is False
assert extension["modelo-nivel"]["valueString"] == "item"
assert extension["modelo-n-cohorte"]["valueInteger"] == 60
(report,) = resources(bundle, "DiagnosticReport")
ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-"))
assert riesgo["basis"] == [{"reference": f"DiagnosticReport/{report['id']}"},
{"reference": f"Observation/{ados2['id']}"}]
assert len(riesgo["prediction"]) == 2
assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2_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 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 (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
bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea")
(riesgo,) = resources(bundle, "RiskAssessment")
item, dominio = riesgo["prediction"]
assert item["outcome"]["coding"][0] == {
"system": "https://isssteleon.org/fhir/CodeSystem/tea-ados2-resultado", "code": "ados2_item_07",
"display": "Disfrute compartido en la interacción"}
assert dominio["outcome"]["coding"][0] == {
"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"] == {
"system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-metrica", "code": "RITMO_POSTERIOR",
"display": "Ritmo posterior"}
assert extension["zona"]["valueCoding"] == {
"system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-zona", "code": "occipital",
"display": "Occipital"}
assert (extension["tipo"]["valueString"], extension["evento"]["valueString"]) == ("item", ">=1")
assert extension["valor-z"]["valueDecimal"] == -4.08
assert (extension["odds-ratio"]["valueDecimal"], extension["ic-inf"]["valueDecimal"],
extension["ic-sup"]["valueDecimal"], extension["q"]["valueDecimal"]) == (3.5, 1.4, 8.7, 0.02)
assert extension["probabilidad-referencia"]["valueDecimal"] == 0.22
assert extension["observado"]["valueInteger"] == 2
assert _extension(dominio)["observado"]["valueInteger"] == 7
def test_the_summary_omits_the_model_without_rows(client):
"""Pins down: a child whose study EEG no model row scored gets no `RiskAssessment` at all (not an empty one):
child 2, in neuropediatrics without an EEG. Fails if the emission stops keying on the view's rows."""
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&etapa=NEUROPEDIATRIA"))
(child_2,) = episodes
bundle = get(client, f"/tea/fhir/Patient/{child_2['id']}/$resumen-tea")
assert not resources(bundle, "RiskAssessment")
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"}
+64
View File
@@ -0,0 +1,64 @@
"""What this module covers: `webapi.fhir.risk.risk_assessment` naming what the model's number is (`[estimand]` of its
scenario's `model.toml`) in the extension `estimando` and `method.text`, and leaving both out for a model whose
scenario can't be read.
Fixtures: none; the patient's risk is a stand-in with the fields `PatientRisk` has.
"""
from datetime import date, datetime, timezone
from types import SimpleNamespace
from webapi.fhir import risk
def _risk(modelo_nombre):
horizon = SimpleNamespace(horizonte_anios=1.0, probabilidad=0.1, ic_bajo=0.05, ic_alto=0.2)
return SimpleNamespace(lote_id=1, estado_lote="final", evaluado_en=datetime(2026, 1, 1, tzinfo=timezone.utc),
modelo_nombre=modelo_nombre, modelo_version="2", fecha_indice=date(2025, 1, 1),
horizontes=[horizon], desenlace="cin2")
def test_the_risk_says_what_its_number_is():
"""Pins down: a PIM risk carries its scenario's quantity, outcome and horizons' unit. Fails if the extension's url
or keys change, which the WebApp reads, or the scenario stops being found by the registered name."""
found = risk.risk_assessment(7, _risk("cacu-cin2_pim"), True, {}, "cin2_mas")
extension = {e["url"]: e["valueString"] for e in found["extension"][0]["extension"]}
assert found["extension"][0]["url"] == risk.ESTIMAND and found["method"]["text"] == "Riesgo acumulado"
assert extension["horizons_unit"] == "años" and extension["outcome"].startswith("CIN2+")
def test_a_model_without_a_scenario_has_no_estimand():
"""Pins down: a registered name with no scenario behind it gives the resource without the extension. Fails if
a missing scenario breaks the patient's risk."""
found = risk.risk_assessment(7, _risk("cacu-no_existe"), True, {}, "cin2_mas")
assert "text" not in found["method"] and not any(e.get("url") == risk.ESTIMAND for e in found.get("extension", []))
def test_a_cacu_risk_names_the_results_of_its_index_cytology(monkeypatch):
"""Pins down: CaCu's RiskAssessment carries the squamous, glandular and HPV results of the cytology sampled on the
risk's index date (the most complete if there are several), which the record words its sentence with; a risk
with none that day has no such extension. Fails if the extension's url or keys change, or another day's sample
is read."""
from persistance import cacu as repos
from webapi.fhir import cacu
asked = []
def rows(**filters):
asked.append(filters)
return [SimpleNamespace(cit_celulas_escamosas="LIEBG", cit_celulas_glandulares=None, cit_vph_resultado=None),
SimpleNamespace(cit_celulas_escamosas="LIEBG", cit_celulas_glandulares=None,
cit_vph_resultado="POSITIVO")]
monkeypatch.setattr(repos.citologia_cervical_repository, "list", rows)
found = cacu.risk_assessment(7, _risk("cacu-cin2_pim"), True)
extension = next(e for e in found["extension"] if e["url"] == cacu.INDEX_RESULTS)
assert {e["url"]: e["valueString"] for e in extension["extension"]} == {"escamosas": "LIEBG", "vph": "POSITIVO"}
assert asked[0]["pac_id"] == 7 and asked[0]["cit_fecha_toma"] == date(2025, 1, 1)
monkeypatch.setattr(repos.citologia_cervical_repository, "list", lambda **filters: [])
without = cacu.risk_assessment(7, _risk("cacu-cin2_pim"), True)["extension"]
assert not any(e["url"] == cacu.INDEX_RESULTS for e in without)
+1 -1
View File
@@ -201,7 +201,7 @@ def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client):
from webapi.fhir import tea
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial",
"duracion_min": 25.0, "canales": 19}
"duracion_min": 25.0, "edad_meses": None, "canales": 19}
checks = [
{"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None,
"bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"},
+51 -4
View File
@@ -113,13 +113,13 @@ REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_vali
def test_model_version_lifecycle_over_http(client):
"""A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can,
and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared
over the API, or promotion stops retiring the previous version."""
"""A version registered over HTTP carries no saved model, so it can't be promoted; trained ones can, and promoting
the second retires the first. Fails if the ML-01b check starts trusting what's declared over the API, or promotion
stops retiring the previous version."""
declared = _register(client, "v0", scenario="lifecycle")
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json()
assert checks["ready"] is False
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"]
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote")
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
@@ -448,3 +448,50 @@ def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
refused before anything runs. Fails if `/experiments` stops checking any of them."""
response = _run(client, notebook or _notebook("1"), **fields)
assert response.status_code in (400, 404)
def _run_template(client, template, *, scenario):
form = {"template": template, "domain": "cacu", "scenario": scenario, "url": "cacu/cohorte_vigilancia",
"source": "dbt", "build": "4"}
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
def test_the_notebooks_kept_in_the_code_are_listed_with_their_scenarios(client, notebooks):
"""Fails if `/notebook-templates` stops listing the notebooks under `models/<domain>/<scenario>/notebooks/` or the
scenarios each can run for."""
found = {t["id"]: t for t in client.get("/governance/notebook-templates", query_string={"domain": "cacu"})
.get_json()["templates"]}
assert "cin2_pim_post_colposcopy" in found["cacu/cin2_pim/reporte_subgrupos"]["scenarios"]
assert found["cacu/survival/reporte_subgrupos"]["scenarios"] == ["survival"]
def test_a_template_runs_like_an_upload_with_the_notebook_read_from_the_code(client, notebooks, monkeypatch):
"""Pins down: a template answers 202 with a run whose notebook is the template's, read from the code (the run
itself is left queued here). Fails if the request's notebook could stand in for the template or the run loses its
name."""
from models.reports.rendering import notebook_sha256
from models.reports.templates import template_notebook
from webapi.blueprints import governance
monkeypatch.setattr(governance, "submit", lambda job, *args: None)
started = _run_template(client, "cacu/cin2_pim/reporte_subgrupos", scenario="cin2_pim_post_colposcopy")
assert started.status_code == 202, started.get_json()
run = started.get_json()
assert run["notebook"] == "reporte_subgrupos" and run["scenario"] == "cin2_pim_post_colposcopy"
assert run["notebook_sha256"] == notebook_sha256(template_notebook("cacu/cin2_pim/reporte_subgrupos")[1])
@pytest.mark.parametrize("template, scenario, status", [
("cacu/survival/reporte_subgrupos", "cin2_pim", 400), # not a scenario it serves
("cacu/../../etc/passwd", "cin2_pim", 400), # not a template id
("cacu/cin2_pim/no_existe", "cin2_pim", 404), # no such template
])
def test_a_template_that_does_not_serve_the_run_is_refused(client, notebooks, template, scenario, status):
"""Fails if a template runs for a scenario it doesn't serve, or an id reaches a file outside the templates."""
assert _run_template(client, template, scenario=scenario).status_code == status
def test_a_file_and_a_template_together_are_refused(client, notebooks):
"""Fails if a request with both a file and a template runs either."""
response = _run(client, _notebook("1"), template="cacu/survival/reporte_subgrupos", scenario="survival")
assert response.status_code == 400
+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"
+139
View File
@@ -0,0 +1,139 @@
"""What this module covers: the ADOS-2 association model's import targets (`tea.RelacionAdos2` and
`tea.RelacionAdos2Paciente`): their registration in `/imports/targets` with the natural keys the tables' unique
constraints define, the upsert merge on those keys through the import service (a re-import updates in place
instead of duplicating), and the schemas' validations (probabilities and q within [0, 1], the confidence
interval's order, the outcome code per level, the cataloged biomarker and level, the bounded key columns).
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`).
"""
import base64
import json
import pytest
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("tea")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
def _json_source(records: list[dict], *, target: str) -> dict:
raw = json.dumps(records).encode()
return {
"source_type": "json",
"target": target,
"column_mapping": {name: name for name in records[0]},
"payload": {"file_base64": base64.b64encode(raw).decode()},
}
# One item row (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": "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": "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.
_PACIENTE_1 = {"rap_id": "rap-1", "rap_rel_id": "rel-1", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
"rap_probabilidad": 0.81, "rap_probabilidad_referencia": 0.22}
_PACIENTE_2 = {"rap_id": "rap-2", "rap_rel_id": "rel-2", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
"rap_probabilidad": 0.35, "rap_probabilidad_referencia": 0.4}
def test_targets_list_the_association_tables_with_their_natural_keys(client):
"""Pins down: `/imports/targets` exposes both association tables with the conflict fields of the tables' unique
constraints (uq_relacion_ados2, uq_relacion_ados2_paciente), so `on_conflict=upsert` merges on them, and lists
them as fields to map. Fails if a target is deregistered or its conflict fields drift from the constraints."""
targets = {t["key"]: t for t in client.get("/imports/targets").get_json()["targets"]}
modelo, paciente = targets["tea.RelacionAdos2"], targets["tea.RelacionAdos2Paciente"]
assert modelo["conflict_fields"] == ["rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"]
assert paciente["conflict_fields"] == ["rap_rel_id", "rap_eeg_id"]
assert {"rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"} <= {f["name"] for f in modelo["fields"]}
assert {"rap_rel_id", "rap_eeg_id"} <= {f["name"] for f in paciente["fields"]}
def test_model_and_patient_rows_import_and_reimport_upserts_on_the_natural_keys(client):
"""Pins down: both tables load through the import service and a second import of the same rows updates in
place (created 0, nothing duplicated), keeping the value the later import carried. Fails if the conflict
fields stop matching the natural key (rows would duplicate) or the upsert stops updating."""
fuentes = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
_json_source([_PACIENTE_1, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
body = client.post("/imports/commit", json={"sources": fuentes, "on_conflict": "upsert"}).get_json()
assert [(r["target"], r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [
("tea.RelacionAdos2", 2, 0, 0), ("tea.RelacionAdos2Paciente", 2, 0, 0)]
cambiada = {**_PACIENTE_1, "rap_probabilidad": 0.55}
otra_vez = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
_json_source([cambiada, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
body = client.post("/imports/commit", json={"sources": otra_vez, "on_conflict": "upsert"}).get_json()
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 2, 0), (0, 2, 0)]
filas = client.get("/data/tea.RelacionAdos2Paciente", query_string={"limit": 500}).get_json()["rows"]
assert len(filas) == 2
assert next(f for f in filas if f["rap_id"] == "rap-1")["rap_probabilidad"] == 0.55
def test_invalid_model_rows_are_rejected(client):
"""Pins down: a model row with an out-of-range q, a non-positive odds ratio, an inverted confidence
interval, an unknown level or biomarker, an outcome code that doesn't match its level (`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},
{**_MODELO_ITEM, "rel_id": "rel-m2", "rel_version": "0.9.1", "rel_q": 1.5},
{**_MODELO_ITEM, "rel_id": "rel-m3", "rel_version": "0.9.2", "rel_or": 0},
{**_MODELO_ITEM, "rel_id": "rel-m4", "rel_version": "0.9.3", "rel_ic_inf": 9.0, "rel_ic_sup": 4.0},
{**_MODELO_ITEM, "rel_id": "rel-m5", "rel_version": "0.9.4", "rel_nivel": "itemm"},
{**_MODELO_ITEM, "rel_id": "rel-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "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()
resultado = body["results"][0]
assert resultado["created"] == 0 and resultado["rejected"] == len(casos)
campos = {e["field"] for e in resultado["errors"]}
assert {"rel_version", "rel_q", "rel_or", "rel_nivel", "rel_biomarcador", "<entre campos>"} <= campos
filas = client.get("/data/tea.RelacionAdos2", query_string={"limit": 500}).get_json()["rows"]
assert not [f for f in filas if f["rel_id"].startswith("rel-m")]
def test_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."""
buena = {**_PACIENTE_1, "rap_id": "rap-ok", "rap_rel_id": "rel-9"}
casos = [buena,
{**buena, "rap_id": "rap-m1", "rap_probabilidad": 1.2},
{**buena, "rap_id": "rap-m2", "rap_probabilidad_referencia": -0.1}]
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2Paciente")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert (resultado["created"], resultado["rejected"]) == (1, 2)
assert {e["field"] for e in resultado["errors"]} == {"rap_probabilidad", "rap_probabilidad_referencia"}
+8 -6
View File
@@ -80,14 +80,16 @@ def test_the_list_names_what_is_answered_on_request(client):
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA",
"CACU_RIESGO_BANDA"}
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
"CACU_DIAS_TOMA_COLPOSCOPIA", "CACU_DIAS_TOMA_BIOPSIA", "CACU_DIAS_RESULTADO_COLPOSCOPIA",
"CACU_DIAS_COLPOSCOPIA_BIOPSIA", "CACU_DIAS_BIOPSIA_DIAGNOSTICO",
"CACU_CONFIRMACION_CITOLOGIA", "CACU_RIESGO_BANDA"}
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its
by default). 2025-S2's samples resolved in 40 and 161 days, and the 120-day horizon keeps only the first. Fails if a duration stops being served or its
contract changes."""
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
(entry,) = bundle["entry"]
@@ -95,9 +97,9 @@ def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
(group,) = report["group"]
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
"initial-population": 4, "measure-observation": 2}
assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d"
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75]
"initial-population": 4, "measure-observation": 1}
assert group["measureScore"]["value"] == 40.0 and group["measureScore"]["unit"] == "d"
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [40.0, 40.0]
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
if os.environ.get("MEASURE_REPORT_OUT"):
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
+18 -14
View File
@@ -13,34 +13,38 @@ from webapi.recomputation import RecomputationQueue
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
def test_only_cacu_has_a_live_estimator():
"""CaMa and TEA have no registered model, so their cycles estimate nothing. Fails if a domain without a model
gets an estimator that would then fail resolving a version."""
def test_with_an_empty_registry_no_domain_has_a_live_estimator():
"""With no version in the registry, neither CaMa's nor TEA's cycle estimates anything. Fails if a domain without
a production model gets an estimator that would then fail resolving a version."""
assert estimators.live_estimators("cama") == {}
assert estimators.live_estimators("tea") == {}
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
Fails if `live_estimators` stops catching the registry's `LookupError`."""
Fails if `live_estimators` offers a scenario the registry does not list as in production."""
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
monkeypatch.setattr(registry, "in_production", lambda domain: [])
assert estimators.live_estimators("cacu") == {}
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
def test_every_scenario_in_production_scores_its_cohort(monkeypatch):
"""Each scenario the registry has in production gets an estimator on the cohort its `model.toml` names, so two
scenarios on one cohort give that cohort two estimators; a registered name with no scenario in `models` is
skipped. An estimator reports nothing until it has estimated. Fails if the scenarios go back to a fixed list,
if one cohort keeps a single estimator, or if an unknown registered name breaks the cycle."""
from models.dags.training import Scenario
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
monkeypatch.setattr(registry, "in_production", lambda domain: ["cancer_pim", "cin2_pim", "no_such_model"])
live = estimators.live_estimators("cacu")
assert list(live) == [URL]
estimator = live[URL]
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
cohort = Scenario.load("cacu", "cin2_pim").cohort
assert Scenario.load("cacu", "cancer_pim").cohort == cohort
assert list(live) == [cohort]
assert [e.scenario for e in live[cohort]] == ["cancer_pim", "cin2_pim"]
with pytest.raises(RuntimeError):
estimator.procedencia()
live[cohort][0].procedencia()
@pytest.mark.parametrize("proyecto", ["cacu"])
@@ -48,7 +52,7 @@ def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monk
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
as anything but `preliminary`."""
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: [EstimadorFijo()]})
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
assert result["estado"] == "ok", result
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
+126 -6
View File
@@ -19,9 +19,9 @@ from sqlalchemy import text
from sqlmodel import Session, select
from conftest import base_de
from core.cacu.models import BiopsiaCervical, CitologiaCervical
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, Paciente
from webapi.compositions import answer_composition, composition_definitions, composition_report
from webapi.metrics import Question, answer, measure_definitions, measure_report
from webapi.metrics import INTERVAL_HIGH, INTERVAL_LOW, Counts, Question, answer, measure_definitions, measure_report
from webapi.orchestration import run
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
@@ -47,6 +47,61 @@ def base(tmp_path, sin_supresion, manifest):
base.motor.dispose()
def _con_tratamiento(sesion: Session) -> None:
"""The fixture data and, for H-004, her colposcopy (August 20) and her treatment (August 28), after the
valuation visit of August 10: the timeline then holds a treatment to end an interval at."""
from staging.cacu import COLPOSCOPIA, FAMILIAR, insertar
insertar(sesion)
paciente = sesion.exec(select(Paciente).where(Paciente.pac_id_hospital == "H-004")).one()
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-004", nm_id_hospital=f"NM-9{n}", nm_fecha=fecha,
nm_cie_codigo=cie, nm_especialidad=especialidad)
for n, (fecha, cie, especialidad) in enumerate(
[(date(2025, 8, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 28), "D06.9", FAMILIAR)], start=1))
sesion.commit()
def _con_ruta(sesion: Session) -> None:
"""The fixture data and H-007, who goes the whole route in order: a cytology on July 5 with its result on July 15,
a valuation note on July 20, her colposcopy and the request of her biopsy on August 5, the biopsy report on
August 25 and a diagnosis after it on September 10."""
from staging.cacu import COLPOSCOPIA, ONCOLOGIA, SATISFACTORIO, insertar
insertar(sesion)
paciente = Paciente(pac_id_hospital="H-007", pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1))
sesion.add(paciente)
sesion.flush()
citologia = CitologiaCervical(pac_id=paciente.pac_id, pac_id_hospital="H-007", cit_fecha_toma=date(2025, 7, 5),
cit_calidad_especimen=SATISFACTORIO, cit_fecha_reporte=date(2025, 7, 15),
cit_celulas_escamosas="ASC-US", cit_vph_resultado="POSITIVO")
sesion.add(citologia)
sesion.flush()
sesion.add(BiopsiaCervical(pac_id=paciente.pac_id, pac_id_hospital="H-007", cit_id=citologia.cit_id,
bx_fecha_solicitud=date(2025, 8, 5), bx_fecha_reporte=date(2025, 8, 25), bx_cin_grado="CIN2"))
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-007", nm_id_hospital=f"NM-8{n}", nm_fecha=fecha,
nm_cie_codigo=cie, nm_especialidad=especialidad)
for n, (fecha, cie, especialidad) in enumerate(
[(date(2025, 7, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 5), "R87.6", COLPOSCOPIA),
(date(2025, 9, 10), "D06.9", ONCOLOGIA)], start=1))
sesion.commit()
@pytest.fixture
def base_con_ruta(tmp_path, sin_supresion, manifest):
base = base_de("cacu", tmp_path, datos=_con_ruta)
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
base.motor.dispose()
@pytest.fixture
def base_con_tratamiento(tmp_path, sin_supresion, manifest):
base = base_de("cacu", tmp_path, datos=_con_tratamiento)
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
base.motor.dispose()
@pytest.fixture
def kit():
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
@@ -254,8 +309,9 @@ def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base,
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's
categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer."""
inclusive period end, each population's count, the score with its interval, strata as a `stratifier`, and a
composition's categories as one more. Fails if a population, the score, a stratum or a category stops matching
the answer."""
period = base.dominio.dim_periodo_repository.get("2025-S1")
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
@@ -265,7 +321,7 @@ def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
"initial-population": 4, "denominator": 4, "numerator": 1}
assert group["measureScore"] == {"value": 0.25}
assert group["measureScore"]["value"] == 0.25
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
@@ -281,12 +337,31 @@ def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
def test_a_proportion_is_scored_with_its_wilson_interval():
"""Pins down: `Counts.score` carries the proportion and its 95 % Wilson interval as proportions, in the
`ic-bajo` and `ic-alto` extensions (1 of 4 is 0.25 within 0.0456 and 0.6994), and publishes no score when the
denominator is zero. Fails if an interval is dropped, comes out as a percentage, or a zero denominator is scored."""
score = Counts(1, 4).score
bounds = {e["url"]: e["valueDecimal"] for e in score["extension"]}
assert score["value"] == 0.25
assert bounds[INTERVAL_LOW] == pytest.approx(0.0456, abs=1e-4)
assert bounds[INTERVAL_HIGH] == pytest.approx(0.6994, abs=1e-4)
assert Counts(0, 0).score is None
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO])
# The oracle is the kit's output at the kit's 180-day horizon from the sample to the diagnosis; the project's is 120 (a
# parameter it set on purpose), so a sample the kit measures at 161 days is no longer measured. The comparison fails
# for that period until the oracle is regenerated from the kit with the project's horizon (strict: it then asks for
# this mark to go).
SIN_ORACULO_DE_120 = pytest.mark.xfail(strict=True, reason="the kit's oracle uses a 180-day horizon from the sample to the diagnosis; the project's is 120")
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, pytest.param(DIAS_TOMA_DIAGNOSTICO, marks=SIN_ORACULO_DE_120)])
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
@@ -454,6 +529,51 @@ def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_y
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
DIAS_TOMA_TRATAMIENTO = "cacu/CACU_DIAS_TOMA_TRATAMIENTO"
DIAS_DIAGNOSTICO_TRATAMIENTO = "cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (1, 1, 58.0, 0)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
def test_the_times_to_treatment_are_counted_from_their_start_to_the_first_treatment(base_con_tratamiento, manifest, url, expected):
"""Pins down the two times to treatment on the fixture with H-004's colposcopy and treatment, 2025-S2 cut at the
end of the year. From the sample (a 180-day horizon): H-004's July sample reaches her treatment of August 28 in 58
days; the others of the semester (August 12, September 1 and October 2) have no treatment and their horizon is
after the cut, so they are pending and not in the initial population. From the diagnosis (60 days): only that
sample has one in the period, and its diagnosis of August 10 reaches the treatment in 18 days. Fails if the end
event, the start (sample or diagnosis), the horizon
rule or the split between not measured yet and without event changes."""
from webapi.durations import answer_duration, duration_definitions
definition = duration_definitions(manifest)[url]
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)),
**repositories(base_con_tratamiento))
assert (result.initial, result.n, result.median, result.excluded) == expected
RUTA = { # url -> (población inicial, n, mediana, excluidas) en 2025-S2, con corte a fin de año
"cacu/CACU_DIAS_TOMA_COLPOSCOPIA": (5, 1, 31.0, 4),
"cacu/CACU_DIAS_TOMA_BIOPSIA": (5, 2, 41.0, 3),
"cacu/CACU_DIAS_RESULTADO_COLPOSCOPIA": (3, 1, 21.0, 2),
"cacu/CACU_DIAS_COLPOSCOPIA_BIOPSIA": (1, 1, 20.0, 0),
"cacu/CACU_DIAS_BIOPSIA_DIAGNOSTICO": (2, 2, 12.5, 0),
}
@pytest.mark.parametrize("url", sorted(RUTA))
def test_the_times_along_the_screening_route_count_between_consecutive_events(base_con_ruta, manifest, url):
"""Pins down the five times of the screening route on the fixture with H-007, 2025-S2 cut at the end of the year.
From the sample: H-007's colposcopy (31 days) and the biopsy reports of H-004 (31) and H-007 (51); the other
samples have none and their 60-day horizon has passed, so they are in the initial population and not measured.
Between events: the colposcopy from the cytology result (21 days), the biopsy report from the colposcopy (20) and
the diagnosis from the biopsy report (9 and 16 days). Fails if an event, its start, its horizon or the population
each measure counts over changes."""
from webapi.durations import answer_duration, duration_definitions
definition = duration_definitions(manifest)[url]
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)), **repositories(base_con_ruta))
assert (result.initial, result.n, result.median, result.excluded) == RUTA[url]
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
+294
View File
@@ -0,0 +1,294 @@
"""What this module covers: `GET /cama/modelo/curvas` and `GET /cama/modelo/desarrollo` (`webapi.model_analysis`): they serve the production version's
population record with the version it comes from, and answers 404 while there is no version in production or the
version has no such record.
Fixtures: `client`, the app with the registry's `resolve` and `artifact` replaced by what the test says a production
version holds, so no MLflow is needed; the CaMa survival record is a small stand-in for what a run publishes.
"""
import json
from types import SimpleNamespace
import pytest
RECORD = {"horizons_months": [6, 12, 18], "points": {"COMB": {"S": [0.9, 0.8, 0.7], "low": [0.8, 0.7, 0.6], "high": [0.95, 0.9, 0.8]}}}
@pytest.fixture
def client(monkeypatch):
from flask import Flask
from models.io import registry as registry_module
from webapi.model_analysis import model_analysis_blueprint
app = Flask(__name__)
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
monkeypatch.setenv("DEV_REVISION", "pruebas")
holder = SimpleNamespace(files={"analisis/curvas.json": json.dumps(RECORD).encode()}, production="3")
def resolve(domain, scenario, version=None):
if holder.production is None:
raise LookupError("no hay una versión en producción")
return SimpleNamespace(version=holder.production, run_id="run-1")
def artifact(domain, scenario, version, path):
if path not in holder.files:
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
return path.rsplit("/", 1)[-1], holder.files[path]
monkeypatch.setattr(registry_module.registry, "resolve", resolve)
monkeypatch.setattr(registry_module.registry, "artifact", artifact)
with app.test_client() as test_client:
test_client.holder = holder
yield test_client
def test_it_serves_the_production_versions_record_and_names_the_version(client):
"""Pins down: the answer carries the record unchanged, the model and version it comes from and the simulated-data
flag. Fails if the record is altered on the way or the answer stops saying which version it is."""
body = client.get("/cama/modelo/curvas").get_json()
assert body["curvas"] == RECORD and body["simulado"] is True
assert body["modelo"] == {"nombre": "cama-survival", "version": "3", "mlflow_run_id": "run-1"}
def test_without_a_version_in_production_or_a_record_it_is_a_404(client):
"""Pins down: no production version, and a version whose run published no `analisis/curvas.json`, are both a 404
with the reason, never an empty record. Fails if either becomes a 200 or a 500."""
client.holder.files.clear()
missing_record = client.get("/cama/modelo/curvas")
client.holder.production = None
no_version = client.get("/cama/modelo/curvas")
assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"]
assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"]
def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none(client):
"""Pins down: `GET /cama/modelo/desarrollo` returns `analisis/desarrollo.json` with the version it comes from, and a
version trained before that record existed is a 404, not an empty page. Fails if the route reads another file or
answers 200 without a record."""
record = {"tablas": {"or_lr_balanceada": [{"variable": "Grado"}]}, "figuras": {}}
client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode()
found = client.get("/cama/modelo/desarrollo")
del client.holder.files["analisis/desarrollo.json"]
missing = client.get("/cama/modelo/desarrollo")
assert found.status_code == 200 and found.get_json()["desarrollo"] == record
assert found.get_json()["modelo"]["version"] == "3"
assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"]
SUMMARY = {"columnas": ["escenario", "riesgo_definitorios", "incluye_factor_riesgo"],
"filas": [{"escenario": "< 45 años", "riesgo_definitorios": "Grado=G3 (robusto, 97%)", "incluye_factor_riesgo": True},
{"escenario": "Estadio IV", "riesgo_definitorios": "", "incluye_factor_riesgo": False}]}
@pytest.fixture
def live_client(client, monkeypatch):
"""`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, and the version's summary
of two scenarios (one with a risk factor, one without) in its development record, so the routes run without MLflow or a
cohort build; `live.curves` answers from the stand-in or raises what the test sets; the masks put patients 1-100 in
`< 45 años`, 1-3 in a tiny scenario with no summary row, and nobody in `Estadio IV`."""
import numpy as np
import pandas as pd
from models.cama.survival import live
from webapi import model_analysis
holder = client.holder
holder.calls, holder.error = 0, None
labelled = pd.DataFrame({"pac_id": range(1, 201), "event": [True] * 40 + [False] * 160})
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, 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()
return client
def test_the_menu_offers_the_scenarios_with_a_summary_row_and_enough_patients(live_client):
"""Pins down: `GET /cama/modelo/escenarios` offers only the scenarios that have a row in the version's summary and enough patients
to draw (not the one with no row, not the one with nobody), with their patients, in the pipeline's order, and names the one a
patient belongs to as the default. Fails if a scenario with nothing to say reaches the menu, or the default ignores the patient."""
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
def test_a_scenarios_figure_comes_with_its_risk_factors_and_the_answer_is_kept(live_client):
"""Pins down: `POST /cama/modelo/curvas/consulta` returns the figure of the named scenario with its summary row (the risk-factor
label) and the version that scored it, and the same scenario a second time is answered without computing again; a scenario with
no row has no factors. Fails if curve and label can come from different scenarios, or every request recomputes."""
first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}).get_json()
again = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}).get_json()
other = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Diminuto"}).get_json()
assert first["curvas"]["escenario"] == "< 45 años" and first["factores"]["riesgo_definitorios"] == "Grado=G3 (robusto, 97%)"
assert again == first and live_client.holder.calls == 2 and other["factores"] is None
assert first["modelo"]["version"] == "3"
def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client):
"""Pins down: an unknown scenario or one too small is a 422 with the message, not a 500 or an empty record. Fails if the
reader sees a server error instead of why the scenario says nothing."""
live_client.holder.error = "El escenario tiene 3 pacientes"
answer = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Estadio IV"})
assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"]
@pytest.fixture
def recurrence_client(monkeypatch):
"""The recurrence route on a bare app, with the registry's production version, its recurrence record, its summary and the
labelled members replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor."""
import pandas as pd
from flask import Flask
from models.io import registry as registry_module
from webapi import model_analysis
figure = lambda cohorte, name, cond, n: {"cohorte": cohorte, "escenario": name, "condiciones": cond, "n": n}
record = {"horizons_months": [12, 36, 60], "escenarios": [
figure("metabric", "< 45 años", {"Edad": ["<45"]}, 100), figure("metabric", "RE− · grado 3", {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, 300),
figure("metabric", "Ganglios 4+", {"Ganglios_positivos": ["4+"]}, 80), figure("scanb", "Grado 3", {"Grado_histologico": ["3"]}, 900),
figure("scanb", "Sin fila", {"Edad": ["<45"]}, 50)]}
summary = {"tablas": {"escenarios_resumen": {"filas": [
{"cohorte": "metabric", "escenario": "< 45 años", "horizonte_meses": 60}, {"cohorte": "metabric", "escenario": "RE− · grado 3", "horizonte_meses": 60},
{"cohorte": "metabric", "escenario": "Ganglios 4+", "horizonte_meses": 60}, {"cohorte": "scanb", "escenario": "Grado 3", "horizonte_meses": 60}]}}}
labelled = pd.DataFrame({"pac_id": [7], "age_years": [40.0], "size_mm": [None], "grade": ["G3"], "er": ["NEGATIVO"], "pr": ["NEGATIVO"], "her2": ["H2"]})
holder = SimpleNamespace(production="2")
def resolve(domain, scenario, version=None):
if holder.production is None:
raise LookupError("no hay una versión en producción")
return SimpleNamespace(version=holder.production, run_id="run-2")
files = {"analisis/recurrencia.json": json.dumps(record).encode(), "analisis/recurrencia_desarrollo.json": json.dumps(summary).encode()}
monkeypatch.setattr(registry_module.registry, "resolve", resolve)
monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: (p, files[p]))
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3"))
app = Flask(__name__)
app.register_blueprint(model_analysis.recurrence_blueprint(), url_prefix="/cama")
with app.test_client() as client:
client.holder = holder
yield client
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), 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 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):
"""Pins down: no recurrence version in production is a 404 with the reason. Fails if it becomes a 200 with nothing or a 500."""
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"]
+7 -5
View File
@@ -66,16 +66,18 @@ def test_volver_a_correr_no_agrega_reportes(bases):
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
def test_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases):
def test_arma_cada_cohorte_de_dbt_una_vez(bases):
"""Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores
as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from
anywhere else than dbt, or a build's count and members disagree."""
as many members as it counts (CaCu's, CaMa's total and survival cohorts); a project without dbt cohorts (TEA) has no
cohort step. Fails if a cohort comes from anywhere else than dbt, or a build's count and members disagree."""
proyecto, ctx, motor, _, pasos = bases
if proyecto != "cacu":
urls = set(cohort_urls(proyecto, ctx.dbt_manifest))
if not urls:
assert "cohorts" not in [p.name for p in pasos]
return
armados = [p.summary for p in pasos if p.name == "cohorts"][0]
assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados
assert set(armados) == urls
assert ({"cacu/cohorte_vigilancia"} if proyecto == "cacu" else {"cama/cohorte_total"}) <= set(armados)
with motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
for armado_id, _ in armados.values():
+4 -4
View File
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
# TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto]
# CaCu: three strata and its fourteen measures; CaMa: the BI-RADS stratum of the histopathological result and its
# eleven measures; TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 17, "cama": 12, "tea": 11}[base.proyecto]
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
assert base.dominio.cat_measure_repository.count() == {"cacu": 14, "cama": 11, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
+18 -4
View File
@@ -56,7 +56,7 @@ def cuenta(base, sql):
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
estimador = EstimadorFijo()
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: [estimador]})["estimate"][URL][0]
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
assert nuevo and miembros > 0
@@ -68,16 +68,30 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
(primero, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
assert cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0] == (primero, False)
assert cacu.run("estimate")["estimate"] == {}
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_dos_modelos_de_una_cohorte_dejan_un_lote_cada_uno(cacu):
"""Two estimators on one cohort (two scenarios in production on the same build) write one batch each. Fails if
`estimate` keeps only one estimator per cohort or folds two models into one batch."""
class OtroModelo(EstimadorFijo):
def procedencia(self):
return Procedencia(modelo_nombre="cacu-otro")
lotes = cacu.run("estimate", estimators={URL: [EstimadorFijo(), OtroModelo()]})["estimate"][URL]
assert [nuevo for _, nuevo in lotes] == [True, True] and lotes[0][0] != lotes[1][0]
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 2
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
(lote_id, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
+8 -6
View File
@@ -15,7 +15,9 @@ from pathlib import Path
import pytest
CORTE = date(2025, 12, 31)
INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"}
# What dbt adds to the kit's timeline: the procedures it infers and the patient's birth and death, from `persona`.
ADDED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente", "orden_biopsia",
"nacimiento", "defuncion"}
KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json"
@@ -38,18 +40,18 @@ def kit_rows():
def as_kit(rows) -> list[dict]:
"""Rows as the snapshot keeps them: text values, no load time, without the inferred procedures."""
"""Rows as the snapshot keeps them: text values, no load time, without the rows dbt adds."""
return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"}
for row in rows if row["tipo"] not in INFERRED]
for row in rows if row["tipo"] not in ADDED]
def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows):
"""Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its
order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or
the view stops giving one of the kit's rows."""
order and with a date as `fecha`, plus the inferred procedures and the patient's birth and death. Fails if the
orchestration binds another query, or the view stops giving one of the kit's rows."""
rows = loaded.ctx.repos.silver.timeline.read(until=CORTE)
assert as_kit(rows) == kit_rows
assert {row["tipo"] for row in rows} & INFERRED
assert {row["tipo"] for row in rows} & ADDED
assert all(isinstance(row["fecha"], date) for row in rows)
+63
View File
@@ -0,0 +1,63 @@
"""What this module covers: how silver reads the wording of a breast pathology report's text layer, as the hospital's
reports (and dev-data's synthetic ones) print it: the grade after a histological type that says "no especial", the
HER2 caption with its method in parentheses, and Ki-67 under its long caption. Each case is one report fragment.
Fixtures: none; the extractor is `silver.cama.DEL_REPORTE_DE_PATOLOGIA`, fed text through `lineas_de_texto`.
"""
import pytest
from webapi.orchestration.silver.cama import DEL_REPORTE_DE_PATOLOGIA
from webapi.orchestration.silver.extracted import lineas_de_texto
DIAGNOSTICO = (
"BIOPSIA: CARCINOMA DUCTAL INFILTRANTE (CARCINOMA INVASOR DE TIPO NO ESPECIAL) (8500/3), GRADO HISTOLÓGICO {g} "
"DE NOTTINGHAM (PUNTAJE 6/9). INVASIÓN LINFOVASCULAR: NO IDENTIFICADA."
)
def _leer(texto: str) -> dict:
extractor = DEL_REPORTE_DE_PATOLOGIA._extraer # the cached reader of text, as `leer` calls it
return extractor(texto)
@pytest.mark.parametrize("grado, codigo", [(1, "G1"), (2, "G2"), (3, "G3")])
def test_the_grade_after_a_type_that_says_no_especial_is_read(grado, codigo):
"""Pins down: "TIPO NO ESPECIAL" names a histological type, it does not deny what follows, so the Nottingham grade
later in the same line is still read. Fails if "no especial" stops being a pseudo-trigger of the negation context."""
assert _leer(DIAGNOSTICO.format(g=grado))["biopsia.grado_nottingham"][0] == codigo
@pytest.mark.parametrize("texto, codigo", [
("HER2/neu (IHQ): NEGATIVO (0)", "H0"), ("HER2/neu (IHQ): NEGATIVO (1+)", "H1"),
("HER2/neu (IHQ): EQUÍVOCO (2+)", "H2"), ("HER2/neu (IHQ): POSITIVO (3+)", "H3"),
])
def test_her2_is_read_with_its_method_in_the_caption(texto, codigo):
"""Pins down: a caption "HER2/neu (IHQ):" gives the score that follows it, not the "(IHQ):" of its own method.
Fails if the longer captions leave the catalog's `etiquetas_fuente` for HER2."""
assert _leer(texto)["biopsia.her2"][0] == codigo
def test_ki67_is_read_under_its_long_caption_and_not_from_the_name():
"""Pins down: "Índice de proliferación Ki-67: 25 %" gives 25, not the 67 of the marker's name. Fails if the long
caption leaves the catalog's `etiquetas_fuente` for Ki-67."""
assert float(_leer("Índice de proliferación Ki-67: 25 %")["biopsia.ki67_pct"][0]) == 25.0
@pytest.mark.parametrize("tipo, codigo", [("CARCINOMA MUCINOSO", "8480/3"), ("CARCINOMA TUBULAR", "8211/3"),
("CARCINOMA DUCTAL Y LOBULILLAR INFILTRANTE (MIXTO)", "8522/3")])
def test_the_rarer_invasive_types_are_read_as_their_code(tipo, codigo):
"""Pins down: a mucinous, tubular or mixed ductal and lobular carcinoma is read as its ICD-O-3 code rather than left
unresolved or taken as ductal or lobular. Fails if their names leave the catalog's aliases."""
assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == codigo
@pytest.mark.parametrize("texto", [
"GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO DE LA LESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.",
"GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO DE LA\nLESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.",
"GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO\nDE LA LESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.",
])
def test_the_lesion_size_is_read_even_when_the_page_wraps_its_caption(texto):
"""Pins down: "TAMAÑO DE LA LESIÓN: 25 MM" gives 25 whether it is on one line or the page wraps it between words,
because the extractor also sees each pair of adjacent lines joined. Fails if the joined lines stop being offered."""
assert float(_leer(texto)["biopsia.tamano_tumor_mm"][0]) == 25.0
+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
+3 -1
View File
@@ -108,7 +108,9 @@ def test_indicators_recompute_from_imported_rows(client):
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
"CACU_DIAS_TOMA_COLPOSCOPIA", "CACU_DIAS_TOMA_BIOPSIA", "CACU_DIAS_RESULTADO_COLPOSCOPIA",
"CACU_DIAS_COLPOSCOPIA_BIOPSIA", "CACU_DIAS_BIOPSIA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
+14
View File
@@ -100,3 +100,17 @@ def test_an_unknown_batch_is_404(client):
"""Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed
nothing."""
assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404
def test_a_decision_that_collides_with_another_is_409(client, monkeypatch):
"""Pins down: two decisions of one batch at the same moment (a double click reaching both workers) give the
second a 409 instead of a server error. Fails if the unique version of an evaluation surfaces as a 500."""
from persistance import cacu
from sqlalchemy.exc import IntegrityError
def collide(*args, **kwargs):
raise IntegrityError("INSERT", {}, Exception("UNIQUE constraint failed"))
monkeypatch.setattr(cacu.cohort_repository, "change_state", collide)
assert client.post("/cacu/riesgos/lotes/1/confirmar", json={"reason": "revisado"}).status_code == 409
+12
View File
@@ -43,6 +43,18 @@ def test_paciente_schema_coerces_date_from_datetime_object():
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
def test_cacu_paciente_keeps_her_date_of_death():
"""Pins down: a CaCu patient's `pac_fecha_defuncion` is imported (the survival scenario's outcome), and an alive
patient has none. Fails if the schema drops the column again: every CaCu death would be lost on import and the
survival model would train with no deaths."""
from datetime import date
dead = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="1960-03-01", pac_fecha_defuncion="2025-07-09")
alive = PacienteImportSchema(pac_id_hospital="H-2", pac_fecha_nacimiento="1960-03-01")
assert dead.pac_fecha_defuncion == date(2025, 7, 9) and alive.pac_fecha_defuncion is None
def test_tea_pacientes_schema_is_fully_optional():
schema = PacientesImportSchema()
assert schema.pac_id_hospital is None
+124 -4
View File
@@ -8,9 +8,10 @@ de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostr
import pytest
from conftest import cliente_de
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "horizontes_disponibles", "reglas",
"paginacion", "items"}
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
"dias_toma_diagnostico", "prioridad"} # fmt: skip
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
@pytest.fixture(scope="module")
@@ -41,12 +42,13 @@ def test_el_pedido_se_respeta(client):
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA", "orden": "reciente", "horizonte": 5.0}
@pytest.mark.parametrize(
"query",
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500",
"?orden=edad", "?horizonte=cinco"],
)
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
response = client.get(f"/cacu/seguimiento{query}")
@@ -68,3 +70,121 @@ def test_in_dev_esta_obsoleta():
with pytest.warns(DeprecationWarning):
in_dev()
def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(client):
"""Fija: con un lote de CIN2+ confirmado, cada fila trae sus probabilidades por horizonte y `orden=lieag` pone
primero a la de mayor probabilidad al `horizonte` pedido, y al final a quien el modelo no evalúa; un horizonte que
los modelos no dan es 400. Falla si la lista deja de leer los lotes vigentes, o si ordena solo dentro de la página."""
from datetime import date, datetime, timezone
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
from persistance import cacu
from persistance.db import get_cacu_session
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
baja, alta = int(filas[0]["pac_id"]), int(filas[1]["pac_id"])
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-orden",
marco_sha="m", n_miembros=2, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
session.add(build)
session.flush()
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
for p in (baja, alta)])
session.commit()
armado = build.armado_id
indice = date(2025, 3, 1)
lote, _ = cacu.cohort_repository.save_batch(
armado, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "9", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2", [(baja, indice, 1.0, 0.02, 0.01, 0.04), (baja, indice, 5.0, 0.05, 0.03, 0.08),
(alta, indice, 1.0, 0.10, 0.07, 0.14), (alta, indice, 5.0, 0.30, 0.22, 0.40)])
cacu.cohort_repository.change_state(lote, "final", "revisado")
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=lieag&horizonte=1").get_json()
assert cuerpo["horizontes_disponibles"] == [1.0, 5.0] and cuerpo["filtros"]["orden"] == "lieag"
assert [i["pac_id"] for i in cuerpo["items"][:2]] == [str(alta), str(baja)]
assert cuerpo["items"][0]["probabilidades"]["lieag"][1] == {"horizonte_anios": 5.0, "probabilidad": 0.30,
"ic_bajo": 0.22, "ic_alto": 0.40}
assert all(i["probabilidades"] is None for i in cuerpo["items"][2:])
assert client.get("/cacu/seguimiento?corte=2025-12-31&orden=lieag&horizonte=3").status_code == 400
def test_un_caso_tiene_su_estatus_y_su_probabilidad_de_supervivencia(client):
"""Fija: una paciente con biopsia de carcinoma es CASO, gane lo que gane lo demás, y su probabilidad de supervivencia
es 1 − la de morir del modelo de supervivencia, con el IC invertido, y 1 a los 0 años; la lista se ordena por ella.
Falla si CASO
deja de ganar o si la supervivencia se muestra como la probabilidad de morir."""
from datetime import date, datetime, timezone
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
from persistance import cacu
from persistance.db import get_cacu_session
from webapi.follow_up.status import ESTATUS
assert ESTATUS[0] == "CASO"
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
paciente = int(filas[2]["pac_id"])
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_total", version="0.4.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-caso",
marco_sha="m", n_miembros=1, armado_en=datetime(2026, 1, 2, tzinfo=timezone.utc))
session.add(build)
session.flush()
session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=paciente, fecha_indice=date(2025, 3, 1),
indice_fuente_tabla="biopsiacervical", indice_fuente_id=str(paciente)))
session.commit()
armado = build.armado_id
lote, _ = cacu.cohort_repository.save_batch(
armado, {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
"muerte", [(paciente, date(2025, 3, 1), 5.0, 0.30, 0.20, 0.45)])
cacu.cohort_repository.change_state(lote, "final", "revisado")
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=supervivencia&horizonte=5"
).get_json()
primera = cuerpo["items"][0]
assert primera["pac_id"] == str(paciente)
assert primera["probabilidades"]["supervivencia"] == [
{"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0},
{"horizonte_anios": 5.0, "probabilidad": 0.7, "ic_bajo": 0.55, "ic_alto": 0.8}]
def test_una_biopsia_de_un_grado_de_caso_hace_caso_a_la_paciente(client, monkeypatch):
"""Fija: quien tiene una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` al corte es CASO, gane lo
que gane lo demás, y nadie sin una lo es; el filtro `estatus=CASO` las da. La base de demostración no tiene
carcinomas, así que la regla se toma aquí como CIN2. Falla si la precedencia deja de poner CASO primero o el
estatus deja de leer el grado de la biopsia de su regla."""
from sqlalchemy import select
from persistance.db import get_cacu_session
from webapi.follow_up import listing
from webapi.follow_up.silver import biopsias
original = listing.valor_de
monkeypatch.setattr(listing, "valor_de", lambda sesion, clave, **kw:
["CIN2"] if clave == "cacu.seguimiento.caso.grados" else original(sesion, clave, **kw))
b = biopsias()
with get_cacu_session() as session:
con_cin2 = {r.pac_id for r in session.execute(select(b.c.pac_id).where(b.c.grado == "CIN2"))}
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
casos = {int(i["pac_id"]) for i in filas if i["estatus"]["codigo"] == "CASO"}
assert casos and casos == con_cin2 & {int(i["pac_id"]) for i in filas}
solo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&estatus=CASO").get_json()["items"]
assert {int(i["pac_id"]) for i in solo} == casos
def test_un_caso_es_un_carcinoma_invasor_o_in_situ():
"""Fija: la regla de CASO toma CIS y carcinoma, como el índice del escenario de supervivencia, para que la tabla y
la supervivencia hablen de las mismas pacientes. Falla si la regla deja fuera el in situ."""
import tomllib
from pathlib import Path
import webapi.orchestration.reference as referencia
parametros = tomllib.loads((Path(referencia.__file__).parent / "parametros.toml").read_text(encoding="utf-8"))
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
+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
+19 -14
View File
@@ -4,8 +4,8 @@
Fixtures: `loaded`, a TEA database (`base_de`) loaded up to the event models, with one patient and one analysed EEG
`e-1`: valid, triage `completo`; three checks (95 % clean windows against a low limit of 60, the triage level as text,
and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0 and p5/median/p95 5/6/7, and its N2
spindles' value 2.5 with z -0.4 at Fz.
and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0, p5/median/p95 5/6/7 and the registered
label of the baseline it was compared against, and its N2 spindles' value 2.5 with z -0.4 at Fz.
"""
import os
from datetime import date
@@ -34,7 +34,7 @@ def _rows(sesion):
])
sesion.add_all([
EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=1.2, met_fuera=0,
met_p5=5.0, met_mediana=6.0, met_p95=7.0),
met_p5=5.0, met_mediana=6.0, met_p95=7.0, met_modelo="tea-eeg-posterior-rhythm/3"),
EegMetrica(met_id="n2", met_eeg_id="e-1", met_codigo="HUSOS_SUENO_N2", met_valor=2.5),
EegMetricaElectrodo(mel_id="n2-fz", mel_met_id="n2", mel_electrodo="Fz", mel_valor=1.4, mel_z=-0.4),
])
@@ -92,13 +92,16 @@ def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded):
def test_a_metric_carries_its_deviation_from_the_baseline(loaded):
"""Pins down: a metric's z, -1/0/+1 and the baseline's p5/median/p95 at the age are results of the recording.
"""Pins down: a metric's z, -1/0/+1, the baseline's p5/median/p95 at the age and the baseline's registered label
are results of the recording.
Fails if the silver mapping or the catalog drops one of the deviation's results.
Fails if the silver mapping or the catalog drops one of the deviation's results or the label (the load skips a
result the catalog doesn't have).
"""
toma = _observations(loaded, "toma")
assert [toma[None, f"eeg.ritmo_posterior{s}"] for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95")] == \
[6.8, 1.2, 0, 5.0, 6.0, 7.0]
assert [toma[None, f"eeg.ritmo_posterior{s}"]
for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95", "_modelo")] == \
[6.8, 1.2, 0, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3"]
def test_the_quality_view_lists_each_check_with_its_label(loaded):
@@ -126,18 +129,20 @@ def test_the_quality_view_lists_each_check_with_its_label(loaded):
def test_a_metric_is_scored_by_the_analysis_s_deviation(loaded):
"""Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state and the baseline's
p5/median/p95 as the reference; a metric without a z (no baseline in production) can't be evaluated. And the
electrodes view carries each electrode's z next to its value.
"""Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state, the baseline's
p5/median/p95 as the reference and the baseline's registered label; a metric without a z (no baseline in
production) can't be evaluated. And the electrodes view carries each electrode's z next to its value.
Fails if dbt goes back to scoring metrics against fixed ranges of its own, or drops the electrode z.
Fails if dbt goes back to scoring metrics against fixed ranges of its own, drops the baseline label, or drops the
electrode z.
"""
with loaded.motor.connect() as connection:
metrics = {r.metrica: r for r in connection.execute(text(
"select metrica, valor, ref_min, ref_mediana, ref_max, valor_z, estado from tea_paciente_eeg_metricas"))}
"select metrica, valor, ref_min, ref_mediana, ref_max, modelo, valor_z, estado "
"from tea_paciente_eeg_metricas"))}
(electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all()
rhythm = metrics["ritmo_posterior"]
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.valor_z, rhythm.estado) == \
(6.8, 5.0, 6.0, 7.0, 1.2, "normal")
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.modelo, rhythm.valor_z,
rhythm.estado) == (6.8, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3", 1.2, "normal")
assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
assert tuple(electrode) == (1.4, -0.4)
+175
View File
@@ -0,0 +1,175 @@
"""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 (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`. 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")
def _rows(sesion):
from core.tea.models import (
Ados2,
Eeg,
Mchat,
Pacientes,
RelacionAdos2,
RelacionAdos2Paciente,
)
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Pacientes(pac_id=2, pac_id_hospital="H-2", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add_all([
Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12),
Mchat(mch_id="m-2", mch_pac_id=2, mch_fecha=date(2025, 1, 10), mch_puntaje=8),
])
# 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=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),
Eeg(eeg_id="e-3", eeg_pac_id=2, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1),
])
sesion.add_all([
RelacionAdos2(rel_id="rel-10", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42,
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
rel_resultado="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="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="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="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="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="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([
# The stale version's probability: the latest version wins.
RelacionAdos2Paciente(rap_id="rap-0", rap_rel_id="rel-10", rap_eeg_id="e-1", rap_valor_z=-2.5,
rap_probabilidad=0.6, rap_probabilidad_referencia=0.25),
RelacionAdos2Paciente(rap_id="rap-1", rap_rel_id="rel-20", rap_eeg_id="e-1", rap_valor_z=-2.5,
rap_probabilidad=0.81, rap_probabilidad_referencia=0.22),
RelacionAdos2Paciente(rap_id="rap-2", rap_rel_id="rel-21", rap_eeg_id="e-1", rap_valor_z=-2.5,
rap_probabilidad=0.35, rap_probabilidad_referencia=0.4),
RelacionAdos2Paciente(rap_id="rap-3", rap_rel_id="rel-22", rap_eeg_id="e-1", rap_valor_z=1.1,
rap_probabilidad=0.5, rap_probabilidad_referencia=0.45),
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),
])
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models, with the view under test created."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_relacion"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
def _filas(loaded):
with loaded.motor.connect() as connection:
return connection.execute(text(
"select pac_id, procedimiento_id, version, validado, nivel, n_cohorte, biomarcador, zona, tipo,"
" resultado, evento, odds_ratio, ic_inf, ic_sup, q, valor_z, probabilidad,"
" probabilidad_referencia, observado from tea_paciente_relacion_ados2")).all()
def test_the_view_keeps_the_latest_version_of_the_study_eeg_only(loaded):
"""Pins down: one row per association row of the greatest model version that scored the study's EEG (1.1.0).
The stale version's probability (1.0.0), the probability for the later EEG (e-2), the model rows of 1.1.0
without a probability for the study's EEG (rel-23) or scored only on the other EEG don't appear, and a child
without model rows (patient 2) doesn't either. Fails if the view stops filtering by the study's EEG or by the
latest version."""
filas = _filas(loaded)
claves = sorted((f.version, f.resultado, f.tipo) for f in filas)
assert claves == [("1.1.0", "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}
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 == "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)
assert (item.valor_z, item.probabilidad, item.probabilidad_referencia) == (-2.5, 0.81, 0.22)
def test_observado_is_the_outcome_score_of_the_first_ados2(loaded):
"""Pins down: `observado` is read from the first ADOS-2 by date (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 == {"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()}
+129
View File
@@ -0,0 +1,129 @@
"""What this module covers: the scenarios governance can train and the background training jobs (`webapi.training_jobs`
and their routes in `webapi.blueprints.governance`): the catalog, a job's states (running, completed, failed, trained but
not promoted, interrupted), and the refusal to start a second job of a scenario that is running.
Fixtures: `app_client`, the governance blueprint on a bare Flask app with `INDICADORES_DIR` in a temporary folder and the
job's command replaced by a Python one-liner the test chooses, so no model is trained. `esperar` waits for a job to leave
`en_curso`.
"""
import sys
import time
import pytest
from flask import Flask
from webapi import training_jobs
from webapi.blueprints.governance import governance_bp
@pytest.fixture
def app_client(tmp_path, monkeypatch):
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
monkeypatch.setenv("DBT_MANIFEST", str(tmp_path / "manifest.json"))
app = Flask(__name__)
app.register_blueprint(governance_bp, url_prefix="/governance")
with app.test_client() as client:
yield client
def _command_that(code: str):
return lambda domain, scenario: [sys.executable, "-c", code]
def esperar(client, job_id, timeout=20):
deadline = time.time() + timeout
while time.time() < deadline:
job = client.get(f"/governance/training-jobs/{job_id}").get_json()["job"]
if job["estado"] != "en_curso":
return job
time.sleep(0.1)
raise AssertionError("the job did not finish")
def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings():
"""Pins down: every scenario with its own `model.toml` and a cohort is listed (CaCu, CaMa), TEA's EEG is listed as
trained on its reference, and the SEER pipeline's settings file is not a scenario. Fails if a scenario stops being
discoverable or a settings file starts showing as one."""
entries = {(s["domain"], s["scenario"]): s for s in training_jobs.catalog()}
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"] == "cohorte" # the patients loaded from METABRIC and SCAN-B
@pytest.mark.parametrize("code,estado", [
("print('trained: version 4')", "completado"),
("import sys; print('boom', file=sys.stderr); sys.exit(1)", "fallido"),
("import sys; print('version 4 not promoted, missing MLD-01', file=sys.stderr); sys.exit(1)", "entrenado_sin_promover"),
])
def test_a_job_ends_as_completed_failed_or_trained_without_promotion(app_client, monkeypatch, code, estado):
"""Pins down: the job's state comes from its exit code and its error output, and carries both outputs. Fails if a
failure is shown as done, or a version that only lacks its reports is shown as failed."""
monkeypatch.setattr(training_jobs, "_command", _command_that(code))
started = app_client.post("/governance/model-versions/cama/survival/train-jobs")
job = esperar(app_client, started.get_json()["job"]["id"])
assert started.status_code == 202 and job["estado"] == estado
assert ("trained" in job["salida"]) or ("boom" in job["error"]) or ("not promoted" in job["error"])
def test_a_second_job_of_a_running_scenario_is_refused_with_the_running_one(app_client, monkeypatch):
"""Pins down: while a scenario's job runs, starting another answers 409 with that job, and another scenario still
starts. Fails if two trainings of one model can run at once, which would register the same version twice."""
monkeypatch.setattr(training_jobs, "_command", _command_that("import time; time.sleep(3)"))
first = app_client.post("/governance/model-versions/cama/survival/train-jobs")
again = app_client.post("/governance/model-versions/cama/survival/train-jobs")
other = app_client.post("/governance/model-versions/cacu/cin2_logistic/train-jobs")
assert first.status_code == 202 and again.status_code == 409
assert again.get_json()["job"]["id"] == first.get_json()["job"]["id"]
assert other.status_code == 202
def test_a_job_whose_process_is_gone_without_an_exit_code_is_interrupted(app_client, tmp_path):
"""Pins down: a job file with no exit file and a dead process reads `interrumpido`, not `en_curso` forever. Fails if
a killed worker leaves its job running in the list."""
folder = tmp_path / "entrenamientos" / "20260101T000000-aaaaaa"
folder.mkdir(parents=True)
(folder / "job.json").write_text('{"id": "20260101T000000-aaaaaa", "domain": "cama", "scenario": "survival", '
'"pid": 2147483646, "iniciado": "2026-01-01T00:00:00+00:00"}')
assert app_client.get("/governance/training-jobs/20260101T000000-aaaaaa").get_json()["job"]["estado"] == "interrumpido"
assert [j["id"] for j in app_client.get("/governance/training-jobs").get_json()["jobs"]] == ["20260101T000000-aaaaaa"]
def test_an_unknown_scenario_or_job_is_a_404_and_no_manifest_is_a_503(app_client, monkeypatch):
"""Pins down: starting an unknown scenario, or reading an unknown job, is a 404; a cohort scenario with no dbt
manifest configured is a 503 and starts nothing. Fails if either becomes a 500 or starts a process."""
assert app_client.post("/governance/model-versions/cama/nope/train-jobs").status_code == 404
assert app_client.get("/governance/training-jobs/nada").status_code == 404
monkeypatch.delenv("DBT_MANIFEST")
assert app_client.post("/governance/model-versions/cama/survival/train-jobs").status_code == 503
def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypatch):
"""Pins down: with `TEA_REFERENCE_DIR` (and its ages table) set, TEA's job passes them to `models run`, and CaMa's job
never does. Fails if the folder is ignored, which would send the training to storage the machine cannot reach."""
monkeypatch.setenv("DBT_MANIFEST", "m.json")
monkeypatch.setenv("TEA_REFERENCE_DIR", "/referencia")
monkeypatch.setenv("TEA_REFERENCE_AGES", "/referencia/edades.csv")
tea = training_jobs._command("tea", "eeg")
cama = training_jobs._command("cama", "survival")
assert tea[tea.index("--reference-dir") + 1] == "/referencia" and tea[tea.index("--reference-ages") + 1] == "/referencia/edades.csv"
assert "--manifest" not in tea and "--reference-dir" not in cama
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")
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
+76 -11
View File
@@ -1,5 +1,5 @@
version = 1
revision = 5
revision = 3
requires-python = ">=3.12"
resolution-markers = [
"python_full_version >= '3.14' and sys_platform == 'win32'",
@@ -299,6 +299,28 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" },
]
[[package]]
name = "autograd"
version = "1.9.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9d/ac/4a8b58364ba865ab545251edbe475e5a35326814a5d274a2211d33ed8a5d/autograd-1.9.1.tar.gz", hash = "sha256:7818c5c69ddf9efb7da74097bd741a4c7920133f41966f68537223a15ef798bc", size = 2566975, upload-time = "2026-07-02T07:43:58.255Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/6e/ce/8c98e6604bb1ec9d03c8493c328185b69bb7533fe08f3640f0f3641bd9d1/autograd-1.9.1-py3-none-any.whl", hash = "sha256:b788bae3fa010cbffb4cfb7b8ba2a3f0daa6072a8506da6164c779fe9cf3e05a", size = 54387, upload-time = "2026-07-02T07:43:56.502Z" },
]
[[package]]
name = "autograd-gamma"
version = "0.5.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "autograd" },
{ name = "scipy" },
]
sdist = { url = "https://files.pythonhosted.org/packages/85/ae/7f2031ea76140444b2453fa139041e5afd4a09fc5300cfefeb1103291f80/autograd-gamma-0.5.0.tar.gz", hash = "sha256:f27abb7b8bb9cffc8badcbf59f3fe44a9db39e124ecacf1992b6d952934ac9c4", size = 3952, upload-time = "2020-10-15T16:51:06.785Z" }
[[package]]
name = "beautifulsoup4"
version = "4.15.0"
@@ -994,11 +1016,11 @@ wheels = [
[[package]]
name = "filelock"
version = "4.3.0"
version = "4.2.12"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/6c/bf/a895b0b8e83d0a64d134f658e393e83998abfc22bbb8b58181ce55268706/filelock-4.3.0.tar.gz", hash = "sha256:143407310acf479e82d88068e3b9a6486f45fb410c0ed8729fe7359eaabeb6f1", size = 742199, upload-time = "2026-11-22T02:15:03.187Z" }
sdist = { url = "https://files.pythonhosted.org/packages/52/aa/8ccff8da9a27e089727fcffd3c5b61708383217e47eb1e1b8af37b1dd166/filelock-4.2.12.tar.gz", hash = "sha256:7e7da24d3ac39268b0f156e56870001de44886318f092f9d851e692f7114d6dd", size = 680837, upload-time = "2026-11-18T01:20:03.951Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/68/66/870b527908a06c7ec0e91239bd2c4d0bb22921efd4f915428b4e47d461a6/filelock-4.3.0-py3-none-any.whl", hash = "sha256:f933f39f7e01249a4a49b9abab30edc6d4b874624c3de5dd0b0d137aa8adb979", size = 244553, upload-time = "2026-11-22T02:15:01.667Z" },
{ url = "https://files.pythonhosted.org/packages/8a/c9/eb6b6528c7edb958d4c24ac47a8b94113d9de36e4cfc6eecd599b1a4f349/filelock-4.2.12-py3-none-any.whl", hash = "sha256:21decfec02f116ed4c954433cdb31f28c3b346b784543177b6d7059da2702ee9", size = 222442, upload-time = "2026-11-18T01:20:02.439Z" },
]
[[package]]
@@ -1392,8 +1414,8 @@ name = "httpcore2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h11" },
{ name = "truststore" },
{ name = "h11", marker = "sys_platform != 'emscripten'" },
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" }
wheels = [
@@ -1783,6 +1805,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/23/93/4e45e37f26c820216704b36b8e67cc55c490a7abd287a78a26a2c0e21386/lazy_loader-0.6-py3-none-any.whl", hash = "sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056", size = 8791, upload-time = "2026-09-21T21:31:31.632Z" },
]
[[package]]
name = "lifelines"
version = "0.30.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "autograd" },
{ name = "autograd-gamma" },
{ name = "formulaic" },
{ name = "matplotlib" },
{ name = "numpy" },
{ name = "pandas" },
{ name = "scipy" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ea/4f/f0b363278d40baf7d7a03217bee839cb880946c62109f243391c8754bb09/lifelines-0.30.0.tar.gz", hash = "sha256:f7f6f6275fcb167fe0f5b1ef98f868993f9c074cb74b1dd6e92736efa854be18", size = 383221, upload-time = "2024-10-29T12:00:43.513Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/14/f7/379e185a75ac8166ac70756d0ba68d9a2b02b555c7fde4983246752396bd/lifelines-0.30.0-py3-none-any.whl", hash = "sha256:ac7c602c8aceced9770d3977817c9d99c250ed8cd86f2567fa0d23e4e8014bf9", size = 349319, upload-time = "2024-10-29T12:00:41.749Z" },
]
[[package]]
name = "lightgbm"
version = "4.7.0"
@@ -2161,6 +2201,7 @@ notebooks = [
{ name = "nbconvert" },
]
seer-survival = [
{ name = "lifelines" },
{ name = "matplotlib" },
{ name = "mpmath" },
{ name = "networkx" },
@@ -2168,6 +2209,11 @@ seer-survival = [
{ name = "scipy" },
{ name = "statsmodels" },
]
survival-curves = [
{ name = "mpmath" },
{ name = "plotly" },
{ name = "scipy" },
]
[package.metadata]
requires-dist = [
@@ -2175,9 +2221,11 @@ requires-dist = [
{ name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" },
{ name = "extraction", editable = "../Extraction" },
{ name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" },
{ name = "lifelines", marker = "extra == 'seer-survival'", specifier = ">=0.28" },
{ name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" },
{ name = "mlflow", specifier = ">=2.9" },
{ name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" },
{ name = "mpmath", marker = "extra == 'survival-curves'", specifier = ">=1.3" },
{ name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" },
{ name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" },
{ name = "networkx", marker = "extra == 'seer-survival'", specifier = ">=3.0" },
@@ -2185,24 +2233,28 @@ requires-dist = [
{ name = "pandera", specifier = ">=0.20" },
{ name = "persistance", editable = "../Persistance" },
{ name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" },
{ name = "plotly", marker = "extra == 'survival-curves'", specifier = ">=5.18" },
{ name = "pyarrow", specifier = ">=15" },
{ name = "scikit-learn", specifier = ">=1.4" },
{ name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" },
{ name = "scipy", marker = "extra == 'survival-curves'", specifier = ">=1.11" },
{ name = "statsmodels", marker = "extra == 'seer-survival'", specifier = ">=0.14" },
{ name = "tea", editable = "../models/libs/tea" },
{ name = "tea", extras = ["s3"], marker = "extra == 'eeg-reference'", editable = "../models/libs/tea" },
]
provides-extras = ["eeg-reference", "notebooks", "seer-survival", "seer-survival-dca"]
provides-extras = ["eeg-reference", "notebooks", "seer-survival", "survival-curves", "seer-survival-dca"]
[package.metadata.requires-dev]
dev = [
{ name = "ipykernel", specifier = ">=6.29" },
{ name = "lifelines", specifier = ">=0.28" },
{ name = "matplotlib", specifier = ">=3.8" },
{ name = "mpmath", specifier = ">=1.3" },
{ name = "nbclient", specifier = ">=0.10" },
{ name = "nbconvert", specifier = ">=7.16" },
{ name = "networkx", specifier = ">=3.0" },
{ name = "pgmpy", specifier = ">=1.0" },
{ name = "plotly", specifier = ">=5.18" },
{ name = "pytest", specifier = ">=8.0.0" },
{ name = "reportlab", specifier = ">=4.0" },
{ name = "scipy", specifier = ">=1.11" },
@@ -2900,7 +2952,7 @@ name = "pexpect"
version = "4.9.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "ptyprocess" },
{ name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }
wheels = [
@@ -3010,6 +3062,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" },
]
[[package]]
name = "plotly"
version = "7.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "narwhals" },
{ name = "packaging" },
]
sdist = { url = "https://files.pythonhosted.org/packages/49/c3/72b369f5ed7701b04ab0ea3dcf83e9bbce71c0b3bc6f07f87568550d09ea/plotly-7.1.0.tar.gz", hash = "sha256:f860166a4a3d78c69cb1f4a15f28a5c8283eade98a282a698f3bb853a449ace5", size = 6689315, upload-time = "2026-09-15T19:21:21.75Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl", hash = "sha256:dbb7fa18afce40d0a8e80d1bf162eceb3faa0ce5a77fe741ad09a74cf78f53f3", size = 9692368, upload-time = "2026-09-15T19:21:18.331Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
@@ -4359,7 +4424,7 @@ wheels = [
[[package]]
name = "tea"
version = "0.2.0"
version = "0.3.0"
source = { editable = "../models/libs/tea" }
dependencies = [
{ name = "antropy" },
@@ -4688,7 +4753,7 @@ dependencies = [
{ name = "flask" },
{ name = "flask-cors" },
{ name = "gunicorn" },
{ name = "models", extra = ["notebooks", "seer-survival"] },
{ name = "models", extra = ["notebooks", "seer-survival", "survival-curves"] },
{ name = "openpyxl" },
{ name = "pandas" },
{ name = "pdfplumber" },
@@ -4724,7 +4789,7 @@ requires-dist = [
{ name = "flask", specifier = ">=3.0" },
{ name = "flask-cors", specifier = ">=4.0" },
{ name = "gunicorn", specifier = ">=23.0" },
{ name = "models", extras = ["notebooks", "seer-survival"], editable = "../models" },
{ name = "models", extras = ["notebooks", "survival-curves", "seer-survival"], editable = "../models" },
{ name = "openpyxl", specifier = ">=3.1" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "pdfplumber", specifier = ">=0.11" },
+24 -2
View File
@@ -1,4 +1,5 @@
import datetime as _dt
import logging
import os
from decimal import Decimal
@@ -13,7 +14,6 @@ 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.cama_survival.routes import cama_survival_bp
from webapi.follow_up.routes import follow_up_blueprint
@@ -97,15 +97,37 @@ def create_app() -> Flask:
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
from persistance import cacu as cacu_repositories
from persistance import cama as cama_repositories
from persistance.db import get_cacu_session, get_cama_session
from webapi.model_analysis import model_analysis_blueprint, recurrence_blueprint
from webapi.risk_batches import risk_batches_blueprint
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_survival_bp, url_prefix="/cama/supervivencia")
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()
+289 -9
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 ----------------------------------------------------------------
@@ -117,6 +239,55 @@ def train_model_version(domain: str, scenario: str):
return jsonify({"error": error or "No se pudo entrenar el modelo.", "output": output}), status
@governance_bp.get("/scenarios")
def trainable_scenarios():
"""The scenarios that can be trained from here, each with its production version if it has one."""
from webapi import training_jobs
result = []
for entry in training_jobs.catalog():
try:
production = str(registry.resolve(entry["domain"], entry["scenario"]).version)
except LookupError:
production = None
result.append({**entry, "produccion": production})
return jsonify({"scenarios": result})
@governance_bp.post("/model-versions/<domain>/<scenario>/train-jobs")
def start_training_job(domain: str, scenario: str):
"""Starts the scenario's training in the background and answers 202 with the job; a job of that scenario that is
still running is answered 409 with it. 404 for a scenario that cannot be trained, 503 with no dbt manifest."""
from webapi import training_jobs
if training_jobs.running(domain, scenario) is not None:
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
@governance_bp.get("/training-jobs")
def list_training_jobs():
from webapi import training_jobs
return jsonify({"jobs": training_jobs.jobs()})
@governance_bp.get("/training-jobs/<job_id>")
def training_job(job_id: str):
from webapi import training_jobs
return jsonify({"job": training_jobs.get(job_id)})
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
def attach_reports(domain: str, scenario: str, version: str):
"""MLD-01/01b/03 documents, usually written after training."""
@@ -184,6 +355,15 @@ def list_cohort_files():
return jsonify({"builds": exported_builds(_cohorts_root(domain), domain)})
@governance_bp.get("/notebook-templates")
def list_notebook_templates():
"""`?domain=`: the notebooks kept in the code (`models/<domain>/<scenario>/notebooks/`), with the scenarios each can
run for; `POST /experiments` runs one by its `id` as `template`."""
from models.reports.templates import notebook_templates
return jsonify({"templates": notebook_templates(request.args.get("domain") or None)})
@governance_bp.get("/experiments")
def list_experiments():
"""Notebook runs, newest first; `?domain=` and `?domain=&scenario=` narrow them."""
@@ -193,13 +373,18 @@ def list_experiments():
@governance_bp.post("/experiments")
def run_experiment():
"""Multipart `file` (a .ipynb), `domain`, `scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`:
runs the notebook on that build's file in the background and answers 202 with the run, still `en_curso`."""
"""Multipart `file` (a .ipynb) or `template` (the id of a notebook kept in the code, `/notebook-templates`), `domain`,
`scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`: runs the notebook on that build's file in
the background and answers 202 with the run, still `en_curso`. A template is read from the code, never from the
request, and must be of the domain and serve the scenario."""
upload = request.files.get("file")
form = request.form
template = form.get("template") or None
missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)]
if upload is None or missing:
return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 400
if (upload is None and template is None) or missing:
return jsonify({"error": f"faltan campos: {(['file o template'] if upload is None and template is None else []) + missing}"}), 400
if upload is not None and template is not None:
return jsonify({"error": "elige un archivo o una plantilla, no ambos"}), 400
domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None
url = form["url"]
if url.split("/", 1)[0] != domain:
@@ -207,13 +392,21 @@ def run_experiment():
if not form["build"].isdigit():
return jsonify({"error": "build debe ser un número"}), 400
path = build_file(_cohorts_root(domain), url, form["source"], int(form["build"]))
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
if template is not None:
from models.reports.templates import notebook_templates, template_notebook
name, notebook = template_notebook(template)
found = {t["id"]: t for t in notebook_templates(domain)}.get(template)
if found is None or scenario not in found["scenarios"]:
return jsonify({"error": f"la plantilla {template!r} no corre para {domain}/{scenario}"}), 400
else:
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
name = experiment.notebook_name(upload.filename or "notebook")
if version:
registry.get(domain, scenario, version)
name = experiment.notebook_name(upload.filename or "notebook")
run_id = experiment.start(notebook, name, path, domain, scenario, version)
submit(experiment.execute, run_id, notebook, name, path, domain, scenario, version)
return jsonify(experiment.describe(run_id)), 202
@@ -375,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
@@ -429,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
+21 -3
View File
@@ -6,12 +6,14 @@ date taken, then the greatest source id, then the latest report date, then the g
always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one
(`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy
shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to.
Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on
or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise.
Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off.
"""
from dataclasses import dataclass
from datetime import date
from datetime import date, timedelta
from sqlalchemy import Date, Integer, String, column, func, inspect, select, table
from sqlmodel import Session
@@ -25,6 +27,8 @@ ESCENARIO = "diagnostico"
VERSION = "0.1.0"
SIN_DATO = "SIN_DATO"
SIN_BIOPSIA = "SIN_BIOPSIA"
POST_TRATAMIENTO = "POST_TRATAMIENTO"
EN_OBSERVACION = "EN_OBSERVACION"
# Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest.
GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
@@ -35,14 +39,17 @@ CANDIDATOS = table(
column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String),
column("biopsia_fecha_reporte", Date), column("biopsia_grado", String),
)
LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date))
class CohorteNoDisponible(RuntimeError):
"""The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503)."""
"""The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't
run (503)."""
def disponible(sesion: Session) -> bool:
return inspect(sesion.get_bind()).has_table(CANDIDATOS.name)
inspector = inspect(sesion.get_bind())
return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO))
@dataclass(frozen=True)
@@ -58,6 +65,7 @@ class Fila:
# The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`).
primera_biopsia_fecha: date | None = None
primer_maligno_fecha: date | None = None
escenario_clinico: str = EN_OBSERVACION
@property
def resultado(self) -> str:
@@ -93,8 +101,17 @@ def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
return SIN_DATO
def en_postratamiento(sesion: Session, corte: date) -> set[int]:
"""The patients whose timeline puts them in post-treatment on or before `corte`."""
linea = LINEA_DE_TIEMPO.c
# Before the next day, so a date stored with a time still counts on its own day.
return set(sesion.execute(select(linea.pac_id).distinct().where(
linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars())
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
postratamiento = en_postratamiento(sesion, corte)
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS)
@@ -133,6 +150,7 @@ def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None,
primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None),
primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None),
escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION,
))
return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id))
+57 -3
View File
@@ -9,12 +9,15 @@ 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
from webapi.cama_follow_up.cohort import (
COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
COHORTE, EN_OBSERVACION, ESCENARIO, POST_TRATAMIENTO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
disponible, grupos_de_edad,
)
from webapi.orchestration.reference.rules import valor_de
@@ -25,11 +28,13 @@ VENTANA_POR_OMISION = 3
PAGINA_MAXIMA = 200
EXPORTACION_MAXIMA = 5000
GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"}
ESCENARIOS_CLINICOS = {POST_TRATAMIENTO: "Post-tratamiento", EN_OBSERVACION: "En observación"}
COLUMNAS = [
{"clave": "pac_id", "etiqueta": "Identificador de paciente"},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad"},
{"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]},
{"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico"},
]
@@ -80,6 +85,8 @@ def filtros_disponibles(sesion: Session) -> list[dict]:
*({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()),
{"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"},
{"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico", "opciones": [
{"codigo": c, "etiqueta": e} for c, e in ESCENARIOS_CLINICOS.items()]},
]
@@ -111,10 +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}
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None,
"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]]:
@@ -127,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):
+1 -1
View File
@@ -15,7 +15,7 @@ from webapi.cama_follow_up.listing import (
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia")
FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")
-5
View File
@@ -1,5 +0,0 @@
"""CaMa's survival figures over the model in production.
service.py the production model and the live cohort, a scenario's figure and a patient's scenarios, cached
routes.py the routes: `/cama/supervivencia/...`
"""
-37
View File
@@ -1,37 +0,0 @@
"""`/cama/supervivencia`: the survival figure of a clinical scenario and the scenarios of a patient."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_survival import service
cama_survival_bp = Blueprint("cama_survival", __name__)
@cama_survival_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_survival_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_survival_bp.get("/figura")
def figure():
scenario = request.args.get("escenario", "").strip()
if not scenario:
raise BadRequest("falta el parámetro «escenario»")
try:
return jsonify(service.figure(scenario))
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}»")
@cama_survival_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")
-124
View File
@@ -1,124 +0,0 @@
"""The production CaMa survival model over the live cohort build.
A scenario's figure is computed on request from the production version of `cama/seer_survival` and the latest build of its
cohort, and kept per (model version, cohort build, scenario): a new version or a new build computes it again. The saved model
is rehydrated with the current class before it scores (`SeerSurvivalModel.rehydrate`).
"""
import os
import pickle
import threading
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
import mlflow.sklearn
import pandas as pd
from models.cama.seer_survival import seer_model
from models.dags.training import Scenario
from models.io.registry import registry
from models.io.storage import KitBuild
DOMAIN, SCENARIO = "cama", "seer_survival"
class NotAvailable(LookupError):
"""There is no production version, or no cohort build to draw on."""
class SavedFile:
"""The model saved as a file (`CAMA_SURVIVAL_MODEL`), versioned by its modification time."""
def __init__(self, path: str):
self.path = Path(path)
self.version = f"archivo-{int(self.path.stat().st_mtime)}"
def load(self):
with self.path.open("rb") as handle:
return pickle.load(handle)
@dataclass
class Live:
"""The model of the production version and the live build's members, recoded once for both."""
version: str
build_id: int
model: seer_model.SeerSurvivalModel
cohort: pd.DataFrame
frame: object
figures: dict
_lock = threading.RLock()
_live: Live | None = None
def _resolve() -> tuple[str, int, object]:
scenario = Scenario.load(DOMAIN, SCENARIO)
repositories = import_module(f"persistance.{DOMAIN}")
file = os.environ.get("CAMA_SURVIVAL_MODEL")
if file:
if not Path(file).is_file():
raise NotAvailable("no hay un modelo de supervivencia guardado")
resolved = SavedFile(file)
else:
try:
resolved = registry.resolve(DOMAIN, SCENARIO)
except LookupError as error:
raise NotAvailable("no hay una versión del modelo de supervivencia en producción") from error
build_id = repositories.cohort_repository.latest_build(scenario.cohort)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el modelo de supervivencia")
return resolved.version, int(build_id), resolved
def live() -> Live:
"""The production version over the latest build; loaded again only when either changed."""
global _live
version, build_id, resolved = _resolve()
with _lock:
if _live is None or (_live.version, _live.build_id) != (version, build_id):
saved = resolved.load() if isinstance(resolved, SavedFile) else mlflow.sklearn.load_model(resolved.model_uri)
model = seer_model.SeerSurvivalModel.rehydrate(saved)
cohort = KitBuild(DOMAIN, build_id).frame()
recoded = model.recode(cohort)
_live = Live(version, build_id, model, cohort, model.frame(recoded), {})
return _live
def scenarios() -> dict:
current = live()
return {"model_version": current.version, "build": current.build_id, "scenarios": current.model.scenario_names()}
def figure(scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for a scenario the model doesn't define."""
current = live()
if scenario not in current.model.scenario_names():
raise KeyError(scenario)
with _lock:
if scenario not in current.figures:
settings = seer_model.figure_settings()
current.figures[scenario] = {
"model_version": current.version, "build": current.build_id,
**current.model.figure_record(
current.frame, scenario, ks_max_seconds=settings["ks_max_seconds"], n_boot=settings["n_boot"],
min_members=settings["min_members"], min_deaths=settings["min_deaths"])}
return current.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient belongs to, from her variables over the timeline (age, stage, subtype, surgery)."""
current = live()
events = current.cohort[current.cohort["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
model = current.model
recoded = model.recode(events)
names = []
if len(recoded):
masks = model.scenario_masks(model.frame(recoded))
names = [name for name, mask in masks.items() if bool(mask[0])]
return {"model_version": current.version, "build": current.build_id, "pac_id": pac_id, "scenarios": names}
+35
View File
@@ -99,6 +99,40 @@ class CompositionDefinition:
improvement_notation = None
class InvalidCategoryGroups(ValueError):
"""A composition's category groups (`categoria.grupos` and each label's `grupo`) don't hold together."""
def category_groups(url: str, rule: dict) -> dict[str, str]:
"""The groups of a composition's categories (`categoria.grupos`: code -> caption), checked against the labels that
name them (`categoria.etiquetas.<code>.grupo`). Optional: without either, there are none.
A label may name no group (a category kept apart, like «Sin biopsia aún»); every group named is declared, every
declared group has a category, and the no-data category, if grouped, is alone in the group of its own code, as the
indicator page reads it.
"""
grupos = rule.get("grupos")
labels = rule.get("etiquetas", {})
named = {code: spec["grupo"] for code, spec in labels.items() if isinstance(spec, dict) and "grupo" in spec}
if grupos is None:
if named:
raise InvalidCategoryGroups(f"{url}: categories name groups ({', '.join(sorted(named))}) but `grupos` is missing")
return {}
if not isinstance(grupos, dict) or not grupos or not all(
isinstance(code, str) and code and isinstance(caption, str) and caption.strip() for code, caption in grupos.items()):
raise InvalidCategoryGroups(f"{url}: `grupos` maps each group's code to a non-empty caption")
if unknown := sorted({g for g in named.values() if g not in grupos}):
raise InvalidCategoryGroups(f"{url}: undeclared groups {unknown}")
if unused := sorted(set(grupos) - set(named.values())):
raise InvalidCategoryGroups(f"{url}: groups without categories {unused}")
no_data = rule.get("sin_dato")
if no_data in named and (named[no_data] != no_data or [c for c, g in named.items() if g == no_data and c != no_data]):
raise InvalidCategoryGroups(f"{url}: the no-data category {no_data!r} goes alone in the group {no_data!r}")
if no_data in grupos and named.get(no_data) != no_data:
raise InvalidCategoryGroups(f"{url}: the group {no_data!r} is the no-data category's own")
return dict(grupos)
def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
"""The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`."""
m = json.loads(manifest.read_text(encoding="utf-8"))
@@ -112,6 +146,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
model = _semantic_model_of(metric, semantic)
node = models[model["depends_on"]["nodes"][0]]
rule = meta["categoria"]
category_groups(meta["measure_url"], rule) # fails the manifest's load if the groups don't hold together
definitions[meta["measure_url"]] = CompositionDefinition(
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"],
model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"],
+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)
+3 -2
View File
@@ -20,6 +20,7 @@ from pathlib import Path
from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true
from webapi.fhir_base import STRUCTURE
from webapi.metrics import (
AGGREGATION_VERSION,
EVENT_CUTOFF,
@@ -278,9 +279,9 @@ def duration_report(definition: DurationDefinition, question: Question, result:
]}
if result.median is not None:
group["measureScore"] = {"value": result.median, "unit": "d",
"extension": [{"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
"extension": [{"url": f"{STRUCTURE}/q1",
"valueDecimal": result.q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
{"url": f"{STRUCTURE}/q3",
"valueDecimal": result.q3}]}
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id},
{"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or question.event_cutoff).isoformat()}]
+21 -9
View File
@@ -9,7 +9,7 @@ individual risk.
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's individual risk, the current batch (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's and CaMa's individual risk, the current batch (DEV only)
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
@@ -24,10 +24,12 @@ from werkzeug.exceptions import HTTPException
from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data
from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url
from webapi.fhir.risk import not_scored
from webapi.fhir.terminology import code_systems, metric_value_set
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
from webapi.metrics import Question, UndecidedRule
RISK_DOMAINS = ("cacu", "cama") # the domains whose patients' individual risk is served as a RiskAssessment
TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion")
@@ -38,7 +40,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
blueprint = Blueprint(f"{project}_fhir", __name__)
titles = labels(manifest)
patients = with_patients and project == "tea"
risks = with_patients and project == "cacu"
risks = with_patients and project in RISK_DOMAINS
def definitions() -> dict:
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
@@ -176,13 +178,15 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
if patients:
_patient_routes(blueprint, repositories, now)
if risks:
_risk_routes(blueprint, repositories)
_risk_routes(blueprint, repositories, project)
return blueprint
def _risk_routes(blueprint: Blueprint, repositories) -> None:
"""CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from webapi.fhir import cacu
def _risk_routes(blueprint: Blueprint, repositories, project: str) -> None:
"""A patient's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from importlib import import_module
domain = import_module(f"webapi.fhir.{project}")
@blueprint.get("/RiskAssessment")
def risk_assessments():
@@ -195,8 +199,15 @@ def _risk_routes(blueprint: Blueprint, repositories) -> None:
except ValueError as error:
return outcome(400, "invalid", str(error))
pac_id = int(reference)
risk = repositories.cohort_repository.current_risk(pac_id)
found = [] if risk is None else [cacu.risk_assessment(pac_id, risk, simulated_data())]
# one RiskAssessment per outcome: the current batch of each (a CIN2+ and a cancer model, say), and, for a
# patient with some risk, one with no prediction for each current model of another outcome that didn't
# score her
risks = repositories.cohort_repository.current_risks(pac_id)
found = [domain.risk_assessment(pac_id, r, simulated_data()) for r in risks]
if risks:
scored = {r.desenlace for r in risks}
found += [not_scored(domain.risk_assessment(pac_id, b, simulated_data()), b.desenlace)
for b in repositories.cohort_repository.current_batches() if b.desenlace not in scored]
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
@@ -382,5 +393,6 @@ def _included(tea, queries, e, simulated: bool) -> list[dict]:
tea.care_plan(e, simulated)]
resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r]
if (eeg := e.study_eeg()) is not None:
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks)
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks,
curves=tea.baseline_curves())
return resources
+32 -54
View File
@@ -1,62 +1,40 @@
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data).
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by
`webapi.fhir.risk` with CaCu's outcomes.
The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed
evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient:
id `<lote_id>-<pac_id>`
status the batch's state (`final`)
subject `Patient/<pac_id>`: CaCu's follow-up list uses the platform's `pac_id` (TEA keeps a
pseudonym until its patients get their own identity)
occurrenceDateTime when the batch was evaluated
method the registered model and its version (MLflow)
prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod`
from the risk's index date (the model's decision point) to that date plus the horizon;
the immediate risk (horizon 0) is a period of one day. A confidence interval, when the
model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a
decimal or a range, not both).
Not yet: `basis` (CaCu doesn't publish its cytology and HPV `Observation`s) and `mitigation` (ASCCP's clinical
action thresholds are for CIN3+; the outcome here is CIN2+).
The results the risk was computed from, the cytology sampled on its index date, go in the extension
`resultados-indice`: one `valueString` per result it has (`escamosas`, `glandulares`, `vph`), as
`citologiacervical` holds them. A risk with no cytology sampled that day has no such extension.
"""
from datetime import date, datetime, timedelta, timezone
from webapi.fhir import risk
from webapi.fhir.common import STRUCTURE
from webapi.fhir.risk import DAYS_PER_YEAR, INTERVAL, MODEL, OUTCOME # noqa: F401 (kept for readers of this module)
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
OUTCOME = f"{CODE_SYSTEM}/desenlace"
MODEL = f"{CODE_SYSTEM}/modelo"
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"}
DAYS_PER_YEAR = 365.25
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses", "cin2": "CIN2+ por biopsia",
"cancer": "Cáncer cervicouterino por biopsia"}
INDEX_RESULTS = f"{STRUCTURE}/resultados-indice"
RESULT_COLUMNS = {"escamosas": "cit_celulas_escamosas", "glandulares": "cit_celulas_glandulares",
"vph": "cit_vph_resultado"}
def _utc(moment: datetime) -> str:
moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def index_results(pac_id: int, fecha_indice) -> dict[str, str]:
"""The results of the patient's cytology sampled on `fecha_indice` (the one with most of them), by name."""
if fecha_indice is None:
return {}
from persistance import cacu
found = {}
for row in cacu.citologia_cervical_repository.list(pac_id=pac_id, cit_fecha_toma=fecha_indice, limit=10):
results = {name: str(v) for name, column in RESULT_COLUMNS.items() if (v := getattr(row, column, None))}
if len(results) > len(found):
found = results
return found
def _until(start: date, years: float) -> date:
return start + timedelta(days=round(years * DAYS_PER_YEAR))
def _prediction(horizon, outcome: dict, start: date | None) -> dict:
item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad}
if start is not None:
item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()}
if horizon.ic_bajo is not None and horizon.ic_alto is not None:
item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo},
"high": {"value": horizon.ic_alto}}}]
return item
def risk_assessment(pac_id: int, risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`."""
desenlace = risk.desenlace or "cin2_mas"
outcome = concept(OUTCOME, desenlace, OUTCOMES.get(desenlace))
resource = {
"resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote,
"subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en),
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
}
return tagged(resource, simulated)
def risk_assessment(pac_id: int, patient_risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`, with the index cytology's results."""
resource = risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "cin2_mas")
if results := index_results(pac_id, patient_risk.fecha_indice):
resource.setdefault("extension", []).append(
{"url": INDEX_RESULTS, "extension": [{"url": k, "valueString": v} for k, v in results.items()]})
return resource
+11
View File
@@ -0,0 +1,11 @@
"""CaMa's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by
`webapi.fhir.risk` with CaMa's outcomes: the mortality at each horizon from the model's index date."""
from webapi.fhir import risk
OUTCOMES = {"muerte": "Muerte por cualquier causa"}
def risk_assessment(pac_id: int, patient_risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`."""
return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "muerte")
+4 -2
View File
@@ -9,12 +9,14 @@ from urllib.parse import urlencode
from flask import Response, request
from webapi.fhir_base import BASE as _BASE, STRUCTURE as _STRUCTURE
FHIR_VERSION = "4.0.1"
MEDIA_TYPE = "application/fhir+json"
BASE = "https://isssteleon.org/fhir"
BASE = _BASE
CODE_SYSTEM = f"{BASE}/CodeSystem"
VALUE_SET = f"{BASE}/ValueSet"
STRUCTURE = f"{BASE}/StructureDefinition"
STRUCTURE = _STRUCTURE
SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"}
MAX_COUNT = 200
DEFAULT_COUNT = 50
+107
View File
@@ -0,0 +1,107 @@
"""The age-norm curves behind the EEG metrics' reference ranges, for the FHIR answers.
Each metric row names the baseline its analysis compared it against: its `modelo` (from `eeg_metrica.met_modelo`,
carried by `tea_paciente_eeg_metricas`) is the registered model's label, `tea-<scenario>/<version>`, pinned to the
version the analysis used (which may no longer be the one in production). The full centile curve of that exact
version is its registered artifact, loaded the way the analysis loads it (`models.tea.eeg.baselines`). A label that
can't be resolved, or a module that can't be loaded, gives no curve: the answer keeps the reference range it already
had.
"""
PERCENTILES = ("p5", "p25", "mediana", "p75", "p95")
class BaselineCurves:
"""Loads and caches the centile curves of the registered baselines the EEG analysis pinned.
`curve(label, metric)` is the curve the named version draws for the metric — `{"edad_meses": [...],
"p5": [...], "p25": [...], "mediana": [...], "p75": [...], "p95": [...]}` with the ages increasing and each
row's percentiles non-crossing — or None when the label doesn't name the metric's baseline or any step of the
resolution fails (unknown metric, unknown scenario, unreachable registry, unloadable artifact). Modules are
loaded once per label. `registry` and `loader` are injectable so tests run without a model registry.
"""
def __init__(self, registry=None, loader=None):
self._registry = registry
self._loader = loader
self._modules: dict[str, dict[str, object | None]] = {}
self._curves: dict[tuple[str, str], dict | None] = {}
def curve(self, label: str, metric: str) -> dict | None:
key = (label, metric)
if key not in self._curves:
self._curves[key] = self._extract(label, metric)
return self._curves[key]
def _extract(self, label: str, metric: str) -> dict | None:
spec = self._spec_of(metric)
module = self._module(label, spec.scenario) if spec is not None else None
if module is None:
return None
from models.tea.eeg.baselines import _feature_baseline
baseline = _feature_baseline(module, spec.feature)
curve = getattr(baseline, "curva", None) # a baseline without a curve (age blocks) draws none
if curve is None:
return None
rows = curve.dropna(subset=list(PERCENTILES))
if len(rows) < 2:
return None
return {"edad_meses": [float(v) for v in rows["edad_meses"]],
**{p: [float(v) for v in rows[p]] for p in PERCENTILES}}
@staticmethod
def _spec_of(metric: str):
"""The analysis's own mapping of the stored metric code to its library feature and baseline scenario."""
from models.tea.eeg.settings import settings
return next((m for m in settings().metrics if m.code.lower() == metric), None)
def _module(self, label: str, scenario: str):
modules = self._modules.setdefault(label, {})
if scenario not in modules:
modules[scenario] = self._load(label, scenario)
return modules[scenario]
def _load(self, label: str, scenario: str):
version = self._version(label, scenario)
if version is None:
return None
try:
registry = self._registry if self._registry is not None else _default_registry()
loader = self._loader if self._loader is not None else _default_loader()
return loader(registry.resolve("tea", scenario, version).model_uri)
except Exception: # the registry may be unreachable or the artifact unloadable; the curve is omitted
return None
@staticmethod
def _version(label: str, scenario: str) -> str | None:
"""The version the label pins for the scenario, looked up among its `;`-joined baseline names."""
for name_version in label.split(";"):
name, _, version = name_version.rpartition("/")
if name.removeprefix("tea-") == scenario and version:
return version
return None
def _default_registry():
from models.io.registry import registry
return registry
def _default_loader():
from models.tea.eeg.baselines import _load
return _load
_shared: BaselineCurves | None = None
def baseline_curves() -> BaselineCurves:
"""The process-wide loader: each label's module is loaded once per deployment."""
global _shared
if _shared is None:
_shared = BaselineCurves()
return _shared
+20 -5
View File
@@ -11,7 +11,7 @@ import json
from datetime import datetime, timedelta
from pathlib import Path
from webapi.compositions import CompositionAnswer, CompositionDefinition
from webapi.compositions import CompositionAnswer, CompositionDefinition, category_groups
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
@@ -24,6 +24,7 @@ EXCLUDED = "measure-population-exclusion"
FIGURES = f"{STRUCTURE}/figuras"
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
CATEGORY_GROUP = f"{STRUCTURE}/categoria-grupo"
CONTRACT = f"{STRUCTURE}/contrato"
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
POPULATION_LABELS = {
@@ -87,9 +88,16 @@ def measure_resource(definition, title: str, description: str) -> dict:
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
category = meta.get("categoria", {})
# Optional and additive: a category's group (`grupo`) and each group's caption (`categoria-grupo`), only when the
# composition declares them; a client that doesn't know them reads the labels alone.
extensions += [{"url": CATEGORY_LABEL, "extension": [
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
{"url": "color", "valueString": spec["color"]},
*([{"url": "grupo", "valueCode": spec["grupo"]}] if spec.get("grupo") else [])]}
for code, spec in category.get("etiquetas", {}).items()]
extensions += [{"url": CATEGORY_GROUP, "extension": [
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": caption}]}
for code, caption in category_groups(definition.url, category).items()]
if meta.get("requiere_validacion"):
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
resource = {
@@ -114,8 +122,8 @@ def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
if excluded is not None and getattr(definition, "exclusion", None):
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
if counts.proportion is not None:
cells["measureScore"] = {"value": counts.proportion}
if counts.score:
cells["measureScore"] = counts.score
return cells
@@ -141,13 +149,20 @@ def _groups(definition, result) -> list[dict]:
result.total)]}
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
category = definition.category.value
# A stratum value's caption, as a proportion's strata have it (`_label`), or from `meta.etiquetas_estrato`,
# which stays out of the strata's spec so the report's key doesn't change.
spec_of = {s.name: s.spec for s in definition.strata}
captions = definition.meta.get("etiquetas_estrato", {})
def caption(name: str, value: str) -> str | None:
return _label(spec_of.get(name, {}), value) or captions.get(name, {}).get(value)
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
for c, n in sorted(result.categories.items())]}]
for name, by_value in result.strata.items():
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
"stratum": [{"component": [
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v, caption(name, v))},
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
], "population": [_count("initial-population", n)]}
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
+99
View File
@@ -0,0 +1,99 @@
"""A patient's individual risk in FHIR R4: one `RiskAssessment` per batch and patient, built from `PatientRisk`
(`CohortRepository.current_risk`: the newest batch with a confirmed evaluation).
id `<lote_id>-<pac_id>`
status the batch's state (`final`)
subject `Patient/<pac_id>`: the platform's key (TEA keeps a pseudonym until its patients get
their own identity)
occurrenceDateTime when the batch was evaluated
method the registered model and its version (MLflow)
prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod`
from the risk's index date (the model's decision point) to that date plus the horizon;
the immediate risk (horizon 0) is a period of one day. A confidence interval, when the
model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a
decimal or a range, not both).
What the number is, from the model's scenario (`[estimand]` of its `model.toml`), goes in the extension `estimando`:
one `valueString` per key (`quantity`, `description`, `outcome`, `index_date`, `horizons_unit`), and its
`quantity` as `method.text`. A model whose scenario can't be read has neither.
A current model of an outcome that didn't score the patient gives a `RiskAssessment` with no `prediction` and the
extension `sin-estimacion` (`not_scored`), so her record can tell "no model" from "not estimated for her".
Not yet: `basis` (the observations the model used) and `mitigation`. Each domain gives its outcomes' codes and labels
(`webapi.fhir.cacu`, `webapi.fhir.cama`).
"""
from datetime import date, datetime, timedelta, timezone
from functools import lru_cache
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
OUTCOME = f"{CODE_SYSTEM}/desenlace"
MODEL = f"{CODE_SYSTEM}/modelo"
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
ESTIMAND = f"{STRUCTURE}/estimando"
NOT_SCORED = f"{STRUCTURE}/sin-estimacion"
NOT_SCORED_TEXT = ("el modelo vigente de este desenlace no estima a la paciente: queda fuera de su población (su "
"índice o sus reglas) o su combinación de resultados no estuvo en su entrenamiento")
DAYS_PER_YEAR = 365.25
def _utc(moment: datetime) -> str:
moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _until(start: date, years: float) -> date:
return start + timedelta(days=round(years * DAYS_PER_YEAR))
def _prediction(horizon, outcome: dict, start: date | None) -> dict:
item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad}
if start is not None:
item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()}
if horizon.ic_bajo is not None and horizon.ic_alto is not None:
item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo},
"high": {"value": horizon.ic_alto}}}]
return item
@lru_cache(maxsize=32)
def estimand(modelo_nombre: str) -> dict[str, str]:
"""The `[estimand]` of the registered model's scenario (`<domain>-<scenario>`), empty if it can't be read."""
domain, _, scenario = modelo_nombre.partition("-")
try:
from models.dags.training import Scenario
return {str(k): str(v) for k, v in Scenario.load(domain, scenario).estimand.items()}
except (ImportError, LookupError, OSError, ValueError):
return {}
def risk_assessment(pac_id: int, risk, simulated: bool, outcomes: dict[str, str], default_outcome: str) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`; `outcomes` maps the domain's outcome codes to
their labels, and `default_outcome` stands for a batch that doesn't name one."""
desenlace = risk.desenlace or default_outcome
outcome = concept(OUTCOME, desenlace, outcomes.get(desenlace))
resource = {
"resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote,
"subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en),
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
}
if not risk.horizontes: # a current model of the outcome that didn't score her (`not_scored`)
del resource["prediction"]
if found := estimand(risk.modelo_nombre):
resource["method"]["text"] = found.get("quantity", "")
resource["extension"] = [{"url": ESTIMAND, "extension": [{"url": k, "valueString": v}
for k, v in found.items()]}]
return tagged(resource, simulated)
def not_scored(resource: dict, desenlace: str | None) -> dict:
"""A `RiskAssessment` of a model that didn't score the patient (a batch with no horizons of hers), marked with
the extension `sin-estimacion`: its outcome (`desenlace`, since there is no prediction to carry it) and why it
may be so (`motivo`)."""
resource.setdefault("extension", []).append({"url": NOT_SCORED, "extension": [
{"url": "desenlace", "valueCode": desenlace or ""}, {"url": "motivo", "valueString": NOT_SCORED_TEXT}]})
return resource
+133 -17
View File
@@ -4,7 +4,11 @@ Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, n
at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its
stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. The views carry the age the analysis compared
the references at and, per metric, the registered label of the baseline that comparison used, from which the metric
observations draw the baseline's full centile curve. The ADOS-2 association model reaches the summary as one
`RiskAssessment` per patient (a prediction per association row of `tea_paciente_relacion_ados2`), and stays out
while no model row scored the patient's study EEG.
Until the domain expert validates the age baselines, every alteration stays hidden (`alterations_validated`):
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
@@ -18,6 +22,7 @@ from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
from webapi.fhir.eeg_curves import PERCENTILES, baseline_curves
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
@@ -29,25 +34,30 @@ ICD10 = "http://hl7.org/fhir/sid/icd-10"
CATALOG = f"{CODE_SYSTEM}/tea-catalogo"
STAGE_DATE = f"{STRUCTURE}/fecha-etapa"
AGE_GROUP = f"{STRUCTURE}/grupo-edad"
CURVE = f"{STRUCTURE}/curva-referencia"
DEFAULT_SALT = "dev-simulado"
FOLLOW_UP = table("tea_seguimiento", *map(column, (
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
EEGS = table("tea_paciente_eegs", *map(column, (
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "nivel", "fraccion_limpia",
"canales_malos", "ruido_linea_db", "calidad", "valido")))
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "edad_meses", "nivel",
"fraccion_limpia", "canales_malos", "ruido_linea_db", "calidad", "valido")))
CHECKS = table("tea_paciente_eeg_criterios", *map(column, (
"procedimiento_id", "pac_id", "criterio", "electrodo", "valor", "valor_texto", "bajo", "alto", "anormal",
"decisivo", "etiqueta", "unidad")))
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "valor_z",
"estado")))
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "modelo",
"valor_z", "estado")))
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
"valor", "valor_z")))
ADOS2 = table("tea_paciente_ados2", *map(column, (
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
"etiqueta", "puntaje", "puntaje_algoritmo")))
RELACION = table("tea_paciente_relacion_ados2", *map(column, (
"pac_id", "procedimiento_id", "version", "validado", "nivel", "n_cohorte", "biomarcador", "zona", "tipo",
"resultado", "evento", "odds_ratio", "ic_inf", "ic_sup", "q", "valor_z", "probabilidad",
"probabilidad_referencia", "observado")))
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
@@ -263,12 +273,26 @@ def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulate
return observations
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
extension holds scalars, not arrays."""
series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES))
return {"url": CURVE, "extension": [
{"url": f"{CURVE}/fuente", "valueString": label},
{"url": f"{CURVE}/estado", "valueString": "validada" if (alterations_validated() 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) -> 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. A value without a z is a metric the
baseline couldn't score (none in production, or an age it doesn't cover): no interpretation."""
as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label
(`modelo`) and a loader, the observation also carries the baseline's full centile curve as an extension. A value
without a z is a metric the baseline couldn't score (none in production, or an age it doesn't cover): no
interpretation."""
from webapi.fhir.terminology import TEA_EEG
observations = []
@@ -295,6 +319,10 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]},
"high": {"value": float(m["ref_max"]), "unit": spec["unidad"]},
"text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}]
if curves is not None and m.get("modelo"):
curve = curves.curve(m["modelo"], m["metrica"])
if curve is not None:
resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve, 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]
@@ -310,12 +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] = ()) -> 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."""
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`). `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)
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}"},
@@ -329,10 +361,12 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
from tea.validation.fhir import SYSTEM
report["conclusionCode"].append(concept(SYSTEM, "valid" if eeg["valido"] == 1 else "not-valid"))
if eeg["duracion_min"] is not None or eeg["canales"] is not None:
if eeg["duracion_min"] is not None or eeg["edad_meses"] is not None or eeg["canales"] is not None:
report["extension"] = [e for e in (
{"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])}
if eeg["duracion_min"] is not None else None,
{"url": f"{STRUCTURE}/edad-meses", "valueDecimal": float(eeg["edad_meses"])}
if eeg["edad_meses"] is not None else None,
{"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
) if e]
if eeg["calidad"] == "SIN_ANALIZAR":
@@ -343,9 +377,81 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
return [procedure, tagged(report, simulated), *quality, *altered]
def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_id: int | None,
simulated: bool) -> dict | None:
"""The association model as one `RiskAssessment`: a prediction per association row that scored the study's EEG,
the clearest cohort association (lowest q) first. The model's version, expert validation, level and cohort size
sit on the resource; each prediction carries the outcome (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 TEA_EEG, ados2_resultados
resultados, metricas, zonas = ados2_resultados(), TEA_EEG["metricas"], TEA_EEG["zonas"]
def prediction(f: dict) -> dict:
outcome = concept(f"{CODE_SYSTEM}/tea-ados2-resultado", f["resultado"],
resultados.get(f["resultado"], f["resultado"]))
return {
"outcome": outcome,
"probabilityDecimal": float(f["probabilidad"]),
"extension": [
{"url": f"{STRUCTURE}/biomarcador",
"valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-metrica", f["biomarcador"],
metricas.get((f["biomarcador"] or "").lower(), {}).get("etiqueta"))},
{"url": f"{STRUCTURE}/zona", "valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-zona", f["zona"],
zonas.get(f["zona"], f["zona"]))},
*([{"url": f"{STRUCTURE}/tipo", "valueString": f["tipo"]}] if f["tipo"] else []),
*([{"url": f"{STRUCTURE}/evento", "valueString": f["evento"]}] if f["evento"] else []),
*([{"url": f"{STRUCTURE}/valor-z", "valueDecimal": float(f["valor_z"])}]
if f["valor_z"] is not None else []),
*([{"url": f"{STRUCTURE}/odds-ratio", "valueDecimal": float(f["odds_ratio"])}]
if f["odds_ratio"] is not None else []),
*([{"url": f"{STRUCTURE}/ic-inf", "valueDecimal": float(f["ic_inf"])}]
if f["ic_inf"] is not None else []),
*([{"url": f"{STRUCTURE}/ic-sup", "valueDecimal": float(f["ic_sup"])}]
if f["ic_sup"] is not None else []),
*([{"url": f"{STRUCTURE}/q", "valueDecimal": float(f["q"])}] if f["q"] is not None else []),
*([{"url": f"{STRUCTURE}/probabilidad-referencia", "valueDecimal":
float(f["probabilidad_referencia"])}] if f["probabilidad_referencia"] is not None else []),
*([{"url": f"{STRUCTURE}/observado", "valueInteger": int(f["observado"])}]
if f["observado"] is not None else []),
],
}
primero = rows[0]
resource = {
"resourceType": "RiskAssessment", "id": f"relacion-ados2-{pseudonym}", "status": "final",
"subject": {"reference": f"Patient/{pseudonym}"},
"code": {"coding": [coding(f"{CODE_SYSTEM}/tea-relacion-ados2", "modelo",
"Modelo de asociación de alteraciones del EEG con el ADOS-2")],
"text": "Asociación de alteraciones del EEG con el ADOS-2"},
"extension": [
{"url": f"{STRUCTURE}/modelo-version", "valueString": primero["version"]},
{"url": f"{STRUCTURE}/modelo-validado", "valueBoolean": primero["validado"] == 1},
*([{"url": f"{STRUCTURE}/modelo-nivel", "valueString": primero["nivel"]}]
if primero["nivel"] else []),
*([{"url": f"{STRUCTURE}/modelo-n-cohorte", "valueInteger": int(primero["n_cohorte"])}]
if primero["n_cohorte"] is not None else []),
],
"prediction": [prediction(f) for f in sorted(
rows, key=lambda f: (f["q"] is None, f["q"] or 0, f["biomarcador"] or "", f["resultado"] or ""))],
"basis": [{"reference": f"DiagnosticReport/eeg-{primero['procedimiento_id']}"},
*([{"reference": f"Observation/ados2-{ados2_id}"}] if ados2_id is not None else [])],
}
if fecha is not None:
resource["occurrenceDateTime"] = _date(fecha).isoformat()
return tagged(resource, simulated)
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
items, each item with its algorithm score."""
from webapi.fhir.terminology import DOMINIOS_ADOS2
if not rows:
return None
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
@@ -362,7 +468,7 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
if first["clasificacion"]:
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
for domain, label in DOMINIOS_ADOS2.items():
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
@@ -376,12 +482,16 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
"""The `$resumen-tea` collection: the patient, its screening episode (with its age group), its first ADOS-2 and
the EEG the study uses, as of today."""
the EEG the study uses, as of today, and the ADOS-2 association model as one `RiskAssessment` when model rows
scored the study's EEG."""
pseudonym = seudonimo(pac_id, salt())
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
ados2_rows = _rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id))
ados2 = ados2_observation(ados2_rows, pseudonym, simulated)
resources += [ados2] if ados2 else []
first_ados2 = min((r for r in ados2_rows if r["fecha_ados2"] is not None),
key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]), default=None)
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
if child is not None:
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
@@ -391,5 +501,11 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
eeg = e.study_eeg()
if eeg is not None:
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks)
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks,
curves=baseline_curves())
riesgo = relacion_ados2(_rows(queries, select(RELACION).where(RELACION.c.pac_id == pac_id)), pseudonym,
eeg["fecha_eeg"] if eeg is not None else None,
first_ados2["procedimiento_id"] if first_ados2 is not None else None, simulated)
if riesgo:
resources.append(riesgo)
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
+15
View File
@@ -56,3 +56,18 @@ P4 = [0.33, -0.4]
T6 = [0.65, -0.47]
O1 = [-0.25, -0.77]
O2 = [0.25, -0.77]
# The scalp zones the association model relates an EEG alteration in with an ADOS-2 outcome, as the `tea` library
# codes them, 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"
+14 -1
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
@@ -14,6 +14,15 @@ STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psico
("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG"))
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
DOMINIOS_ADOS2 = {"SA": "Afecto social", "RRB": "Comportamiento restringido y repetitivo"}
CSS_ETIQUETA = "Puntaje de severidad calibrado (CSS)"
def ados2_resultados() -> dict[str, str]:
"""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:
@@ -66,6 +75,10 @@ def tea_code_systems() -> dict[str, dict]:
eeg_checks(),
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
_code_system("tea-eeg-zona", "Zonas del cuero cabelludo",
[{"code": z, "display": e} for z, e in TEA_EEG["zonas"].items()]),
_code_system("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"}]),
+12
View File
@@ -0,0 +1,12 @@
"""The base of every FHIR URL this API emits: code systems, value sets and extensions.
It is a name we mint, not an address that has to resolve. `FHIR_BASE_URL` sets it. The WebApp reads these URLs by
exact match (`fhir.ts` CODE_SYSTEM and `paciente-riesgo.validation.ts` INTERVAL), so a change of domain goes to both.
A module of its own, with no imports from the package, so `metrics` and `durations` can use it without a cycle.
"""
import os
BASE = os.environ.get("FHIR_BASE_URL", "https://isssteleon.org/fhir").rstrip("/")
STRUCTURE = f"{BASE}/StructureDefinition"
+2
View File
@@ -27,6 +27,7 @@ etiqueta = "Estatus de seguimiento"
expression = "cacu.seguimiento:estrato"
unidad = "paciente"
valores = [
{ valor = "CASO", etiqueta = "Caso (cáncer)" },
{ valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" },
{ valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" },
{ valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" },
@@ -37,6 +38,7 @@ valores = [
seguimiento_marco = "cacu.seguimiento.marco"
seguimiento_referencia = "cacu.seguimiento.referencia"
seguimiento_precedencia = "cacu.seguimiento.precedencia"
seguimiento_grados_caso = "cacu.seguimiento.caso.grados"
seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias"
seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito"
seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito"
+75 -3
View File
@@ -5,7 +5,9 @@ vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada pacient
estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su
grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
de CACU_DIAS_TOMA_DIAGNOSTICO), su última biopsia reportada al corte y su probabilidad vigente de LIEAG+ y de
cáncer en cada horizonte (los lotes confirmados que muestra su ficha). `orden` la ordena por la más reciente o por
una de esas probabilidades a `horizonte`. `prioridad` está reservada y va nula.
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
@@ -26,7 +28,7 @@ from types import SimpleNamespace
from sqlalchemy import func, select
from sqlmodel import Session
from webapi.follow_up.silver import citologias, notas
from webapi.follow_up.silver import biopsias, citologias, notas
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
from webapi.orchestration.tables.cacu import TABLAS
from webapi.follow_up.view import P
@@ -73,6 +75,12 @@ PARAMETROS_DE_LA_LISTA = {
"horizonte_dias": "cacu.horizontes.toma_diagnostico_dias",
}
ESTRATO = "estatus_seguimiento"
# How the list can be ordered: by its most recent study (the default), or by the probability, at `horizonte`, of
# LIEAG+ (CIN2+, the models whose outcome starts with `cin2`), of cancer or of surviving (a case's), highest first.
ORDENES = ("reciente", "lieag", "cancer", "supervivencia")
HORIZONTE_POR_OMISION = 5.0
# The outcomes other than CIN2+ the list shows, by their key in `probabilidades`.
DESENLACES = {"cancer": "cancer", "muerte": "supervivencia"}
class PedidoInvalido(ValueError):
@@ -89,6 +97,8 @@ def seguimiento_de(
corte: date | None = None,
meses: int | None = None,
estatus: str | None = None,
orden: str = "reciente",
horizonte: float | None = None,
page: int = 1,
page_size: int = 50,
hoy: date | None = None,
@@ -113,6 +123,8 @@ def seguimiento_de(
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
if estatus is not None and estatus not in ESTATUS:
raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.")
if orden not in ORDENES:
raise PedidoInvalido(f"orden desconocido {orden!r}; hay {list(ORDENES)}.")
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
@@ -122,6 +134,13 @@ def seguimiento_de(
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
if estatus is not None:
items = [i for i in items if i["estatus"]["codigo"] == estatus]
horizontes = sorted({h["horizonte_anios"] for i in items for p in (i["probabilidades"] or {}).values() for h in p})
horizonte = HORIZONTE_POR_OMISION if horizonte is None else float(horizonte)
if horizontes and horizonte not in horizontes:
raise PedidoInvalido(f"horizonte = {horizonte:g}: los modelos dan {[f'{h:g}' for h in horizontes]} años.")
if orden != "reciente":
# highest first, patients the model doesn't score last; the sort is stable, so ties stay most recent first
items.sort(key=lambda i: (p := _probabilidad(i, orden, horizonte)) is None or -p)
total = len(items)
paginas = -(-total // page_size)
@@ -132,7 +151,8 @@ def seguimiento_de(
"simulado": True,
"corte": corte.isoformat(),
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
"filtros": {"estatus": estatus},
"filtros": {"estatus": estatus, "orden": orden, "horizonte": horizonte},
"horizontes_disponibles": horizontes,
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
@@ -176,6 +196,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
if "vph" in lista["estudios"] and e["vph"] is not None:
de_la_paciente["vph"].append(e)
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
biopsia_de = _ultima_biopsia(sesion, corte, tablas)
riesgos = _probabilidades_por_paciente()
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
notas_de = _notas_por_paciente(sesion, corte)
items = []
@@ -199,6 +221,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
"genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]),
},
"dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista),
"ultima_biopsia": biopsia_de.get(pac_id),
"probabilidades": {k: v[pac_id] for k, v in riesgos.items() if pac_id in v} or None,
"prioridad": None,
"_orden": mas_reciente,
})
@@ -207,6 +231,54 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
return items
def _ultima_biopsia(sesion: Session, corte: date, tablas: TablasKit) -> dict[int, dict]:
"""Each patient's latest biopsy reported by the cut-off: its report date and grade (`GradoCIN`)."""
b = biopsias(tablas)
filas = sesion.execute(select(b.c.pac_id, b.c.fecha_reporte, b.c.grado).where(b.c.fecha_reporte.is_not(None))).all()
found: dict[int, dict] = {}
for pac_id, fecha, grado in filas:
fecha = _fecha(fecha)
if fecha <= corte and (pac_id not in found or fecha > date.fromisoformat(found[pac_id]["fecha"])):
found[pac_id] = {"fecha": fecha.isoformat(), "grado": grado}
return found
def _probabilidades_por_paciente() -> dict[str, dict[int, list[dict]]]:
"""Each patient's current probability of LIEAG+ (`lieag`, the outcomes `cin2*`), of cancer (`cancer`) and of
surviving (`supervivencia`, the complement of the survival model's death) at every horizon, with its interval: the
confirmed batches the patient's record shows (`current_risks_by_patient`)."""
from persistance import cacu
found: dict[str, dict[int, list[dict]]] = {}
for desenlace, por_paciente in cacu.cohort_repository.current_risks_by_patient().items():
clave = "lieag" if (desenlace or "").startswith("cin2") else DESENLACES.get(desenlace)
if clave is None:
continue
destino = found.setdefault(clave, {})
for pac_id, horizontes in por_paciente.items():
filas = [_horizonte(h, complemento=clave == "supervivencia") for h in horizontes]
if clave == "supervivencia" and filas and not any(f["horizonte_anios"] == 0 for f in filas):
# at the index date every patient is alive
filas.insert(0, {"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0})
destino.setdefault(pac_id, filas)
return found
def _horizonte(h, *, complemento: bool) -> dict:
"""A horizon's probability and interval; with `complemento`, of not having the outcome (surviving a death)."""
if not complemento:
return {"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
"ic_alto": h.ic_alto}
return {"horizonte_anios": h.horizonte_anios, "probabilidad": 1 - h.probabilidad,
"ic_bajo": None if h.ic_alto is None else 1 - h.ic_alto,
"ic_alto": None if h.ic_bajo is None else 1 - h.ic_bajo}
def _probabilidad(item: dict, clave: str, horizonte: float) -> float | None:
return next((h["probabilidad"] for h in ((item["probabilidades"] or {}).get(clave) or [])
if h["horizonte_anios"] == horizonte), None)
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
c = citologias()
+7
View File
@@ -66,4 +66,11 @@ def _requested(args) -> dict:
pedido[nombre] = int(texto)
if estatus := args.get("estatus"):
pedido["estatus"] = estatus
if orden := args.get("orden"):
pedido["orden"] = orden
if (horizonte := args.get("horizonte")) not in (None, ""):
try:
pedido["horizonte"] = float(horizonte)
except ValueError:
raise ValueError(f"horizonte debe ser un número de años; llegó {horizonte!r}") from None
return pedido
+14 -3
View File
@@ -6,6 +6,8 @@ reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las
fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo
pasado no cambia cuando la paciente avanza.
CASO una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` (CIS o carcinoma): la
paciente ya tiene cáncer, y lo que se sigue es su supervivencia
POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia
POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si
es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de
@@ -38,7 +40,7 @@ from webapi.follow_up.functions import dias_entre
from webapi.follow_up.view import P, vista
from webapi.orchestration.tables import TablasKit
ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
ESTATUS = ("CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3)
MARCOS = ("estatus", "ronda")
REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte
@@ -81,7 +83,7 @@ def reglas_de(valores: Mapping) -> Reglas:
precedencia = tuple(valores["seguimiento_precedencia"])
if sorted(precedencia) != sorted(ESTATUS):
raise ReglaDesconocida(
f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; "
f"cacu.seguimiento.precedencia debe ordenar los {len(ESTATUS)} estatus, sin repetir: {ESTATUS}; "
f"llegó {precedencia}."
)
exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS)
@@ -186,6 +188,13 @@ def estatus_al(
.group_by(evidencias.c.pac_id)
.cte("seguimiento_colposcopia")
)
# Un caso: una biopsia reportada antes de la referencia con un grado de cáncer.
caso = (
select(reporte.c.pac_id)
.distinct()
.where(antes(reporte.c.fecha_reporte), reporte.c.grado.in_(P("seguimiento_grados_caso", lista=True)))
.cte("seguimiento_caso")
)
tratamiento = (
select(nota.c.pac_id)
.distinct()
@@ -210,6 +219,7 @@ def estatus_al(
)
persona = V_PERSONA
cumple = {
"CASO": caso.c.pac_id.is_not(None),
"POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None),
"POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None),
"INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente),
@@ -219,7 +229,8 @@ def estatus_al(
return (
select(persona.c.pac_id, estatus.label("estatus"))
.select_from(
persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
persona.outerjoin(caso, caso.c.pac_id == persona.c.pac_id)
.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
.outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id)
.outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id)
)
+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)
+3
View File
@@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import (
Catalog,
CatalogValue,
FlexDate,
PostalCode,
RequiredDate,
RequiredHospitalId,
@@ -25,6 +26,8 @@ class PacienteImportSchema(ImportSchema):
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
# IND-01: required, since age at each event of interest is derived from it.
pac_fecha_nacimiento: RequiredDate
# Survival's outcome; empty while she is alive or the date is unknown.
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
+1
View File
@@ -26,6 +26,7 @@ class PacienteImportSchema(ImportSchema):
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
# IND-01: required, since age at each event of interest is derived from it.
pac_fecha_nacimiento: RequiredDate
# Survival's outcome; empty while she is alive or the date is unknown.
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
+5
View File
@@ -138,6 +138,11 @@ def coerce_postal_code(v: Any) -> Any:
# SQLite and is not in the migrations, so the format is enforced here.
CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
# A short code of a natural key made of bounded VARCHAR(32) columns (`relacion_ados2`): an over-long value is a
# validation error here rather than a `Data too long` failure at insert on MySQL/Postgres. Optional, like every
# TEA field (see `tea/pacientes.py`).
ShortKey = Annotated[Optional[Annotated[str, StringConstraints(max_length=32)]], BeforeValidator(optional_str)]
def edf_file(v: Any) -> Any:
"""`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment).
+16
View File
@@ -32,6 +32,8 @@ from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluac
from persistance.tea import mchat_repository as tea_mchat_repository
from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository
from persistance.tea import pacientes_repository as tea_pacientes_repository
from persistance.tea import relacion_ados2_paciente_repository as tea_relacion_ados2_paciente_repository
from persistance.tea import relacion_ados2_repository as tea_relacion_ados2_repository
from webapi.imports.schemas.cacu.biometria_hematica import (
BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema,
)
@@ -68,6 +70,8 @@ from webapi.imports.schemas.tea.ordenes_estudio import (
OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema,
)
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
from webapi.imports.schemas.tea.relacion_ados2 import RelacionAdos2ImportSchema
from webapi.imports.schemas.tea.relacion_ados2_paciente import RelacionAdos2PacienteImportSchema
@dataclass(frozen=True)
@@ -197,4 +201,16 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
# one row.
conflict_fields=("eeg_id_registro_laboratorio",),
),
"tea.RelacionAdos2": EntitySpec(
schema=RelacionAdos2ImportSchema,
repository=tea_relacion_ados2_repository,
# The natural key the import and the `tea` library merge model rows on (the table's unique constraint).
conflict_fields=("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"),
),
"tea.RelacionAdos2Paciente": EntitySpec(
schema=RelacionAdos2PacienteImportSchema,
repository=tea_relacion_ados2_paciente_repository,
# One probability per EEG and association row (the table's unique constraint).
conflict_fields=("rap_rel_id", "rap_eeg_id"),
),
}
@@ -0,0 +1,45 @@
"""Import schema for `core.tea.models.RelacionAdos2`: one association of an EEG alteration in a scalp zone with an
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_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)
_RESULTADOS_DOMINIO = {ADOS2_CSS}
class RelacionAdos2ImportSchema(ImportSchema):
rel_id: SourceId = None
# The natural key the import merges model rows on: rel_version, rel_biomarcador, rel_zona, rel_resultado.
rel_version: ShortKey = None
rel_nivel: CatalogValue(_NIVEL_CATALOG) = None
rel_validado: Bounded(int, 0, 1) = None
rel_n_cohorte: Bounded(int, 1, None) = None
rel_biomarcador: CatalogValue(_BIOMARCADOR_CATALOG) = None
rel_zona: ShortKey = None
rel_tipo: CatalogValue(_NIVEL_CATALOG) = None
rel_resultado: ShortKey = None
rel_evento: OptionalStr = None
rel_or: Optional[Annotated[float, Field(gt=0)]] = None
rel_ic_inf: Bounded(float, 0, None) = None
rel_ic_sup: Bounded(float, 0, None) = None
rel_q: Bounded(float, 0, 1) = None
@model_validator(mode="after")
def _outcome_code_and_interval_checks(self):
if self.rel_ic_inf is not None and self.rel_ic_sup is not None and self.rel_ic_inf > self.rel_ic_sup:
raise ValueError("rel_ic_inf no puede ser mayor que rel_ic_sup")
if self.rel_tipo is not None and self.rel_resultado is not None:
validos = (set(ADOS2_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
@@ -0,0 +1,16 @@
"""Import schema for `core.tea.models.RelacionAdos2Paciente`: one patient's z and model probability for an
association row, per EEG. The observed outcome stays in `ados2`, never here."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Bounded, SourceId
class RelacionAdos2PacienteImportSchema(ImportSchema):
rap_id: SourceId = None
# The natural key the import merges patient rows on: rap_rel_id, rap_eeg_id.
rap_rel_id: SourceId = None
rap_eeg_id: SourceId = None
rap_valor_z: Optional[float] = None
rap_probabilidad: Bounded(float, 0, 1) = None
rap_probabilidad_referencia: Bounded(float, 0, 1) = None
+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
+19 -5
View File
@@ -41,6 +41,9 @@ from sqlalchemy import (
true,
)
from webapi.cama_analysis.stats import wilson
from webapi.fhir_base import STRUCTURE
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
TOTAL = "total"
NO_DATA = "sin_dato"
@@ -545,6 +548,15 @@ class Counts:
def proportion(self) -> float | None:
return self.numerator / self.denominator if self.denominator else None
@property
def score(self) -> dict | None:
"""The FHIR `measureScore`: the proportion and its 95 % Wilson interval, all as proportions in [0, 1]."""
if not self.denominator:
return None
low, high = wilson(self.numerator, self.denominator)
return {"value": self.proportion, "extension": [
{"url": INTERVAL_LOW, "valueDecimal": low}, {"url": INTERVAL_HIGH, "valueDecimal": high}]}
@dataclasses.dataclass(frozen=True)
class Answer:
@@ -654,9 +666,11 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by
# --- the contract --------------------------------------------------------------------------------------------------
POPULATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-population"
EVENT_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-evento"
KNOWLEDGE_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento"
HISTORY_ENTRY = "https://isssteleon.org/fhir/StructureDefinition/reporte-id"
EVENT_CUTOFF = f"{STRUCTURE}/corte-evento"
KNOWLEDGE_CUTOFF = f"{STRUCTURE}/corte-conocimiento"
HISTORY_ENTRY = f"{STRUCTURE}/reporte-id"
INTERVAL_LOW = f"{STRUCTURE}/ic-bajo"
INTERVAL_HIGH = f"{STRUCTURE}/ic-alto"
def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
@@ -667,8 +681,8 @@ def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
def _scored(entry: dict, counts: Counts) -> dict:
if counts.proportion is not None:
entry["measureScore"] = {"value": counts.proportion}
if counts.score:
entry["measureScore"] = counts.score
return entry
+308
View File
@@ -0,0 +1,308 @@
"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas`, `GET /<domain>/modelo/desarrollo` and, over the data ingested so far, `GET /<domain>/modelo/escenarios` and `POST /<domain>/modelo/curvas/consulta`.
The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's
survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the
cohort, not any patient. The answer names the version they come from, and carries `simulado: true` in DEV, where the
data are simulated. 404 while the scenario has no version in production, or its version has no such record.
"""
import json
import logging
import os
from collections import OrderedDict
from pathlib import Path
from threading import Lock
from flask import Blueprint, jsonify, request
from webapi.fhir.common import simulated_data
_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):
"""`(scenario, fitted model, labelled members, version)`: the production version and the cohort build the cycle made last,
kept until either changes. `LookupError` while there is no version or no build."""
import importlib
import mlflow.sklearn
from models.cama.survival import live
from models.dags.training import Scenario
from models.io.registry import registry
resolved = registry.resolve(domain, scenario)
spec = Scenario.load(domain, scenario)
build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(spec.cohort)
if build_id is None:
raise LookupError(f"({domain}, {scenario}) has no cohort build yet")
key = (resolved.version, build_id)
with _LOCK:
if _LIVE.get("key") != key:
model = live.rehydrate(mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1])
_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)."""
from models.io.registry import registry
try:
_, content = registry.artifact(domain, scenario, version, artifact)
except LookupError:
return []
record = json.loads(content)
rows = (record.get("tablas") or record.get("desarrollo", {}).get("tablas") or {}).get(table) or {}
return rows.get("filas", []) if isinstance(rows, dict) else rows
def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
"""The blueprint of one scenario, to register with `url_prefix="/<domain>"`."""
blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__)
@blueprint.get("/modelo/curvas")
def curves():
"""The curves and points of the scenario's production version."""
from models.io.registry import registry
try:
resolved = registry.resolve(domain, scenario)
_, content = registry.artifact(domain, scenario, resolved.version, "analisis/curvas.json")
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
return jsonify({"simulado": simulated_data(),
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
"mlflow_run_id": resolved.run_id},
"curvas": json.loads(content)})
@blueprint.get("/modelo/desarrollo")
def development():
"""The development stages' tables and figures of the scenario's production version."""
from models.io.registry import registry
try:
resolved = registry.resolve(domain, scenario)
_, content = registry.artifact(domain, scenario, resolved.version, "analisis/desarrollo.json")
except LookupError as error:
return jsonify({"error": f"sin desarrollo: {error}"}), 404
return jsonify({"simulado": simulated_data(),
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
"mlflow_run_id": resolved.run_id},
"desarrollo": json.loads(content)})
@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 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:
_, _, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
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, 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
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():
"""The figure's record of the clinical scenario in the body (`{escenario}`), scored with the production version over the data
ingested so far, and the scenario's risk factors (its summary row, `null` when it has none). 422 with the reason for an
unknown scenario or one too small."""
from models.cama.survival import live
name = (request.get_json(silent=True) or {}).get("escenario")
try:
spec, _, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
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, labelled, name, published)
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
with _LOCK:
_ANSWERS[key] = record
while len(_ANSWERS) > MAX_ANSWERS:
_ANSWERS.popitem(last=False)
row = next((r for r in _summary(domain, scenario, version) if r["escenario"] == name), None)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record, "factores": row})
return blueprint
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, 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")
def recurrence():
from models.cama.recurrence import patient
from models.io.registry import registry
try:
resolved = registry.resolve("cama", "recurrence")
_, content = registry.artifact("cama", "recurrence", resolved.version, "analisis/recurrencia.json")
except LookupError as error:
return jsonify({"error": f"sin recurrencia: {error}"}), 404
record = json.loads(content)
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, hers = None, []
paciente = request.args.get("paciente", "")
if paciente.isdigit():
try:
_, _, labelled, _ = _live_context("cama", "survival")
except LookupError:
labelled = None
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]))
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, "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)
+37 -15
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.
"""
@@ -203,20 +224,20 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
@config.when(with_cohorts=True)
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[tuple[int, bool]]]:
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da a cada estimador de la cohorte
(`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los
riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no
duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. Confirmar o anular un lote es la orden
`confirm-risks`, no este paso.
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
estimadores = ctx.estimators.get(url) or []
if not estimadores:
continue
def frame(sesion, url=url):
@@ -226,8 +247,9 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
if armado_id is None:
continue
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
lotes[url] = []
for estimador in estimadores:
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[url].append(ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos))
return lotes
+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
+27 -30
View File
@@ -1,5 +1,5 @@
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
its domain has in production.
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with every model version
of its domain in production, one batch per model.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
@@ -11,7 +11,6 @@ unused by design.
from dataclasses import dataclass
from importlib import import_module
from typing import Any
@dataclass(frozen=True)
@@ -25,41 +24,35 @@ class Provenance:
return {key: value for key, value in self.__dict__.items() if value}
class Cin2LogisticEstimator:
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to
test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has
something to report when `estimate` calls it."""
class ScenarioEstimator:
"""Scores a domain's cohort with the version of one scenario that is in production (or `version`, to test a
candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has something to
report when `estimate` calls it."""
def __init__(self, domain: str = "cacu", version: str | None = None):
def __init__(self, domain: str, scenario: str, version: str | None = None):
self.domain = domain
self.scenario = scenario
self.version = version
self.desenlace = "cin2_mas"
self.desenlace = ""
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import json
import mlflow.pyfunc
import numpy as np
from models.dags.estimation import estimate_frame
from models.dags.estimation import scored_frame
from models.dags.training import Scenario
from models.io.registry import registered_name, registry
from models.io.storage import KitBuild
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
scenario = Scenario.load(self.domain, "cin2_logistic")
scenario = Scenario.load(self.domain, self.scenario)
build_id = repos.cohort_repository.latest_build(scenario.cohort)
resolved = registry.resolve(self.domain, scenario.scenario, self.version)
frame = KitBuild(self.domain, build_id).frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame))
self.desenlace = scenario.outcome
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))]
return [tuple(row) for row in risk_rows(scored_frame(resolved, frame))]
def procedencia(self) -> Provenance:
if self._provenance is None:
@@ -67,17 +60,21 @@ class Cin2LogisticEstimator:
return self._provenance
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
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`, 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
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {scenario.cohort: Cin2LogisticEstimator(domain)}
found: dict[str, list[ScenarioEstimator]] = {}
for name in registry.in_production(domain):
try:
scenario = Scenario.load(domain, name)
except LookupError:
continue
if not scenario.batch_estimates:
continue
found.setdefault(scenario.cohort, []).append(ScenarioEstimator(domain, name))
return found
+2 -2
View File
@@ -204,8 +204,8 @@ def _tipo_de_valor(resultado: dict, resultado_id: str) -> str:
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.")
if tipo_valor != "codigo" and "valores" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.")
if tipo_valor != "externo" and "sistema" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.")
if tipo_valor not in ("codigo", "externo") and "sistema" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo o externo lleva sistema, no uno de tipo {tipo_valor}.")
if tipo_valor != "numero" and "unidad" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.")
return tipo_valor
+10 -3
View File
@@ -203,13 +203,20 @@ estado = "provisional"
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo"
[cacu.seguimiento.precedencia]
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir).
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de "CASO",
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cinco, sin repetir).
# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo).
valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
valor = ["CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
estado = "provisional"
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
[cacu.seguimiento.caso.grados]
# Qué grados de biopsia hacen de la paciente un caso (ya tiene cáncer, invasor o in situ): su estatus es CASO, gane lo
# que gane lo demás, y lo que se le sigue es la supervivencia. Opciones: grados de `GradoCIN`.
valor = ["CIS", "CARCINOMA"]
estado = "provisional"
fuente = "Responsable del proyecto, 2026-11-22: un escenario para las pacientes que ya tienen cáncer, sobre el que se evalúa la supervivencia; falta que clínica la confirme"
[cacu.seguimiento.colposcopia.evidencias]
# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto):
# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos`
+1 -1
View File
@@ -33,7 +33,7 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"cama",
("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno",
"biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct",
"biopsia.her2", "biopsia.ki67_pct"),
"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"})
+14 -1
View File
@@ -42,6 +42,19 @@ def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]:
return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)]
def con_renglones_unidos(lineas: list[SegmentLine]) -> list[SegmentLine]:
"""The lines and, after them, each pair of consecutive lines of a page joined: a caption that the page wraps ("TAMAÑO
DE LA" / "LESIÓN: 25 MM") is whole in one of them. A value found in both counts as found twice, which doesn't change
which one wins."""
unidas = []
for a, b in zip(lineas, lineas[1:]):
if a.page_number != b.page_number or a.document != b.document:
continue
caja = BBox(min(a.line.bbox.x0, b.line.bbox.x0), a.line.bbox.y0, max(a.line.bbox.x1, b.line.bbox.x1), b.line.bbox.y1)
unidas.append(SegmentLine(a.document, a.page_number, Line(f"{a.line.text} {b.line.text}", caja), a.ocr or b.ocr))
return [*lineas, *unidas]
def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]:
"""The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines."""
try:
@@ -74,7 +87,7 @@ class DesdeTexto:
@lru_cache(maxsize=256)
def extraer(contenido: str | bytes) -> dict[str, tuple]:
lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido)
lineas = con_renglones_unidos(lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido))
leidos = extractor.extract(lineas)
return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos}
+6
View File
@@ -26,6 +26,12 @@ def de_derechohabiente(paciente) -> dict:
}
def con_defuncion(paciente) -> dict:
"""Lo de `de_derechohabiente` y la fecha de defunción, el desenlace de la supervivencia: nula mientras vive o si se
desconoce."""
return {**de_derechohabiente(paciente), "fecha_defuncion": paciente.pac_fecha_defuncion}
def con_sexo(paciente) -> dict:
"""Lo que la persona de TEA agrega: el sexo, como código."""
return {"sexo": codigo(paciente.pac_sexo)}
+5 -4
View File
@@ -4,9 +4,9 @@
- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each
hangs from its order when it has one;
- what the EEG analysis writes: the EEG's verdict and study-wide quality checks (`eeg_criterio` without an
electrode) and each metric with its deviation from the age baseline are results of the EEG's recording, not
procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an electrode are `parte`s of
the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric.
electrode) and each metric with its deviation from the age baseline and the baseline's registered label are results
of the EEG's recording, not procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an
electrode are `parte`s of the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric.
"""
from core.tea.enums import (
@@ -140,7 +140,8 @@ DESDE_STAGING = (
DeStaging(
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
derivadas={"metrica": _metrica},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION}},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION},
"met_modelo": "eeg.{metrica}_modelo"},
),
DeStaging(
EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,

Some files were not shown because too many files have changed in this diff Show More