Compare commits
117 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| af054460b5 | |||
| 6452e43cad | |||
| b0b797ac15 | |||
| 0e6494f053 | |||
| 5831fcd9d9 | |||
| bd8c7aa55a | |||
| 1048175531 | |||
| 5738a9c302 | |||
| bf93a5fff9 | |||
| 32483249c7 | |||
| 93649a0e27 | |||
| 201ef4fb03 | |||
| 05b0ccfce6 | |||
| f97d1202a9 | |||
| eb88cb7eb0 | |||
| 430d165594 | |||
| 74303aa1b9 | |||
| f7f8af8b4c | |||
| 2fe4101982 | |||
| 88c9694a46 | |||
| e0967d0175 | |||
| 377882edd0 | |||
| 1fbeabb872 | |||
| c51402510a | |||
| 7640486852 | |||
| 4a61bd8d33 | |||
| 71557ecbd3 | |||
| e2732f5e8a | |||
| b9795c02ca | |||
| b63a253b19 | |||
| cc54c1dc86 | |||
| 9a62ddcdaf | |||
| f002e24811 | |||
| a04ceb6301 | |||
| 03be05fb17 | |||
| 0c69140d2e | |||
| 1d52da79e4 | |||
| 6d01742a85 | |||
| 8e5a7e3b81 | |||
| d156bf3c99 | |||
| 9461dfbd20 | |||
| 0a8e3577a1 | |||
| e44f0c84b3 | |||
| 4840bd3dc8 | |||
| b7ce3e7ddd | |||
| 4cc2ce83ac | |||
| d185aba364 | |||
| 0edac6d0e2 | |||
| 2c4bfa5691 | |||
| a53179aa2e | |||
| 3b192207fd | |||
| 69d2d0e175 | |||
| 26631bd564 | |||
| 57947d4131 | |||
| eeb4c1fbd5 | |||
| 31ab347347 | |||
| 46473bb106 | |||
| 8b379db28b | |||
| dab78ad55e | |||
| 1a6db9cf6b | |||
| e33eaafb08 | |||
| 2d71fe1103 | |||
| fae6b2232f | |||
| 2ee95576a8 | |||
| 6b011df0fd | |||
| 58d3291804 | |||
| e2ecaa027c | |||
| f34c2b5116 | |||
| 9b617db9d0 | |||
| c2b18d9969 | |||
| d1e06798c9 | |||
| 26f2b35338 | |||
| 0c1b383da2 | |||
| 7d06f9db9d | |||
| 8130f86f3a | |||
| 028f774400 | |||
| ca0f02aa0c | |||
| 7a84cb19c9 | |||
| 5a4baeb33e | |||
| c86c530703 | |||
| 553d25fa54 | |||
| 6b8af821a3 | |||
| d35e8bbae9 | |||
| 7101913fff | |||
| 084fe2e8d3 | |||
| b1bbbc25b4 | |||
| 0571b5e6af | |||
| 0a7234f5ef | |||
| 9737b5a67f | |||
| 854a2e9c55 | |||
| b8045e7481 | |||
| 6dce665d93 | |||
| 73cbf0cfb8 | |||
| 64d3d721e3 | |||
| cea74e1566 | |||
| 113b792a7b | |||
| f183e495fb | |||
| 9775a22c57 | |||
| 7d5c79f520 | |||
| e224b8b2aa | |||
| 205bc214fa | |||
| 4fc822d5c7 | |||
| 73b1db1121 | |||
| ea228da7b4 | |||
| 8f84253205 | |||
| ce67de17bc | |||
| e41a2b7127 | |||
| 59fe94ad97 | |||
| edd12df144 | |||
| 96a29cfb19 | |||
| 7d0213eda7 | |||
| 1710cd5ca2 | |||
| 3c28a43cb1 | |||
| 21e6533dab | |||
| b9adedbf6f | |||
| 0cbe390b25 | |||
| 0f00a975fa |
+17
-8
@@ -4,19 +4,25 @@
|
||||
|
||||
# dbt's manifest: the measures' definitions and the compiled SQL of their event
|
||||
# models. The API serves the measures from it and the indicator cycle creates
|
||||
# the views. Compiling needs no data; the SQL is SQLite's, the image's default
|
||||
# engine.
|
||||
# the views. The manifest built here is SQLite's, the image's default engine;
|
||||
# the same environments compile it again at start-up against MySQL/MariaDB,
|
||||
# PostgreSQL or SQL Server when *_DATABASE_URL points there (docker-entrypoint.sh),
|
||||
# because those adapters open a connection to compile. dbt-mysql needs an
|
||||
# older dbt-core, so it gets an environment of its own.
|
||||
FROM python:3.12-slim AS manifest
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
WORKDIR /app/Transformation
|
||||
COPY Transformation/ ./
|
||||
RUN uv sync && uv run --no-sync dbt compile --profiles-dir . --profile tea
|
||||
RUN uv sync --group sqlite --group sqlserver --group postgres \
|
||||
&& UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql \
|
||||
&& uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect
|
||||
|
||||
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/
|
||||
@@ -44,12 +50,15 @@ 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. On another engine, mount a manifest compiled with that dbt target
|
||||
# and point this at it.
|
||||
COPY --from=manifest /app/Transformation/target/manifest.json /app/Transformation/target/manifest.json
|
||||
# registered. The entrypoint replaces it with one compiled against the
|
||||
# deployment's engine when that engine isn't SQLite (webapi.dbt_manifest).
|
||||
COPY --from=manifest /app/Transformation /app/Transformation
|
||||
ENV DBT_MANIFEST=/app/Transformation/target/manifest.json
|
||||
ENV TRANSFORMATION_DIR=/app/Transformation
|
||||
|
||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||
|
||||
|
||||
@@ -18,13 +18,15 @@ webapi/
|
||||
│ ├── data.py /data: lectura paginada de cada tabla importable
|
||||
│ ├── cacu.py, cama.py, tea.py /<dominio>/indicadores
|
||||
│ ├── reportes.py /reportes: bitácora de importaciones y estado del recálculo
|
||||
│ └── governance.py /governance: versiones de modelos y cola de OCR
|
||||
│ └── governance.py /governance: versiones de modelos, notebooks y cola de OCR
|
||||
├── imports/
|
||||
│ ├── connectors/ una clase por tipo de fuente (@register_connector)
|
||||
│ ├── schemas/ un esquema pydantic por tabla destino; registry.py los enlista
|
||||
│ ├── mapping/ sugerencia de mapeo de columnas
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves, escritura
|
||||
│ │ y aprendizaje de las correcciones de documentos (review_learning.py)
|
||||
│ └── audit.py bitácora agregada (sin datos de pacientes)
|
||||
├── nlp.py python -m webapi.nlp evaluate|train: extracción contra una clave de respuestas
|
||||
├── indicadores.py rutas de indicadores (del equipo de indicadores)
|
||||
├── recomputation.py cola y servicio que recalcula indicadores tras cada carga
|
||||
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
|
||||
@@ -45,7 +47,7 @@ y una entrada en `imports/schemas/registry.py`.
|
||||
| `/data/<dominio>.<Tabla>` | Filas de una tabla importable, paginadas (`limit`, `offset`) |
|
||||
| `/<dominio>/indicadores` | Catálogo de indicadores y, por indicador, `/periodos`, `/datos`, `/metadatos` y `/figuras/<figura>` |
|
||||
| `/reportes` | `GET /reportes/importaciones` (resumen y últimos intentos), `/importaciones/descarga`, `GET /reportes/indicadores`, `POST /reportes/indicadores/<dominio>/recalcular` |
|
||||
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro) y cola de revisión de OCR |
|
||||
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro, descarga de sus archivos), notebooks corridos sobre una cohorte exportada (`/governance/experiments`, `/governance/cohort-files`) y cola de revisión de OCR |
|
||||
| `/health` | Verificación de vida |
|
||||
|
||||
Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
@@ -68,7 +70,17 @@ Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
| `INDICADORES_DESDE`, `INDICADORES_HASTA` | hace 5 años, este año | Años que recalcula el servicio |
|
||||
| `INDICADORES_INTERVALO_S` | `20` | Cada cuánto revisa la cola |
|
||||
| `INDICADORES_AL_INICIAR` | `1` | Recalcular los tres dominios al arrancar |
|
||||
| `EEG_ANALYSIS_CLUSTER` | `auto` | Where TEA's cycle analyses the stored EDFs before loading silver: `auto` (`DASK_SCHEDULER_ADDRESS` if set, otherwise a local Dask cluster), `local`, `remote`, `sync` (in the service's own process) or `off` (only `python -m models tea analyze` and `POST /governance/eeg/run` analyse) |
|
||||
| `PORT`, `WEBAPI_WORKERS`, `WEBAPI_TIMEOUT` | `5000`, `2`, `600` | gunicorn en el contenedor |
|
||||
| `NOTEBOOK_JOBS_DIR` | sin carpeta | Carpeta compartida con el servicio `notebooks`; con ella los notebooks corren aislados en ese contenedor |
|
||||
| `NOTEBOOK_EXECUTOR` | `contenedor` con `NOTEBOOK_JOBS_DIR`, si no `local` | Dónde corren los notebooks; `local` es en el propio proceso, sin aislar (desarrollo) |
|
||||
| `NOTEBOOK_RUNNER_UID` | ninguno | Usuario del contenedor `notebooks`, dueño de cada carpeta de trabajo |
|
||||
| `NOTEBOOK_JOB_TIMEOUT`, `NOTEBOOK_CELL_TIMEOUT` | `21600`, `1800` | Segundos que espera un notebook completo y una celda |
|
||||
| `NOTEBOOK_MAX_IMPORT_MB` | `500` | Tope de archivos que se importan de lo que entrenó un notebook |
|
||||
| `WEBAPI_NOTEBOOK_WORKERS` | `1` | Notebooks a la vez por proceso de la API |
|
||||
| `EXTRACTION_RANKER` | `auto` | Ranker de extracción de documentos: `auto` (el de producción, si no el último), `produccion` (solo el de producción) o `ninguno` |
|
||||
| `EXTRACTION_LEARNING` | `1` | `0` deja de aprender de las correcciones hechas al revisar documentos |
|
||||
| `NOTEBOOK_RENDERER` | `quarto` si está instalado, si no `jupyter` | Con qué se corre y se arma la página |
|
||||
|
||||
## Ejecución
|
||||
|
||||
@@ -83,6 +95,15 @@ uv run python main.py # http://localhost:5050
|
||||
uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal
|
||||
```
|
||||
|
||||
Medir la extracción de documentos contra una clave de respuestas (por documento y
|
||||
destino, el valor correcto de cada campo revisado; `null` si debe quedar vacío)
|
||||
y entrenar con ella el ranker del dominio (`Extraction/README.md`):
|
||||
|
||||
```bash
|
||||
uv run python -m webapi.nlp evaluate --documents carpeta/ --key clave.json [--with-values] [--no-ranker]
|
||||
uv run python -m webapi.nlp train --documents carpeta/ --key clave.json
|
||||
```
|
||||
|
||||
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
|
||||
imagen se construye con `WebApi/Dockerfile` (contexto: la raíz, para copiar
|
||||
los paquetes hermanos); `docker-entrypoint.sh` aplica las migraciones y
|
||||
|
||||
+30
-2
@@ -1,6 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# The notebook runner shares the image but runs with no network, a read-only
|
||||
# system and only the jobs folder (models.reports.notebook_jobs): it never touches /data.
|
||||
if [ "$1" = "notebooks" ]; then
|
||||
exec /app/WebApi/.venv/bin/python -m models notebooks serve
|
||||
fi
|
||||
|
||||
mkdir -p /data
|
||||
|
||||
# SQLite won't create a missing parent directory for its database file.
|
||||
@@ -10,14 +16,36 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER
|
||||
esac
|
||||
done
|
||||
|
||||
cd /app/WebApi
|
||||
|
||||
# dbt's manifest for the deployment's engine: the image's is SQLite's; on
|
||||
# another engine it's compiled now, against the configured databases, into
|
||||
# /data (webapi.dbt_manifest prints the path to use, or nothing to keep the
|
||||
# image's).
|
||||
if compiled="$(uv run --no-sync python -m webapi.dbt_manifest)"; then
|
||||
[ -n "$compiled" ] && export DBT_MANIFEST="$compiled"
|
||||
else
|
||||
echo "dbt manifest: compilation failed; the measure routes will stay unregistered" >&2
|
||||
fi
|
||||
|
||||
# The live indicator worker (webapi.recomputation) shares the image; the
|
||||
# API container runs the migrations, so the worker starts after it.
|
||||
if [ "$1" = "indicadores" ]; then
|
||||
cd /app/WebApi
|
||||
exec uv run --no-sync python -m webapi.recomputation
|
||||
fi
|
||||
|
||||
cd /app/WebApi
|
||||
# One-shot training of the CaCu model on the loaded data (compose profile
|
||||
# `entrenar`): the trained version goes into production and the worker's next
|
||||
# cycle estimates with it. `--source dbt` (dbt's cohort, not the kit's numbered
|
||||
# builds) is required: a PROD run needs its cohort build named (ML-03), and
|
||||
# --export --source dbt is the only way to do that without knowing the build
|
||||
# number ahead of time; it also makes the promotion gate's cohort-link check
|
||||
# portable (tag-based, no live lookup of a local build row), unlike the kit's.
|
||||
if [ "$1" = "entrenar" ]; then
|
||||
exec uv run --no-sync python -m models run cacu cin2_logistic --export --source dbt --manifest "$DBT_MANIFEST" \
|
||||
--environment prod --train --promote
|
||||
fi
|
||||
|
||||
# --no-sync: the environment was synced at build time; syncing at startup
|
||||
# would try to reach the package index (and pull dev deps).
|
||||
for domain in cacu cama tea governance; do
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# CaMa descriptive analysis
|
||||
|
||||
Counts and proportions of the BI-RADS cohort, by group and over time, under `/cama/analisis`. It describes the
|
||||
patients of the cohort; it estimates no incidence, survival or risk. The cohort is the follow-up list's (see
|
||||
`cama-follow-up.md`): each patient through her latest reported mammogram, kept when its BI-RADS is 4 to 6.
|
||||
|
||||
## Routes
|
||||
|
||||
All `GET`, with the selection of the follow-up list (all routes but the trend): `corte` (default today), `meses` (`0` whole cohort, default; `1`, `3`,
|
||||
`6`, `12`), the filters `birads`, `grupo_edad` and `biopsia`, and the context `cohorte`, `escenario`, `revision` together.
|
||||
Unknown, repeated or empty parameters are a 400. The trend takes only `corte`, `tipo` and `periodos`: a window, a filter or the cohort
|
||||
context sent to it is a 400, never ignored.
|
||||
|
||||
| Route | Own parameters | Answers |
|
||||
| --- | --- | --- |
|
||||
| `/cama/analisis` | | Dimensions with their options, measures, horizons (30, 90, 180, 365 days), period types, sections and the analyses that are not available, each with its reason |
|
||||
| `/cama/analisis/resumen` | `horizonte` (default 90) | The indicator cards |
|
||||
| `/cama/analisis/distribucion` | `por`: `birads`, `grupo_edad`, `biopsia` | Patients per category: count, share and its Wilson interval, and the filter that opens them in the list |
|
||||
| `/cama/analisis/comparacion` | `por`: `birads`, `grupo_edad`; `medida`: `maligno` (default), `invasor` | Per group, cases among the patients with a known biopsy result, its interval, and the chi-square test of homogeneity |
|
||||
| `/cama/analisis/mapa` | `filas`, `columnas` (two different of `birads`, `grupo_edad`); `medida` | Cells of the two crossed: patients and the share of cases |
|
||||
| `/cama/analisis/tendencia` | `tipo`: `mes`, `semestre`; `periodos`: 1 to 36 (12 months, 6 semesters by default) | Reports of mammogram and biopsy per period and the share of malignant results; general activity, not the cohort |
|
||||
| `/cama/analisis/indicadores` | | The cohort's patients by BI-RADS category, with `simulado: true` (the aggregate the tab has always read); a category is published only from the threshold, so an empty one is not published either |
|
||||
|
||||
Every answer carries `cohorte`, `escenario`, `revision`, `corte`, `ventana`, `filtros` and `umbral_supresion`, and only
|
||||
`/indicadores` carries `simulado`. Errors as in the list: 400, 403 (`motivo: supresion`), 409 (`motivo: revision`) and 503
|
||||
(`motivo: cohorte`, the cohort view is missing).
|
||||
|
||||
A proportion is `{estado, casos, total, valor, ic_bajo, ic_alto}` with values in percent; `estado` is `disponible`,
|
||||
`suprimido` or `sin_datos` (nobody in the denominator). An item with `seleccion` gives the list's filters that open its
|
||||
patients; the page adds the selection's own filters.
|
||||
|
||||
## Definitions (working conventions, for review)
|
||||
|
||||
* **Result** of a patient: the grade of the biopsy the list shows (latest report at the cut-off); `SIN_BIOPSIA` without a
|
||||
report, `SIN_DATO` for a report without a grade. **Known**: benign, in situ or invasive. **Malignant**: a grade in
|
||||
`cama.biopsia_cancer`; **invasive**: `CARCINOMA_INVASOR`.
|
||||
* **Cards.** Cohort (patients). With a biopsy report: of the cohort. Malignant and invasive among the known results: not
|
||||
an incidence, the denominator is patients already biopsied. Biopsy reported within `h` days and malignant result within
|
||||
`h` days of the mammogram: of the cohort's mammograms that have had `h` days by the cut-off (a recent one isn't read as
|
||||
one without a biopsy); the earliest report counts. Days from the mammogram to the first biopsy report: median and
|
||||
quartiles (linear interpolation) among the patients with a report, from five of them.
|
||||
* **Comparison and map.** The proportion's denominator is the patients with a known result; the test needs two or more
|
||||
published groups and every expected count of at least 5, otherwise it says why it is not given.
|
||||
* **Trend.** General activity, not the cohort. It counts reports (`unidad: "reportes"`), not patients: each mammogram report
|
||||
with a BI-RADS and each biopsy report in its period, over every patient; a patient with several reports counts several
|
||||
times. It depends only on `corte`, `tipo` and `periodos`, so it doesn't change with the window or filters of the other
|
||||
sections, and its answer carries no cohort, revision, window or filters. Biopsies: only those that can be linked to a
|
||||
mammogram with a reported BI-RADS (mammogram, order, report); a biopsy without a linked mammogram isn't counted
|
||||
(`alcance_biopsias`). The share is malignant among the biopsy reports with a known grade. The period the cut-off falls in is
|
||||
marked `incompleto`. Counts and shares are descriptive: no test is applied, because reports of one patient aren't
|
||||
independent. The answer needs the cohort view (503 without it) and a `corte` not after today.
|
||||
* **Intervals.** Wilson, 95 %. Shares of the selection (distribution) are descriptive proportions of the patients.
|
||||
|
||||
## Suppression
|
||||
|
||||
Same threshold as the list (`comun.umbral_supresion`, 5). Applied here as:
|
||||
|
||||
* A count of 1 to 4 is never published. A hidden cell takes the smallest published one of its line with it, until the
|
||||
hidden patients are at least 5, so a published total minus the published cells gives nothing away. Tables do the same
|
||||
along every row and column. Zero is published.
|
||||
* A proportion is published only when its group, its cases and its non-cases are each zero or at least 5.
|
||||
* A period's total is published from 5 reports.
|
||||
* The selection itself follows the list's rule (a window or filter that selects 1 to 4 patients is a 403).
|
||||
|
||||
Residual risk: the list shows individual rows of every selection it allows, so what an aggregate hides can be read from
|
||||
the list. The rule bounds the aggregates, not the list.
|
||||
|
||||
## Not available
|
||||
|
||||
Survival, recurrence, treatment adherence, time-to-event curves (cumulative incidence, Kaplan-Meier), hazard ratios, log-rank
|
||||
and restricted mean survival, and BRCA, stage and tumour size. The sources hold no vital status, recurrence, treatment or
|
||||
follow-up visits, and a patient without the event is not known to have been followed: censoring and a common time zero
|
||||
cannot be established. In the synthetic data every malignant biopsy report falls 12 to 42 days after its mammogram, so a
|
||||
24-month curve would be an extrapolation of a diagnostic work-up, not a follow-up.
|
||||
@@ -0,0 +1,94 @@
|
||||
# CaMa follow-up list
|
||||
|
||||
Patient-level list of the BI-RADS cohort, and the file of the same selection. Every response carries
|
||||
`simulado: true`: the list is for synthetic data and local use. Who may read it on real data is an access rule that does
|
||||
not exist yet; nothing here authorizes it.
|
||||
|
||||
## Routes
|
||||
|
||||
`GET /cama/seguimiento` and `GET /cama/seguimiento/exportacion` (the second takes no `page` or `page_size`).
|
||||
|
||||
Compatibility with dev: `GET /cama/pacientes/<pac_id>` accepts the same selection as the export and returns
|
||||
`item` instead of `items`. It applies suppression to the full selection before locating the patient (404 when absent),
|
||||
and uses the list's revision. The existing optional `CAMA_COHORT_ACCESS` callback is honored on the new follow-up
|
||||
and analysis routes; no new authentication mechanism is introduced. `cama_analysis_legacy` retains the former
|
||||
blueprints for explicit consumers, while `create_app` registers only the new routes, without duplicates.
|
||||
|
||||
| Parameter | Meaning |
|
||||
| --- | --- |
|
||||
| `corte` | Cut-off date `AAAA-MM-DD`, not after today. Default: today. |
|
||||
| `meses` | Window: `0` (the whole cohort, from its earliest mammogram), `1`, `3`, `6` or `12`. Default: `3`. |
|
||||
| `page`, `page_size` | From 1; `page_size` from 1 to 200 (default 50). List only. |
|
||||
| `birads`, `grupo_edad`, `biopsia` | Filters, combined with AND. The values are in `filtros_disponibles`. |
|
||||
| `cohorte`, `escenario`, `revision` | The context of an earlier answer, the three together. |
|
||||
|
||||
Unknown, repeated or empty parameters are a 400, before anything is counted.
|
||||
|
||||
Response: `simulado`, `cohorte` (`cama_birads_v1`), `escenario` (`diagnostico`), `revision`, `corte`,
|
||||
`ventana` (`meses`, `desde`, `hasta`), `filtros` (each filter, `null` when not applied), `filtros_disponibles`,
|
||||
`columnas`, `paginacion` and `items`; the file has `total_items` instead of `paginacion`. Each item has `pac_id` (the
|
||||
platform's key as decimal text), `grupo_edad`, `birads`, `mastografia_fecha`, `biopsia` and `biopsia_fecha`. Nothing
|
||||
else: no status, priority, days to diagnosis or prognosis, because the data holds none of them.
|
||||
|
||||
| Code | When |
|
||||
| --- | --- |
|
||||
| 400 | A parameter outside the contract, or the context without all three parts |
|
||||
| 403 | The selection has fewer patients than `comun.umbral_supresion` (`motivo: supresion`) |
|
||||
| 404 | A page past the last one, with patients |
|
||||
| 409 | The cohort, scenario or revision quoted is not the one the server holds (`motivo: revision`) |
|
||||
| 413 | A file of more than 5000 patients |
|
||||
| 503 | The cohort view is missing: the indicator cycle that creates the event views hasn't run (`motivo: cohorte`) |
|
||||
|
||||
## The cohort
|
||||
|
||||
`cama_cohorte_birads` (dbt, `models/cama/gold/seguimiento`) holds one row per mammogram with a reported BI-RADS and each
|
||||
biopsy report that mammogram led to. A view takes no parameter, so the cut-off is applied by `webapi.cama_follow_up`:
|
||||
|
||||
* A patient counts once, through her latest mammogram whose report is dated on or before the cut-off (date taken, then
|
||||
source id, then report date, then report id: the same data always gives the same cohort).
|
||||
* She is in the cohort when that BI-RADS is one of `cama.birads_4_a_6`.
|
||||
* The biopsy shown is the latest report of a biopsy that mammogram led to, dated on or before the cut-off and not before
|
||||
the mammogram. `SIN_BIOPSIA`: none; `SIN_DATO`: a report without a result.
|
||||
* The age group is `cama.grupos_edad` at the cut-off; `SIN_DATO` without a birth date.
|
||||
* Facts are read as silver holds them now. The list is not a reconstruction of what was known on the cut-off.
|
||||
|
||||
## Suppression
|
||||
|
||||
A selection (window and filters applied) of 1 to `umbral_supresion` - 1 patients is never served, as a page or as a file.
|
||||
A selection with a window or a filter and no patients is refused alike, so a refusal never tells a small group from an
|
||||
empty one. The whole cohort (window `0`, no filter) is the only selection that can be empty. Combinations of window and
|
||||
filters are evaluated on the final selection, so they cannot isolate a small group. The file applies the same rule.
|
||||
|
||||
## Revision
|
||||
|
||||
`sha256(cohorte | version | construcción | corte)`. The build is the last load that added or changed rows
|
||||
(`carga-<id>`): a recalculation that changes nothing keeps it, new data changes it. A client that quotes another
|
||||
revision gets a 409.
|
||||
|
||||
## Limits of the revision and of concurrent writes
|
||||
|
||||
The revision pins the cohort, its version, the last load that added or changed rows and the cut-off. It is a marker, not a
|
||||
snapshot: nothing keeps the previous cohort. While no load writes, every page and the file of one selection come from the
|
||||
same data, so pages concatenate to the file and repeated requests give the same answer. A load that adds or changes rows
|
||||
between two requests changes the build, and the next request that quotes the old revision is a 409. A load that is still
|
||||
running when a request arrives is not detected until it records its rows. Until snapshots exist, run reads and files with no
|
||||
concurrent writes.
|
||||
|
||||
Two contradictory facts are resolved the same way whatever the row order: a report with two different BI-RADS counts
|
||||
through the more severe (`cama.birads_gravedad`), and a biopsy report with two grades on the same date through the more
|
||||
severe grade (benign, in situ, invasive). The synthetic data holds no such duplicates.
|
||||
|
||||
## Provisional decisions
|
||||
|
||||
These are working conventions for review, not clinical definitions.
|
||||
|
||||
1. Individual lists are served in the local environment with synthetic data only; the routes are registered like CaCu's and
|
||||
marked `simulado`, with no access rule.
|
||||
2. Threshold of 5 (`comun.umbral_supresion`, itself provisional).
|
||||
3. The cohort rule above (latest reported mammogram, BI-RADS 4 to 6) and the biopsy that is shown.
|
||||
4. The knowledge cut-off is the present: a mammogram or a biopsy loaded after the cut-off date still counts if its own date
|
||||
is on or before it. Data loaded today would otherwise make every earlier cut-off empty.
|
||||
5. Age groups and the BI-RADS list come from the platform parameters, not from this module.
|
||||
6. Residual risk: the suppression rule bounds the size of each selection, not the differences between selections. Two
|
||||
allowed selections can still reveal a small remainder by subtraction. Rows of allowed selections are individual
|
||||
records by design.
|
||||
@@ -0,0 +1,59 @@
|
||||
# CaMa: tasa de detección, resultado a diagnóstico y resultado histopatológico por BI-RADS
|
||||
|
||||
Tres medidas FHIR de CaMa, calculadas a pedido desde la capa semántica de dbt como las demás (`GET /cama/fhir/Measure`,
|
||||
`GET /cama/fhir/MeasureReport?measure=<canónico>&tipo-periodo=<semestre|mes>`). Sus definiciones son convenciones de
|
||||
trabajo, no definiciones clínicas aprobadas; los analistas deben confirmarlas (ver `INFORME_L3_RESUMEN_HISTORICO_CAMA.md`).
|
||||
|
||||
| Medida | Contrato | Unidad | Modelo de eventos (vista) |
|
||||
| --- | --- | --- | --- |
|
||||
| `CAMA-TASA-DETECCION-HISTOPATOLOGICA` | C1 (proporción) | reporte de biopsia | `cama_deteccion_biopsia` |
|
||||
| `CAMA-DIAS-RESULTADO-DIAGNOSTICO` | C3r (duración) | mastografía con reporte | `cama_resultado_diagnostico` |
|
||||
| `CAMA-HISTOPATOLOGIA-BIRADS` | C2 por BI-RADS (composición) | paciente | `cama_resultado_biopsia` |
|
||||
|
||||
## Tasa de detección histopatológica
|
||||
|
||||
* Unidad: el **reporte de biopsia**, fechado por su reporte (`fecha_reporte`) y conocido al inicio de la carga que lo escribió.
|
||||
* Denominador: reportes con resultado conocido (`BENIGNO`, `CARCINOMA_IN_SITU`, `CARCINOMA_INVASOR`); un reporte sin grado, o con
|
||||
un grado que el catálogo no conoce, no entra. Numerador: los de `CARCINOMA_IN_SITU` o `CARCINOMA_INVASOR`.
|
||||
* Las marcas `con_resultado` y `maligno` son de la vista y salen de las variables de dbt `cama.biopsia_gravedad` y
|
||||
`cama.grados_cancer` (esta última, igual a la regla `cama.biopsia_cancer` de `parametros.toml`; una prueba lo verifica). Así la
|
||||
medida no necesita reglas nuevas en la tabla de parámetros de una base ya instalada.
|
||||
* **No** es la tasa de detección de CaCu (`CACU_EU13`: pacientes con lesión confirmada entre las tamizadas), **ni** la
|
||||
proporción de confirmación de CaMa (`CAMA_CONFIRMACION_BIRADS45`: mastografías de sospecha con biopsia reportada), **ni** una
|
||||
proporción dentro de la cohorte de Seguimiento. Es la proporción de resultados malignos entre las biopsias con resultado.
|
||||
|
||||
## Tiempo de resultado a diagnóstico
|
||||
|
||||
* Una fila por mastografía con reporte, fechada por el reporte. Observación: días naturales del reporte a la **primera nota
|
||||
diagnóstica de la paciente con fecha igual o posterior al reporte**, dentro del horizonte (`horizonte_toma_diagnostico_dias`,
|
||||
180) y a la fecha de corte. Nota diagnóstica: un diagnóstico CIE-10 de `cama.cie_diagnostico` escrito por una especialidad de
|
||||
`cama.especialidades_diagnostico` (la misma que usa `CAMA_DIAS_TOMA_DIAGNOSTICO`).
|
||||
* Si una toma tiene varios reportes, se selecciona el primero por `fecha_reporte`, después `reporte_id` y
|
||||
`reporte_carga_id`. Una toma aporta una observación y pertenece al periodo de ese reporte; las correcciones posteriores
|
||||
no crean otra observación. La nota se busca desde ese reporte seleccionado. El horizonte es semiabierto:
|
||||
se admiten 0 a 179 días; el día 180 ya queda fuera. La unidad usa `procedimiento_id`, igual que la identidad del reporte
|
||||
en la tasa de biopsias; `fuente_id` puede repetirse entre fuentes.
|
||||
* La nota es de la paciente: **no está ligada a la mastografía** (las notas no traen episodio) **y no es la fecha de la biopsia**.
|
||||
* Una mastografía sin nota dentro del horizonte no se mide; se cuenta como excluida solo cuando su horizonte ya pasó (la misma
|
||||
regla que `CAMA_EU38A`). Se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.
|
||||
* Misma nota que el tiempo de la toma al diagnóstico: cuando la primera nota es posterior al reporte, los días desde el reporte
|
||||
son los de la toma menos los de la toma al reporte.
|
||||
|
||||
## Resultado histopatológico por categoría BI-RADS
|
||||
|
||||
* Una paciente por periodo (periodo de la toma): su mastografía **más grave** del periodo con reporte a la fecha de corte, la misma
|
||||
regla de `CAMA_BIRADS456_PACIENTE` (así las dos tarjetas del Resumen cuentan las mismas pacientes). Solo cuenta si ese BI-RADS
|
||||
está en `cama.birads_4_a_6`.
|
||||
* Resultado: el grado de la biopsia más grave que esa mastografía originó y que se reportó a la fecha de corte (entre iguales, la
|
||||
más reciente); `SIN_BIOPSIA` si no hay ninguna reportada al corte; `SIN_DATO` si la biopsia no trae grado.
|
||||
* El reporte publica el cruce BI-RADS × resultado como un estratificador con dos componentes (`birads`, `biopsia_grado`), además del
|
||||
estratificador de categorías. Solo se listan las celdas con pacientes; las demás son cero.
|
||||
* La categoría «lesión de riesgo (B3)» de la maqueta no existe en las fuentes (los grados son benigno, in situ e invasor): no se
|
||||
publica ni se inventa.
|
||||
|
||||
## Corrección en el cálculo de composiciones
|
||||
|
||||
La biopsia que sigue a la mastografía elegida se compara con la fecha de conocimiento (`corte_conocimiento`) como fecha y hora. Antes,
|
||||
la columna de esa fecha se leía como texto y, con el corte de conocimiento en el mismo día de la carga, la comparación daba falso y
|
||||
toda paciente quedaba «sin biopsia». Afectaba a toda composición con seguimiento (CaCu: `CACU_CONFIRMACION_CITOLOGIA`) cuyos
|
||||
reportes aún no estuvieran guardados; los ya guardados no cambian hasta que se recalculen.
|
||||
@@ -0,0 +1 @@
|
||||
2026-11-22T10:18:21+00:00
|
||||
+7
-2
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"models[export]",
|
||||
"models[notebooks,survival-curves,seer-survival]",
|
||||
"extraction",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
@@ -20,6 +20,11 @@ dependencies = [
|
||||
"gunicorn>=23.0",
|
||||
"sqlglot>=25.0",
|
||||
"rapidfuzz>=3.9",
|
||||
"watchdog>=6.0",
|
||||
# Every FHIR answer is validated against R4B's models before it leaves (`webapi.fhir.common`).
|
||||
"fhir-resources>=8.3",
|
||||
# The EEG quality checks' code system and interpretations in TEA's FHIR answers (`webapi.fhir.tea`, `webapi.fhir.terminology`).
|
||||
"tea",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -33,6 +38,7 @@ sql-drivers = [
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
tea = { path = "../models/libs/tea", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
@@ -43,7 +49,6 @@ packages = ["webapi"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"fhir-resources>=8",
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -31,6 +31,10 @@ os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postg
|
||||
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
||||
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
||||
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
|
||||
# Extraction ranks by confidence and learns nothing unless a test sets up a
|
||||
# model registry of its own (test_review_learning.py).
|
||||
os.environ.setdefault("EXTRACTION_RANKER", "ninguno")
|
||||
os.environ.setdefault("EXTRACTION_LEARNING", "0")
|
||||
|
||||
ANIO = 2025
|
||||
|
||||
|
||||
+18
-8
@@ -16,9 +16,9 @@ armado = [
|
||||
]
|
||||
lote_final = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, fecha_indice = 2025-08-01, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
|
||||
[[caso]]
|
||||
@@ -34,6 +34,16 @@ incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el periodo es el de la fecha índice del riesgo, no la del miembro"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-09-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
espera."2025-S2" = { "cat:BAJO" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "los cortes son parámetros"
|
||||
incluye = ["armado", "lote_final"]
|
||||
@@ -46,7 +56,7 @@ nombre = "un lote preliminar más nuevo no desplaza al vigente"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
|
||||
|
||||
@@ -54,7 +64,7 @@ espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
|
||||
nombre = "una evaluación anulada en su versión 2 queda sin dato"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
|
||||
|
||||
@@ -63,7 +73,7 @@ nombre = "una evaluación a otro horizonte no cuenta"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
@@ -72,7 +82,7 @@ nombre = "sin lote confirmado no hay población"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
@@ -82,6 +92,6 @@ filas = [
|
||||
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
|
||||
+43
-1
@@ -20,12 +20,18 @@ reporte y grado, y una solicitada que todavía no lo tiene.
|
||||
Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
Texts the silver load reads results from (`TEXTOS`, `INFORME_DE_PATOLOGIA`, `DIAGNOSTICO_DE_NOTA`):
|
||||
H-003's B4A carries density C and a 14 mm lesion, its biopsy a PDF with an invasive ductal carcinoma, grade 2,
|
||||
ER+ 90 %, PR- 0 %, HER2 3+ and Ki-67 25 %, and its oncology note stage IIA. H-101's first mammography says
|
||||
density "tipo E", which the catalog doesn't know: it stays as source text, out of catalog.
|
||||
|
||||
H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`:
|
||||
lo único común entre los dos sistemas es `pac_id_hospital`.
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
import io
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
@@ -69,6 +75,39 @@ NOTAS = (
|
||||
("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta
|
||||
)
|
||||
|
||||
# Index in MASTOGRAFIAS -> the radiologist's interpretation.
|
||||
TEXTOS = {
|
||||
0: "Densidad mamaria: tipo E\nSin hallazgos.",
|
||||
4: "Densidad mamaria: heterogéneamente densas (C).\nNódulo irregular en CSE.\nTamaño de la lesión: 14 mm.",
|
||||
}
|
||||
# Index in BIOPSIAS -> the lines of its pathology report, as a PDF with a text layer.
|
||||
INFORME_DE_PATOLOGIA = {
|
||||
1: (
|
||||
"DIAGNÓSTICO: Carcinoma ductal infiltrante",
|
||||
"Grado histológico: 2 (moderadamente diferenciado)",
|
||||
"Receptores de estrógeno: Positivo (90%)",
|
||||
"Receptores de progesterona: Negativo (0%)",
|
||||
"HER2: 3+",
|
||||
"Ki-67: 25%",
|
||||
),
|
||||
}
|
||||
# Patient -> the diagnosis text of their note.
|
||||
DIAGNOSTICO_DE_NOTA = {"H-003": "Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)"}
|
||||
|
||||
|
||||
def pdf_de(lineas) -> bytes:
|
||||
"""A one-page PDF with these lines as its text layer."""
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
hoja = canvas.Canvas(buffer, pagesize=letter)
|
||||
for i, linea in enumerate(lineas):
|
||||
hoja.drawString(72, 720 - 18 * i, linea)
|
||||
hoja.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía.
|
||||
ORDENES = (
|
||||
@@ -141,11 +180,12 @@ def insertar(sesion: Session) -> None:
|
||||
mast_calidad_imagen=calidad,
|
||||
mast_birads=birads,
|
||||
mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7),
|
||||
mast_interpretacion=TEXTOS.get(indice),
|
||||
)
|
||||
)
|
||||
sesion.add_all(mastografias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
for numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS):
|
||||
mastografia = mastografias[indice]
|
||||
sesion.add(
|
||||
BiopsiaMama(
|
||||
@@ -155,6 +195,7 @@ def insertar(sesion: Session) -> None:
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_grado_histologico=grado,
|
||||
bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[numero]) if numero in INFORME_DE_PATOLOGIA else None,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
@@ -165,6 +206,7 @@ def insertar(sesion: Session) -> None:
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
nm_diagnostico_texto=DIAGNOSTICO_DE_NOTA.get(hospital) if especialidad == ONCOLOGIA else None,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
|
||||
+47
-26
@@ -17,7 +17,8 @@ with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first
|
||||
step is dated by the note, so it reaches EEG on 2 Jun and leaves after June.
|
||||
- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else.
|
||||
|
||||
Every EEG's quality criteria are written as its analysis would; a bad EEG has one criterion out of its threshold.
|
||||
Every EEG's verdict and quality checks are written as its analysis would: a good EEG has its study-wide checks
|
||||
within their limits; a bad one has too few clean windows and a dead channel (T3).
|
||||
|
||||
Test support: writes in the session it's given, never in the domain's database.
|
||||
"""
|
||||
@@ -27,6 +28,7 @@ from datetime import date
|
||||
from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegCriterio,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
@@ -75,10 +77,22 @@ NOTAS = (
|
||||
(6, date(2025, 6, 2), "F84.0"),
|
||||
)
|
||||
|
||||
GOOD = {"amplitud": 0, "alta_frecuencia": 1, "correlacion": 0, "sin_senal": 0, "linea": 3.5}
|
||||
BAD = {**GOOD, "sin_senal": 5}
|
||||
# The analysis's verdict, triage level, clean fraction, bad channels and line noise, and its checks:
|
||||
# (code, electrode, value, text, unit, low, high, decisive, abnormal).
|
||||
GOOD = {"valido": 1, "nivel": "completo", "limpia": 0.95, "malos": 0, "linea": 3.5, "criterios": (
|
||||
("clean-windows", None, 95.0, None, "%", 60.0, None, 1, 0),
|
||||
("usable-scalp", None, 19.0, None, "electrodes", 12.0, None, 1, 0),
|
||||
("triage-level", None, None, "completo", None, None, None, 1, 0),
|
||||
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
|
||||
)}
|
||||
BAD = {"valido": 0, "nivel": "parcial", "limpia": 0.4, "malos": 1, "linea": 3.5, "criterios": (
|
||||
("dead-channel", "T3", None, "dead channel", None, None, None, 0, 1),
|
||||
("clean-windows", None, 40.0, None, "%", 60.0, None, 1, 1),
|
||||
("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, 1, 0),
|
||||
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
|
||||
)}
|
||||
|
||||
# (eeg id, pac_id, date, laboratory id, criteria, with sleep)
|
||||
# (eeg id, pac_id, date, laboratory id, analysis, with sleep)
|
||||
EEGS = (
|
||||
("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0),
|
||||
("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1),
|
||||
@@ -87,30 +101,32 @@ EEGS = (
|
||||
("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1),
|
||||
)
|
||||
|
||||
# (metric id, eeg id, code, value): a null value can't be evaluated.
|
||||
# (metric id, eeg id, code, value, deviation): a null value can't be evaluated. The deviation is the analysis's
|
||||
# against the metric's age baseline: (z, -1/0/+1, p5, median, p95). Child 1's slow posterior rhythm is below p5.
|
||||
METRICAS = (
|
||||
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2),
|
||||
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0),
|
||||
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4),
|
||||
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0),
|
||||
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5),
|
||||
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None),
|
||||
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6),
|
||||
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2, (-4.08, -1, 4.5, 5.75, 7.0)),
|
||||
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0, (-0.5, 0, 2.5, 4.5, 6.5)),
|
||||
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4, (-0.4, 0, 0.0, 0.5, 1.0)),
|
||||
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0, (-6.0, -1, 4.5, 5.75, 7.0)),
|
||||
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5, (0.4, 0, 5.0, 6.25, 7.5)),
|
||||
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None, (None, None, None, None, None)),
|
||||
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6, (0.27, 0, 1.75, 2.5, 3.25)),
|
||||
)
|
||||
|
||||
# (electrode value id, metric id, electrode, z-score)
|
||||
# (electrode value id, metric id, electrode, value, z-score)
|
||||
ELECTRODOS = (
|
||||
("mel-1", "met-1b-rp", "O1", -2.8),
|
||||
("mel-2", "met-1b-rp", "O2", -2.4),
|
||||
("mel-3", "met-1b-rp", "Pz", -1.1),
|
||||
("mel-1", "met-1b-rp", "O1", 3.0, -2.8),
|
||||
("mel-2", "met-1b-rp", "O2", 3.1, -2.4),
|
||||
("mel-3", "met-1b-rp", "Pz", 3.6, -1.1),
|
||||
)
|
||||
|
||||
# The EEG of child 1 that completes the chain hangs from an order.
|
||||
ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),)
|
||||
ORDEN_DE = {"eeg-1b": "ord-1b"}
|
||||
|
||||
# What the load gives (`test_orquestacion_plata`).
|
||||
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS)
|
||||
# What the load gives (`test_orquestacion_plata`): a bad channel is a part of its EEG, as an electrode value is.
|
||||
CANALES_MALOS = sum(1 for *_, analisis, _ in EEGS for c in analisis["criterios"] if c[1] is not None)
|
||||
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS) + CANALES_MALOS
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
@@ -126,14 +142,19 @@ def insertar(sesion: Session) -> None:
|
||||
ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items))
|
||||
sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c)
|
||||
for k, (p, f, c) in enumerate(NOTAS, 1))
|
||||
for i, p, f, lab, criterios, sueno in EEGS:
|
||||
for i, p, f, lab, analisis, sueno in EEGS:
|
||||
sesion.add(Eeg(
|
||||
eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i),
|
||||
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0,
|
||||
eeg_canales_amplitud=criterios["amplitud"], eeg_canales_alta_frecuencia=criterios["alta_frecuencia"],
|
||||
eeg_canales_correlacion=criterios["correlacion"], eeg_canales_sin_senal=criterios["sin_senal"],
|
||||
eeg_ruido_linea_db=criterios["linea"],
|
||||
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=analisis["valido"],
|
||||
eeg_nivel=analisis["nivel"], eeg_fraccion_limpia=analisis["limpia"], eeg_canales_malos=analisis["malos"],
|
||||
eeg_ruido_linea_db=analisis["linea"],
|
||||
))
|
||||
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v) for i, e, c, v in METRICAS)
|
||||
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v)
|
||||
for i, m, e, v in ELECTRODOS)
|
||||
sesion.add_all(EegCriterio(cri_id=f"cri-{i}-{k}", cri_eeg_id=i, cri_codigo=c, cri_electrodo=e, cri_valor=v,
|
||||
cri_valor_texto=t, cri_unidad=u, cri_bajo=lo, cri_alto=hi, cri_decisivo=d,
|
||||
cri_anormal=a)
|
||||
for k, (c, e, v, t, u, lo, hi, d, a) in enumerate(analisis["criterios"], 1))
|
||||
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v, met_z=z, met_fuera=fuera, met_p5=p5,
|
||||
met_mediana=mediana, met_p95=p95)
|
||||
for i, e, c, v, (z, fuera, p5, mediana, p95) in METRICAS)
|
||||
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v, mel_z=z)
|
||||
for i, m, e, v, z in ELECTRODOS)
|
||||
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
@@ -0,0 +1,258 @@
|
||||
"""What this module covers: the routes of CaMa's descriptive analysis (`/cama/analisis`) over the same invented CaMa database
|
||||
as the follow-up list: contract, selection and suppression shared with the list, consistency between the endpoints,
|
||||
states without data, validation and the trend by period.
|
||||
|
||||
Fixtures: `base` and `app`, a CaMa database loaded from `test_cama_follow_up.insertar` (17 invented patients, 15 in the
|
||||
BI-RADS cohort at 2025-12-31) through the cycle up to `event_models`, behind a Flask app with the analysis and follow-up
|
||||
blueprints; needs `DBT_MANIFEST`. The calculations themselves are checked, with exact counts, in
|
||||
`test_cama_analysis_calculations.py`.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlmodel import Session
|
||||
|
||||
from conftest import base_de
|
||||
from test_cama_follow_up import CORTE, UNTIL_MODELS, insertar
|
||||
from webapi.cama_analysis.routes import analysis_blueprint
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
|
||||
base = base_de("cama", tmp_path_factory.mktemp("cama_analisis"), datos=insertar)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(base):
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
|
||||
flask.register_blueprint(analysis_blueprint(lambda: Session(base.motor)), url_prefix="/cama/analisis")
|
||||
return flask.test_client()
|
||||
|
||||
|
||||
def get(app, ruta, **params):
|
||||
return app.get("/cama/analisis" + ruta, query_string={"corte": CORTE, "meses": 0, **params})
|
||||
|
||||
|
||||
def tend(app, **params):
|
||||
"""The trend takes only the cut-off: no window, no filters."""
|
||||
return app.get("/cama/analisis/tendencia", query_string={"corte": CORTE, **params})
|
||||
|
||||
|
||||
def test_the_catalog_lists_what_the_analysis_offers_and_what_it_cannot_calculate(app):
|
||||
"""Pins down: the catalog names the dimensions with their options, the measures, the horizons, the five sections and the
|
||||
analyses that are not available with their reasons, and carries the cohort context. Fails if the tab is given
|
||||
something to draw that has no endpoint, or an unavailable analysis loses its reason."""
|
||||
c = get(app, "").get_json()
|
||||
assert [d["clave"] for d in c["dimensiones"]] == ["birads", "grupo_edad", "biopsia"]
|
||||
assert c["horizontes_dias"] == [30, 90, 180, 365] and c["tipos_periodo"] == ["mes", "semestre"]
|
||||
assert [s["clave"] for s in c["secciones"]] == ["resumen", "distribucion", "comparacion", "mapa", "tendencia"]
|
||||
assert {x["clave"] for x in c["no_disponibles"]} >= {"supervivencia", "recaida", "curvas_tiempo_a_evento"}
|
||||
assert c["cohorte"] == "cama_birads_v1" and re.fullmatch(r"[0-9a-f]{64}", c["revision"]) and c["umbral_supresion"] == 5
|
||||
assert "simulado" not in c
|
||||
|
||||
|
||||
def test_the_cards_distribution_list_and_legacy_aggregate_agree_on_who_is_in_the_cohort(app):
|
||||
"""Pins down: the cohort card, the total of the distribution by each dimension, the list's total and the legacy aggregate's
|
||||
categories all describe the same 15 patients, under one revision. Fails if two parts of the tab count different patients."""
|
||||
resumen = get(app, "/resumen").get_json()
|
||||
total = next(i for i in resumen["indicadores"] if i["clave"] == "cohorte")["valor"]
|
||||
lista = app.get("/cama/seguimiento", query_string={"corte": CORTE, "meses": 0}).get_json()
|
||||
assert total == lista["paginacion"]["total_items"] == 15
|
||||
for por in ("birads", "grupo_edad", "biopsia"):
|
||||
d = get(app, "/distribucion", por=por).get_json()
|
||||
assert d["total"] == 15 and d["revision"] == resumen["revision"] == lista["revision"]
|
||||
publicados = sum(i["n"] for i in d["items"] if not i["suprimido"])
|
||||
assert publicados <= 15
|
||||
legado = get(app, "/indicadores").get_json()
|
||||
por_birads = {i["codigo"]: i for i in get(app, "/distribucion", por="birads").get_json()["items"]}
|
||||
# The legacy contract publishes a category only from the threshold, so an empty one reads as not published.
|
||||
assert {g["codigo"]: g["n"] for g in legado["grupos"]} == {c: (i["n"] or None) for c, i in por_birads.items()}
|
||||
assert all(g["n"] is None or g["n"] >= legado["umbral_supresion"] for g in legado["grupos"])
|
||||
assert legado["simulado"] is True and legado["umbral_supresion"] == 5
|
||||
|
||||
|
||||
def test_small_cohort_figures_are_states_not_numbers(app):
|
||||
"""Pins down: with 4 patients with a biopsy report and 3 with a known result, the cards of proportions are `suprimido`
|
||||
without value or interval, the cohort card shows 15, the cards that need a denominator of zero are `sin_datos`, and the
|
||||
cards of what the data cannot hold are listed apart. Fails if a small group is shown through a card."""
|
||||
r = get(app, "/resumen", horizonte=90).get_json()
|
||||
t = {i["clave"]: i for i in r["indicadores"]}
|
||||
assert t["cohorte"]["valor"] == 15 and t["cohorte"]["estado"] == "disponible"
|
||||
assert t["con_biopsia"]["estado"] == "suprimido" and t["con_biopsia"]["valor"] is None
|
||||
assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["ic_bajo"] is None
|
||||
assert r["horizonte_dias"] == 90 and "maligno_90d" in t and {x["clave"] for x in r["no_disponibles"]}
|
||||
|
||||
|
||||
def test_the_distribution_by_biopsy_result_names_every_category_and_opens_its_patients(app):
|
||||
"""Pins down: by biopsy result the categories are benign, in situ, invasive, report without grade and no biopsy, each with
|
||||
the Seguimiento filter that opens its patients. Four groups of one patient hide with the group of 11 without biopsy, so
|
||||
the difference to the total hides them. Fails if a category is missing, a small group can be recovered by subtraction,
|
||||
or the key is not one the list accepts."""
|
||||
d = get(app, "/distribucion", por="biopsia").get_json()
|
||||
assert [i["codigo"] for i in d["items"]] == ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR", "SIN_DATO", "SIN_BIOPSIA"]
|
||||
sin_biopsia = d["items"][-1]
|
||||
# Four categories of one patient each hide, and the 11 without biopsy goes with them so the difference can't give them away.
|
||||
assert all(i["suprimido"] and i["n"] is None for i in d["items"])
|
||||
assert sin_biopsia["seleccion"] == {"biopsia": "SIN_BIOPSIA"}
|
||||
abierta = app.get("/cama/seguimiento", query_string={"corte": CORTE, "meses": 0, **sin_biopsia["seleccion"]}).get_json()
|
||||
assert abierta["paginacion"]["total_items"] == 11, "the list accepts the key the distribution gives"
|
||||
|
||||
|
||||
def test_comparison_and_map_say_no_data_instead_of_a_test_or_a_cell_they_cannot_support(app):
|
||||
"""Pins down: on this small cohort the comparison has no valid test (it says why) and its groups are suppressed; the
|
||||
map has every cell with a state and no proportions that leak; both refuse the biopsy result as a dimension. Fails if a
|
||||
p-value is given on a table of fewer than five known results."""
|
||||
c = get(app, "/comparacion", por="birads", medida="maligno").get_json()
|
||||
assert c["prueba"]["valida"] is False and c["prueba"]["motivo"]
|
||||
assert all(g["estado"] in ("suprimido", "sin_datos") for g in c["grupos"])
|
||||
m = get(app, "/mapa", filas="birads", columnas="grupo_edad").get_json()
|
||||
assert len(m["celdas"]) == len(m["filas"]["categorias"]) * len(m["columnas"]["categorias"])
|
||||
assert all(c["resultado"]["valor"] is None for c in m["celdas"])
|
||||
assert get(app, "/comparacion", por="biopsia").status_code == 400
|
||||
assert get(app, "/mapa", filas="biopsia", columnas="birads").status_code == 400
|
||||
assert get(app, "/mapa", filas="birads", columnas="birads").status_code == 400
|
||||
|
||||
|
||||
def test_the_trend_counts_reports_per_period_and_flags_the_period_the_cutoff_cuts(app):
|
||||
"""Pins down: by month the reports of mammogram and biopsy fall in their months, small counts are hidden, the answer names
|
||||
its population, unit and biopsy scope, and a cut-off inside a period marks it as incomplete. Fails if a report is counted
|
||||
in another period, a partial period is presented as whole or the answer carries a test or a cohort it doesn't use."""
|
||||
t = tend(app, tipo="mes", periodos=12).get_json()
|
||||
assert [p["periodo"] for p in t["periodos"]][-1] == "2025-12" and len(t["periodos"]) == 12
|
||||
assert all(p["incompleto"] is False for p in t["periodos"])
|
||||
assert t["unidad"] == "reportes" and t["poblacion"] and t["alcance_biopsias"] and t["corte"] == CORTE
|
||||
assert not {"prueba", "cohorte", "revision", "ventana", "filtros"} & set(t)
|
||||
diciembre = t["periodos"][-1]
|
||||
assert diciembre["reportes_mastografia"]["total"] in (None, *range(5, 40))
|
||||
for p in t["periodos"]:
|
||||
categorias = p["reportes_biopsia"]["por_grado"]
|
||||
ocultos = [k for k, v in categorias.items() if v["suprimido"]]
|
||||
assert len(ocultos) != 1 or p["reportes_biopsia"]["total"] is None, "a lone hidden category would be the total minus the published ones"
|
||||
parcial = app.get("/cama/analisis/tendencia", query_string={"corte": "2025-12-15", "tipo": "mes", "periodos": 3}).get_json()
|
||||
assert parcial["periodos"][-1]["periodo"] == "2025-12" and parcial["periodos"][-1]["incompleto"] is True
|
||||
semestres = tend(app, tipo="semestre", periodos=2).get_json()
|
||||
assert [p["periodo"] for p in semestres["periodos"]] == ["2025-S1", "2025-S2"]
|
||||
|
||||
|
||||
def test_the_trend_is_the_same_whatever_the_cohort_selection_and_refuses_to_take_one(app):
|
||||
"""Pins down: the trend is general activity, so a window, a filter or the cohort context are 400 instead of being silently
|
||||
ignored, and the answer of the same cut-off doesn't change with what the other sections have selected. Fails if the trend
|
||||
attributes a filter or window it doesn't apply."""
|
||||
base = tend(app, tipo="mes", periodos=6)
|
||||
assert base.status_code == 200
|
||||
for extra in ({"meses": 3}, {"birads": "BIRADS_5"}, {"grupo_edad": "50_59"}, {"cohorte": "x", "escenario": "y", "revision": "z"}, {"horizonte": 90}):
|
||||
assert tend(app, tipo="mes", periodos=6, **extra).status_code == 400, extra
|
||||
cuerpo = get(app, "/resumen").get_json()
|
||||
get(app, "/distribucion", por="grupo_edad", birads="BIRADS_5")
|
||||
assert tend(app, tipo="mes", periodos=6).get_json() == base.get_json()
|
||||
assert cuerpo["cohorte"] not in str(base.get_json())
|
||||
|
||||
|
||||
def test_a_period_without_reports_has_zero_counts_and_no_proportion(app):
|
||||
"""Pins down: months before the first report have zero reports, a proportion `sin_datos` and no hidden flag on a zero.
|
||||
Fails if an empty month turns into a suppressed or a zero-percent figure."""
|
||||
t = tend(app, tipo="mes", periodos=12).get_json()
|
||||
vacio = t["periodos"][0]
|
||||
assert vacio["periodo"] == "2025-01" and vacio["reportes_biopsia"]["por_grado"]["BENIGNO"] == {"n": 0, "suprimido": False}
|
||||
assert vacio["maligno"]["estado"] == "sin_datos" and vacio["maligno"]["valor"] is None
|
||||
|
||||
|
||||
def test_an_empty_cohort_is_an_answer_with_no_data_in_every_part(app):
|
||||
"""Pins down: before the first mammogram every endpoint answers 200 with zero patients and states without data, never an
|
||||
error or a figure. Fails if an empty cohort breaks a part of the tab."""
|
||||
vacia = {"corte": "2025-01-01", "meses": 0}
|
||||
resumen = app.get("/cama/analisis/resumen", query_string=vacia).get_json()
|
||||
t = {i["clave"]: i for i in resumen["indicadores"]}
|
||||
assert t["cohorte"]["valor"] == 0 and t["maligno_conocido"]["estado"] == "sin_datos" and t["biopsia_90d"]["estado"] == "sin_datos"
|
||||
d = app.get("/cama/analisis/distribucion", query_string={**vacia, "por": "birads"}).get_json()
|
||||
assert d["total"] == 0 and all(i["n"] == 0 and i["porcentaje"] is None for i in d["items"])
|
||||
assert app.get("/cama/analisis/comparacion", query_string={**vacia, "por": "grupo_edad"}).status_code == 200
|
||||
assert app.get("/cama/analisis/mapa", query_string={**vacia, "filas": "birads", "columnas": "grupo_edad"}).status_code == 200
|
||||
|
||||
|
||||
def test_the_selection_rules_of_the_list_apply_to_the_analysis(app):
|
||||
"""Pins down: a window or filter selecting fewer than five patients is a 403 with the reason `supresion`, a stale revision a
|
||||
409, a context quoted in part a 400, and the endpoints share the list's window and filters. Fails if the analysis
|
||||
answers a group the list refuses."""
|
||||
assert get(app, "/distribucion", por="birads", birads="BIRADS_6").status_code == 403
|
||||
assert get(app, "/resumen", meses=1, birads="BIRADS_5").status_code == 403
|
||||
cuerpo = get(app, "/resumen").get_json()
|
||||
contexto = {k: cuerpo[k] for k in ("cohorte", "escenario", "revision")}
|
||||
assert get(app, "/resumen", **contexto).status_code == 200
|
||||
assert get(app, "/resumen", **{**contexto, "revision": "0" * 64}).status_code == 409
|
||||
assert get(app, "/resumen", cohorte=contexto["cohorte"]).status_code == 400
|
||||
filtrado = get(app, "/distribucion", por="grupo_edad", birads="BIRADS_5").get_json()
|
||||
assert filtrado["filtros"]["birads"] == "BIRADS_5" and filtrado["total"] in (6, 7)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ruta, params", [
|
||||
("/distribucion", {}), ("/distribucion", {"por": "edad"}), ("/resumen", {"horizonte": 45}), ("/resumen", {"horizonte": "x"}),
|
||||
("/comparacion", {"por": "birads", "medida": "otra"}), ("/resumen", {"meses": 0, "periodos": 3}), ("/resumen", {"por": "birads"}), ("/resumen", {"estatus": "ALTA"}), ("/distribucion", {"por": ""}),
|
||||
])
|
||||
def test_a_badly_written_request_is_a_400(app, ruta, params):
|
||||
"""Pins down: a missing or unknown dimension, an unadmitted horizon or period count, a parameter of another route and
|
||||
the retired status are all 400. Fails if validation lets an unknown request through."""
|
||||
assert get(app, ruta, **params).status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize("meses", [0, 1, 3, 6, 12])
|
||||
@pytest.mark.parametrize("por", ["birads", "grupo_edad", "biopsia"])
|
||||
def test_each_published_group_opens_exactly_the_patients_it_counts_in_every_window(app, meses, por):
|
||||
"""Pins down: for the whole cohort and for the windows of 1, 3, 6 and 12 months, every published group of the distribution
|
||||
opens in the follow-up list, with its key, the same window and the cohort context, onto as many patients as it counts, and
|
||||
a selection the list suppresses is not published. Fails if a bar leads to a different population than it represents."""
|
||||
respuesta = get(app, "/distribucion", por=por, meses=meses)
|
||||
if respuesta.status_code == 403:
|
||||
assert meses != 0, "only a window may leave the cohort too small"
|
||||
return
|
||||
d = respuesta.get_json()
|
||||
assert d["ventana"]["meses"] == meses
|
||||
contexto = {k: d[k] for k in ("cohorte", "escenario", "revision")}
|
||||
abiertos = 0
|
||||
for item in d["items"]:
|
||||
if item["suprimido"] or not item["n"]:
|
||||
continue
|
||||
lista = app.get("/cama/seguimiento", query_string={"corte": d["corte"], "meses": d["ventana"]["meses"], **contexto, **item["seleccion"]})
|
||||
assert lista.status_code == 200, (item["codigo"], lista.get_json())
|
||||
assert lista.get_json()["paginacion"]["total_items"] == item["n"], (meses, por, item["codigo"])
|
||||
abiertos += 1
|
||||
assert abiertos or meses != 0 or por == "biopsia", "the whole cohort publishes groups"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("params", [{"tipo": "dia"}, {"periodos": 0}, {"periodos": 99}, {"periodos": "x"}, {"corte": "2999-01-01"}])
|
||||
def test_a_badly_written_trend_request_is_a_400(app, params):
|
||||
"""Pins down: an unknown period type, a period count out of range and a cut-off in the future are refused. Fails if the
|
||||
trend answers a request it can't define."""
|
||||
assert tend(app, **{"tipo": "mes", **params}).status_code == 400
|
||||
|
||||
|
||||
def test_a_repeated_parameter_is_a_400_and_the_answers_are_not_cached(app):
|
||||
"""Pins down: `por` twice is refused, and every answer says `no-store`. Fails if a client's choice is ambiguous or a
|
||||
patient-level selection can be cached."""
|
||||
assert app.get("/cama/analisis/distribucion?corte=2025-12-31&meses=0&por=birads&por=grupo_edad").status_code == 400
|
||||
assert get(app, "/resumen").headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_without_the_cohort_view_the_analysis_answers_503(tmp_path):
|
||||
"""Pins down: a database whose indicator cycle hasn't created the cohort view answers 503 with the reason `cohorte`.
|
||||
Fails if a missing view is a server error."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
|
||||
sin_ciclo = base_de("cama", tmp_path, datos=insertar)
|
||||
try:
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(analysis_blueprint(lambda: Session(sin_ciclo.motor)), url_prefix="/cama/analisis")
|
||||
respuesta = flask.test_client().get("/cama/analisis/resumen", query_string={"corte": CORTE, "meses": 0})
|
||||
assert respuesta.status_code == 503 and respuesta.get_json()["motivo"] == "cohorte"
|
||||
finally:
|
||||
sin_ciclo.motor.dispose()
|
||||
@@ -0,0 +1,226 @@
|
||||
"""What this module covers: the statistics, the suppression rule and the calculations of CaMa's descriptive analysis
|
||||
(`webapi.cama_analysis`), as pure functions: no database, no HTTP.
|
||||
|
||||
Fixtures: none. The cohort rows are built here with the exact counts each test needs (`fila`), invented inputs whose
|
||||
expected figures are written out in the tests; nothing is read from a database.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.cama_analysis import calculations as calc
|
||||
from webapi.cama_analysis.stats import chi2_homogeneidad, chi2_sf, cuantil, wilson
|
||||
from webapi.cama_analysis.suppression import proporcion_publicable, suprimir_categorias, suprimir_tabla
|
||||
from webapi.cama_follow_up.cohort import Fila
|
||||
|
||||
CORTE = date(2025, 12, 31)
|
||||
MAST = date(2025, 1, 1)
|
||||
MALIGNOS = {"CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"}
|
||||
CATEGORIAS_BIRADS = [("BIRADS_4A", "BI-RADS 4A"), ("BIRADS_5", "BI-RADS 5"), ("BIRADS_6", "BI-RADS 6")]
|
||||
CATEGORIAS_EDAD = [("40-49", "40 a 49 años"), ("50-59", "50 a 59 años")]
|
||||
|
||||
|
||||
def fila(i, birads="BIRADS_5", edad="50-59", grado=None, con_reporte=None, dias_biopsia=None, dias_maligno=None, mast=MAST):
|
||||
"""One patient: `grado` is the shown biopsy result, `dias_*` the days from the mammogram to the earliest biopsy report and
|
||||
to the earliest malignant one."""
|
||||
reporte = con_reporte if con_reporte is not None else grado is not None
|
||||
return Fila(pac_id=i, mastografia_fecha=mast, birads=birads, grupo_edad=edad, biopsia=grado,
|
||||
biopsia_fecha=mast + timedelta(days=dias_biopsia or 9) if reporte else None,
|
||||
primera_biopsia_fecha=mast + timedelta(days=dias_biopsia) if dias_biopsia is not None else None,
|
||||
primer_maligno_fecha=mast + timedelta(days=dias_maligno) if dias_maligno is not None else None)
|
||||
|
||||
|
||||
def cohorte():
|
||||
"""70 patients: 40 with a known result (30 benign, 5 in situ, 5 invasive), 10 with a report and no grade, 20 without
|
||||
a biopsy. Days to the first biopsy report: 20 benign at 10 days, 6 malignant at 20 days, the other 24 with a report at 100 days."""
|
||||
filas, i = [], 0
|
||||
for grado, n in (("BENIGNO", 30), ("CARCINOMA_IN_SITU", 5), ("CARCINOMA_INVASOR", 5)):
|
||||
for _ in range(n):
|
||||
i += 1
|
||||
filas.append(fila(i, grado=grado))
|
||||
for k, f in enumerate(filas):
|
||||
pronto = k < 20 or (grado_es(f) and k % 10 < 6)
|
||||
dias = 10 if k < 20 else 20 if pronto else 100
|
||||
maligno = (20 if pronto else 120) if grado_es(f) else None
|
||||
filas[k] = fila(f.pac_id, grado=f.biopsia, dias_biopsia=dias, dias_maligno=maligno)
|
||||
for _ in range(10):
|
||||
i += 1
|
||||
filas.append(fila(i, grado=None, con_reporte=True, dias_biopsia=100))
|
||||
for _ in range(20):
|
||||
i += 1
|
||||
filas.append(fila(i))
|
||||
return filas
|
||||
|
||||
|
||||
def grado_es(f):
|
||||
return f.biopsia in MALIGNOS
|
||||
|
||||
|
||||
def test_wilson_matches_the_closed_form_and_stays_inside_zero_and_one():
|
||||
"""Pins down: the Wilson interval of 10 of 40 is (14.1 %, 40.3 %), the interval of 0 of n starts at 0 and of n of n ends at
|
||||
1, and it is symmetric around the midpoint of k and n-k. Fails if the formula or its continuity is changed."""
|
||||
bajo, alto = wilson(10, 40)
|
||||
assert (bajo, alto) == pytest.approx((0.1410, 0.4028), abs=0.001)
|
||||
assert wilson(0, 30)[0] == 0 and wilson(30, 30)[1] == 1
|
||||
assert wilson(10, 40)[0] == pytest.approx(1 - wilson(30, 40)[1])
|
||||
with pytest.raises(ValueError):
|
||||
wilson(5, 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gl, critico", [(1, 3.841458820694124), (2, 5.991464547107979), (3, 7.814727903251179), (4, 9.487729036781154), (9, 16.918977604620448)])
|
||||
def test_chi_square_tail_at_the_five_percent_critical_values(gl, critico):
|
||||
"""Pins down: the tail probability at the textbook 5 % critical value of each degree of freedom is 0.05, and at 0 it is
|
||||
1. Fails if the incomplete gamma function is wrong in its series or its continued fraction."""
|
||||
assert chi2_sf(critico, gl) == pytest.approx(0.05, abs=1e-9)
|
||||
assert chi2_sf(0, gl) == 1
|
||||
|
||||
|
||||
def test_the_homogeneity_test_gives_the_statistic_and_refuses_what_the_approximation_cannot_carry():
|
||||
"""Pins down: groups 20 of 40 and 8 of 40 give chi-square 7.912 with 1 degree of freedom and p 0.0049; two groups with an
|
||||
expected count under 5, a single group, or one outcome only are not tested, with the reason. Fails if a p-value is
|
||||
given where the approximation isn't valid."""
|
||||
prueba = chi2_homogeneidad([(20, 40), (8, 40)])
|
||||
assert prueba["valida"] and prueba["gl"] == 1 and prueba["estadistico"] == pytest.approx(7.912, abs=0.001)
|
||||
assert prueba["p"] == pytest.approx(0.00492, abs=0.0001)
|
||||
assert not chi2_homogeneidad([(1, 10), (2, 10)])["valida"]
|
||||
assert not chi2_homogeneidad([(20, 40)])["valida"]
|
||||
assert not chi2_homogeneidad([(0, 40), (0, 40)])["valida"]
|
||||
|
||||
|
||||
def test_quantiles_interpolate_between_the_order_statistics():
|
||||
"""Pins down: the median of 1 to 4 is 2.5 and the quartiles of 1 to 5 are 2 and 4. Fails if the interpolation changes."""
|
||||
assert cuantil([4, 1, 3, 2], .5) == 2.5
|
||||
assert (cuantil([1, 2, 3, 4, 5], .25), cuantil([1, 2, 3, 4, 5], .75)) == (2, 4)
|
||||
|
||||
|
||||
def test_a_proportion_is_published_only_when_the_group_the_cases_and_the_rest_are_not_small():
|
||||
"""Pins down: 10 of 40 is published; 3 of 40 (3 cases), 38 of 40 (2 non-cases) and 4 of 4 (a group under 5) are not;
|
||||
0 of 40 is published because zero describes nobody. Fails if a small cell can be read from a proportion."""
|
||||
assert proporcion_publicable(10, 40, 5) and proporcion_publicable(0, 40, 5)
|
||||
assert not proporcion_publicable(3, 40, 5) and not proporcion_publicable(38, 40, 5) and not proporcion_publicable(4, 4, 5)
|
||||
|
||||
|
||||
def test_a_hidden_cell_takes_the_smallest_published_one_with_it_until_the_difference_hides_nothing():
|
||||
"""Pins down: with cells 30, 12, 8, 2 and a published total, the 2 is hidden and so is the 8 (2 + 8 >= 5), so the
|
||||
difference between the total and the published cells is 10 patients and says nothing of the 2; cells with no small
|
||||
count hide nothing; zeros are not small. Fails if one hidden cell can be recovered by subtraction."""
|
||||
assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 2}, 5) == {"c", "d"}
|
||||
assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 7}, 5) == set()
|
||||
assert suprimir_categorias({"a": 30, "b": 0, "c": 8}, 5) == set()
|
||||
assert suprimir_categorias({"a": 3, "b": 2}, 5) == {"a", "b"}
|
||||
|
||||
|
||||
def test_a_table_hides_along_rows_and_columns_until_no_line_gives_a_small_cell_away():
|
||||
"""Pins down: in a 2 x 2 table with one cell of 1, the secondary suppression covers its row and its column, so the
|
||||
hidden cells total at least 5 in each line. Fails if a marginal total and the visible cells reveal a hidden cell."""
|
||||
conteos = {("a", "x"): 20, ("a", "y"): 1, ("b", "x"): 9, ("b", "y"): 30}
|
||||
ocultas = suprimir_tabla(conteos, 5)
|
||||
assert ("a", "y") in ocultas
|
||||
for fila_ in ("a", "b"):
|
||||
ocultos = sum(conteos[k] for k in ocultas if k[0] == fila_)
|
||||
assert ocultos == 0 or ocultos >= 5
|
||||
for columna in ("x", "y"):
|
||||
ocultos = sum(conteos[k] for k in ocultas if k[1] == columna)
|
||||
assert ocultos == 0 or ocultos >= 5
|
||||
|
||||
|
||||
def test_the_cards_state_their_numerator_denominator_and_interval():
|
||||
"""Pins down, on a cohort of 70 (40 with a known result, 10 with a report without a grade, 20 without biopsy): cohort 70;
|
||||
with a biopsy report 50 of 70; malignant among the known 10 of 40 (25 %) with its Wilson interval; invasive 5 of 40;
|
||||
a biopsy within 90 days 26 of 70; a malignant result within 90 days 6 of 70; the median days to the report 20 (n 50).
|
||||
Fails if a numerator, a denominator or a definition changes."""
|
||||
t = {x["clave"]: x for x in calc.resumen(cohorte(), CORTE, 90, MALIGNOS, 5)}
|
||||
assert t["cohorte"]["valor"] == 70
|
||||
assert (t["con_biopsia"]["n"], t["con_biopsia"]["denominador"]) == (50, 70)
|
||||
assert (t["maligno_conocido"]["n"], t["maligno_conocido"]["denominador"], t["maligno_conocido"]["valor"]) == (10, 40, 25.0)
|
||||
assert (t["maligno_conocido"]["ic_bajo"], t["maligno_conocido"]["ic_alto"]) == pytest.approx((14.1, 40.3), abs=0.2)
|
||||
assert (t["invasor_conocido"]["n"], t["invasor_conocido"]["denominador"]) == (5, 40)
|
||||
assert (t["biopsia_90d"]["n"], t["biopsia_90d"]["denominador"]) == (26, 70)
|
||||
assert (t["maligno_90d"]["n"], t["maligno_90d"]["denominador"]) == (6, 70)
|
||||
assert (t["dias_a_biopsia"]["valor"], t["dias_a_biopsia"]["n"]) == (20, 50)
|
||||
assert all(x["estado"] == "disponible" for x in t.values())
|
||||
|
||||
|
||||
def test_a_horizon_counts_only_the_mammograms_that_have_had_the_time():
|
||||
"""Pins down: with a 365-day horizon and the cut-off 364 days after the mammograms nobody has had the time, so the
|
||||
denominator is zero and the card has no data, not a zero percent; a mammogram that is recent at the cut-off is left
|
||||
out of the 90-day denominator. Fails if a recent mammogram is read as one without a biopsy."""
|
||||
t = {x["clave"]: x for x in calc.resumen(cohorte(), MAST + timedelta(days=364), 365, MALIGNOS, 5)}
|
||||
assert t["biopsia_365d"]["estado"] == "sin_datos" and t["biopsia_365d"]["valor"] is None
|
||||
recientes = cohorte() + [fila(900 + k, mast=CORTE - timedelta(days=10)) for k in range(6)]
|
||||
t = {x["clave"]: x for x in calc.resumen(recientes, CORTE, 90, MALIGNOS, 5)}
|
||||
assert t["biopsia_90d"]["denominador"] == 70 and t["cohorte"]["valor"] == 76
|
||||
|
||||
|
||||
def test_a_small_numerator_or_denominator_hides_the_figure_and_its_interval():
|
||||
"""Pins down: 3 malignant among 20 known results, and 4 patients with a known result, are not published (state
|
||||
`suprimido`, no value, no interval); an empty cohort has no data. Fails if a small group is shown through a figure."""
|
||||
pocas = [fila(i, grado="CARCINOMA_INVASOR") for i in range(1, 4)] + [fila(10 + i, grado="BENIGNO") for i in range(17)]
|
||||
t = {x["clave"]: x for x in calc.resumen(pocas, CORTE, 90, MALIGNOS, 5)}
|
||||
assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["valor"] is None and t["maligno_conocido"]["ic_bajo"] is None
|
||||
cuatro = {x["clave"]: x for x in calc.resumen([fila(i, grado="BENIGNO") for i in range(4)], CORTE, 90, MALIGNOS, 5)}
|
||||
assert cuatro["maligno_conocido"]["estado"] == "suprimido"
|
||||
vacia = {x["clave"]: x for x in calc.resumen([], CORTE, 90, MALIGNOS, 5)}
|
||||
assert vacia["cohorte"]["valor"] == 0 and vacia["maligno_conocido"]["estado"] == "sin_datos"
|
||||
|
||||
|
||||
def test_the_distribution_adds_up_to_the_selection_and_hides_small_groups_by_complement():
|
||||
"""Pins down: 30 + 12 + 8 + 2 patients by BI-RADS: the total is 52, shares are of the selection with Wilson intervals,
|
||||
the 2 and the 8 are not published. Fails if the cells and the total disagree or a hidden cell can be subtracted."""
|
||||
filas = ([fila(i, birads="BIRADS_5") for i in range(30)] + [fila(100 + i, birads="BIRADS_4A") for i in range(12)]
|
||||
+ [fila(200 + i, birads="BIRADS_6") for i in range(2)])
|
||||
d = calc.distribucion(filas, "birads", [("BIRADS_4A", "4A"), ("BIRADS_5", "5"), ("BIRADS_6", "6")], 5)
|
||||
por = {i["codigo"]: i for i in d["items"]}
|
||||
assert d["total"] == 44 and por["BIRADS_5"]["n"] == 30 and por["BIRADS_5"]["porcentaje"] == pytest.approx(68.18, abs=0.01)
|
||||
assert por["BIRADS_6"]["suprimido"] and por["BIRADS_6"]["n"] is None and por["BIRADS_6"]["ic_bajo"] is None
|
||||
assert por["BIRADS_4A"]["suprimido"], "the smallest published cell is hidden with the small one"
|
||||
assert sum(i["n"] for i in d["items"] if not i["suprimido"]) == 30
|
||||
assert por["BIRADS_5"]["seleccion"] == {"birads": "BIRADS_5"}
|
||||
|
||||
|
||||
def test_the_comparison_shares_the_denominator_of_known_results_and_tests_only_valid_tables():
|
||||
"""Pins down: by BI-RADS, 20 of 40 and 8 of 40 known results are malignant (50 % and 20 %), the test is the chi-square 7.9
|
||||
with p 0.005, patients without a result are not in the denominator, and a group of fewer than five known results is
|
||||
suppressed and left out of the test. Fails if the denominator includes patients without biopsy or the test uses a hidden group."""
|
||||
filas = ([fila(i, birads="BIRADS_4A", grado="CARCINOMA_INVASOR") for i in range(20)] + [fila(30 + i, birads="BIRADS_4A", grado="BENIGNO") for i in range(20)]
|
||||
+ [fila(100 + i, birads="BIRADS_5", grado="CARCINOMA_IN_SITU") for i in range(8)] + [fila(130 + i, birads="BIRADS_5", grado="BENIGNO") for i in range(32)]
|
||||
+ [fila(300 + i, birads="BIRADS_5") for i in range(25)] + [fila(400 + i, birads="BIRADS_6", grado="BENIGNO") for i in range(3)])
|
||||
c = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "maligno", MALIGNOS, 5)
|
||||
g = {x["codigo"]: x for x in c["grupos"]}
|
||||
assert (g["BIRADS_4A"]["casos"], g["BIRADS_4A"]["total"], g["BIRADS_4A"]["valor"]) == (20, 40, 50.0)
|
||||
assert (g["BIRADS_5"]["casos"], g["BIRADS_5"]["total"], g["BIRADS_5"]["valor"]) == (8, 40, 20.0)
|
||||
assert g["BIRADS_6"]["estado"] == "suprimido"
|
||||
assert c["prueba"]["valida"] and c["prueba"]["p"] == pytest.approx(0.00492, abs=0.0001)
|
||||
invasor = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "invasor", MALIGNOS, 5)
|
||||
assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_4A"] == 20
|
||||
assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_5"] == 0
|
||||
|
||||
|
||||
def test_the_map_crosses_two_dimensions_and_its_cells_add_up_to_the_selection():
|
||||
"""Pins down: BI-RADS by age group: each patient is in one cell, the published cells never exceed the selection, the
|
||||
proportion of a cell is among its known results and a hidden cell, secondary ones included, has neither count nor proportion. Fails if a patient
|
||||
is counted twice or a hidden cell leaks through its proportion."""
|
||||
filas = ([fila(i, birads="BIRADS_5", edad="50-59", grado="BENIGNO") for i in range(12)]
|
||||
+ [fila(100 + i, birads="BIRADS_5", edad="40-49", grado="CARCINOMA_INVASOR") for i in range(7)]
|
||||
+ [fila(200 + i, birads="BIRADS_4A", edad="50-59") for i in range(9)] + [fila(300, birads="BIRADS_4A", edad="40-49")])
|
||||
m = calc.mapa(filas, "birads", "grupo_edad", CATEGORIAS_BIRADS, CATEGORIAS_EDAD, "maligno", MALIGNOS, 5)
|
||||
celdas = {(c["fila"], c["columna"]): c for c in m["celdas"]}
|
||||
assert celdas[("BIRADS_5", "50-59")]["n"] == 12 and celdas[("BIRADS_5", "50-59")]["resultado"]["casos"] == 0
|
||||
oculta = celdas[("BIRADS_4A", "40-49")]
|
||||
assert oculta["suprimido"] and oculta["n"] is None and oculta["resultado"]["valor"] is None
|
||||
# The 40-49 column then holds a hidden 1 and a published 7: the 7 goes with it, so the column can't give the 1 away.
|
||||
assert celdas[("BIRADS_5", "40-49")]["suprimido"] and celdas[("BIRADS_5", "40-49")]["resultado"]["valor"] is None
|
||||
assert celdas[("BIRADS_4A", "50-59")]["suprimido"], "and the 4A row hides its 9 for the same reason"
|
||||
assert sum(c["n"] for c in m["celdas"] if not c["suprimido"]) <= len(filas)
|
||||
assert celdas[("BIRADS_5", "50-59")]["seleccion"] == {"birads": "BIRADS_5", "grupo_edad": "50-59"}
|
||||
|
||||
|
||||
def test_the_catalog_of_unavailable_analyses_names_a_reason_for_each():
|
||||
"""Pins down: survival, recurrence, treatment adherence, the time-to-event curves and their tests, and BRCA, stage and
|
||||
size are listed as unavailable, each with its reason. Fails if one of them is dropped or loses its reason."""
|
||||
assert {x["clave"] for x in calc.NO_DISPONIBLES} == {"supervivencia", "recaida", "adherencia_tratamiento", "curvas_tiempo_a_evento",
|
||||
"riesgos_proporcionales", "brca_estadio_tamano"}
|
||||
assert all(x["motivo"] and x["titulo"] for x in calc.NO_DISPONIBLES)
|
||||
assert not math.isnan(wilson(1, 2)[0])
|
||||
@@ -0,0 +1,193 @@
|
||||
"""What this module covers: `CamaCohort.rows` (`webapi.cama_cohort`) and the `/cama/analisis`, `/cama/seguimiento`
|
||||
and `/cama/pacientes` routes over it: eligibility (BI-RADS 4-6, dated and known by the cutoff), the biopsy link
|
||||
(mammogram -> order -> report, never across patients or before the mammogram), pagination, export, patient detail
|
||||
and access control.
|
||||
|
||||
Fixtures: `cohort_db`, an isolated SQLite engine with six synthetic patients' `Persona`/`Carga`/`Procedimiento`/
|
||||
`Observacion` rows (`webapi.orchestration.tables.cama.TABLAS`), one load from 2025 and one from 2027; `client`, a
|
||||
minimal Flask app registering only the two CaMa blueprints over `cohort_db`, with an always-authorized access
|
||||
callback.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
from webapi.cama_analysis import analysis
|
||||
from webapi.cama_cohort import CamaCohort
|
||||
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_db():
|
||||
"""Six eligible people, one linked biopsy and one biopsy without a link."""
|
||||
t = TABLAS
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion):
|
||||
model.__table__.create(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)),
|
||||
t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)),
|
||||
])
|
||||
for patient in range(1, 7):
|
||||
session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1)))
|
||||
session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient),
|
||||
carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1)))
|
||||
session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia',
|
||||
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia',
|
||||
clase='reporte', fecha=date(2025, 2, 2)))
|
||||
session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1,
|
||||
pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5'))
|
||||
for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)):
|
||||
report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15)
|
||||
session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama',
|
||||
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia',
|
||||
clase='orden', fecha=date(2025, 2, 10)))
|
||||
session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2,
|
||||
fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient,
|
||||
estudio_id='biopsia', clase='reporte', fecha=report_date))
|
||||
session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load,
|
||||
pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO'))
|
||||
session.commit()
|
||||
yield engine
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(cohort_db):
|
||||
"""Configure an explicitly synthetic reader and an authorized test principal."""
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(analysis, url_prefix='/cama')
|
||||
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
|
||||
def read(cutoff):
|
||||
with Session(cohort_db) as session:
|
||||
return CamaCohort(session).rows(cutoff)
|
||||
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True)
|
||||
return app.test_client()
|
||||
|
||||
|
||||
QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5'
|
||||
|
||||
|
||||
def query(client, cutoff='2026-10-20'):
|
||||
revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision']
|
||||
return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision
|
||||
|
||||
|
||||
def test_aggregate_list_detail_and_export_have_one_selection(client):
|
||||
"""The published aggregate reconciles with pages, patient details and export."""
|
||||
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6
|
||||
selection = query(client)
|
||||
first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json()
|
||||
assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'}
|
||||
items = []
|
||||
for page in (1, 2, 3):
|
||||
data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json()
|
||||
items.extend(data['items'])
|
||||
exported = client.get('/cama/seguimiento/exportacion' + selection).get_json()
|
||||
assert exported['items'] == items and exported['total_items'] == 6
|
||||
for item in items:
|
||||
detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json()
|
||||
assert detail['item'] == item and detail['corte'] == aggregate['corte']
|
||||
assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1
|
||||
assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items
|
||||
|
||||
|
||||
def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
|
||||
"""Unknown filters and small groups cannot silently broaden patient access."""
|
||||
selection = query(client)
|
||||
assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400
|
||||
assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403
|
||||
assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400
|
||||
assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409
|
||||
client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
|
||||
assert client.get('/cama/seguimiento' + selection).status_code == 403
|
||||
assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403
|
||||
assert client.get('/cama/pacientes/some-id' + selection).status_code == 403
|
||||
|
||||
|
||||
def test_cutoff_excludes_later_clinical_and_load_dates(client):
|
||||
"""A report or observation not yet known at the cutoff cannot appear."""
|
||||
early = query(client, '2025-02-09')
|
||||
rows = client.get('/cama/seguimiento' + early).get_json()['items']
|
||||
assert len(rows) == 6 and all(row['biopsia'] is None for row in rows)
|
||||
empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '')
|
||||
response = client.get('/cama/seguimiento' + empty).get_json()
|
||||
assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01'
|
||||
|
||||
|
||||
def test_links_and_load_dates_are_distinct(client, cohort_db):
|
||||
"""A missing link and a late load cannot supply a diagnosis before cutoff."""
|
||||
ids = {i: str(i) for i in range(1, 5)}
|
||||
data = client.get('/cama/seguimiento' + query(client)).get_json()
|
||||
rows = {item['pac_id']: item for item in data['items']}
|
||||
assert rows[ids[1]]['biopsia'] == 'BENIGNO'
|
||||
assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None
|
||||
assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15'
|
||||
assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None
|
||||
later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json()
|
||||
rows_later = {item['pac_id']: item for item in later['items']}
|
||||
assert rows_later[ids[3]]['biopsia'] == 'BENIGNO'
|
||||
assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15'
|
||||
assert set(rows) == set(rows_later)
|
||||
|
||||
|
||||
def test_full_application_registers_cohort_and_regular_followup(client):
|
||||
"""The regular follow-up uses the configured reader instead of unrelated fixture rows."""
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(client.application.config)
|
||||
full = app.test_client()
|
||||
assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200
|
||||
assert full.get('/cama/seguimiento?corte=2026-10-20&meses=0').get_json()['paginacion']['total_items'] == 6
|
||||
assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400
|
||||
|
||||
|
||||
def test_windows_and_disabled_provider(client):
|
||||
"""Regular windows remain available and a missing reader returns unavailable."""
|
||||
selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '')
|
||||
body = client.get('/cama/seguimiento' + selection).get_json()
|
||||
assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21'
|
||||
client.application.config['CAMA_COHORT_READER'] = None
|
||||
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
|
||||
|
||||
|
||||
def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db):
|
||||
"""The latest reported result is selected before checking BI-RADS eligibility."""
|
||||
previous = query(client)
|
||||
with Session(cohort_db) as session:
|
||||
session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new',
|
||||
carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1)))
|
||||
session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new',
|
||||
carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2)))
|
||||
session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6,
|
||||
resultado_id='mastografia.birads', valor_fuente='B1'))
|
||||
session.commit()
|
||||
assert client.get('/cama/seguimiento' + previous).status_code == 409
|
||||
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5
|
||||
assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5
|
||||
|
||||
|
||||
def test_cross_patient_links_and_observations_are_not_used(cohort_db):
|
||||
"""A mismatched patient or an order before the mammogram cannot supply a result."""
|
||||
with Session(cohort_db) as session:
|
||||
# The biopsy order is linked to patient 1's mammogram but belongs to patient 2.
|
||||
session.get(TABLAS.Procedimiento, 102).pac_id = 2
|
||||
# Patient 3's otherwise linked biopsy order predates the mammogram.
|
||||
session.get(TABLAS.Procedimiento, 106).fecha = date(2025, 1, 1)
|
||||
# The BI-RADS observation belongs to a different patient.
|
||||
session.get(TABLAS.Observacion, 6).pac_id = 5
|
||||
session.commit()
|
||||
reader = CamaCohort(session)
|
||||
rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))}
|
||||
assert '6' not in rows
|
||||
assert rows['1']['biopsia'] is None
|
||||
assert rows['3']['biopsia'] is None
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Integration with dev: no duplicate routes, retained access hook and individual contract."""
|
||||
from test_cama_analysis import app, base
|
||||
from test_cama_follow_up import CORTE
|
||||
|
||||
|
||||
def test_application_has_one_handler_per_cama_route():
|
||||
from webapi import create_app
|
||||
application = create_app()
|
||||
assert application.config['CAMA_COHORT_READER']._cama_default_reader is True
|
||||
rules = list(application.url_map.iter_rules())
|
||||
for path in ('/cama/seguimiento', '/cama/seguimiento/exportacion',
|
||||
'/cama/analisis/indicadores', '/cama/pacientes/<pac_id>'):
|
||||
assert len([r for r in rules if r.rule == path]) == 1
|
||||
assert application.test_client().get('/health').get_json() == {'status': 'ok'}
|
||||
|
||||
|
||||
def test_individual_route_is_a_row_of_the_selected_list(app):
|
||||
q = {'corte': CORTE, 'meses': 0}
|
||||
listing = app.get('/cama/seguimiento', query_string=q).get_json()
|
||||
q.update({k: listing[k] for k in ('cohorte', 'escenario', 'revision')})
|
||||
patient = listing['items'][0]
|
||||
detail = app.get('/cama/pacientes/' + patient['pac_id'], query_string=q)
|
||||
assert detail.status_code == 200
|
||||
assert detail.get_json()['item'] == patient
|
||||
assert detail.get_json()['revision'] == listing['revision']
|
||||
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={**q, 'page': 2, 'page_size': 2}).get_json()['item'] == patient
|
||||
assert app.get('/cama/pacientes/999999999', query_string=q).status_code == 404
|
||||
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={**q, 'revision': '0'*64}).status_code == 409
|
||||
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={'corte': CORTE, 'meses': 0, 'birads': 'BIRADS_6'}).status_code == 403
|
||||
|
||||
|
||||
def test_configured_access_hook_is_preserved(app):
|
||||
app.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
|
||||
for path in ('/cama/seguimiento', '/cama/pacientes/1', '/cama/analisis/resumen'):
|
||||
assert app.get(path).status_code == 403
|
||||
|
||||
|
||||
def test_explicit_dev_reader_keeps_list_detail_and_aggregate_consistent():
|
||||
from webapi import create_app
|
||||
application = create_app()
|
||||
rows = [dict(pac_id=str(i), mastografia_fecha='2026-01-01', birads='BIRADS_5',
|
||||
grupo_edad='50-59', biopsia=None, biopsia_fecha=None) for i in range(1, 7)]
|
||||
application.config['CAMA_COHORT_READER'] = lambda cutoff: rows
|
||||
client = application.test_client()
|
||||
query = {'corte': '2026-10-20', 'meses': 0}
|
||||
listing = client.get('/cama/seguimiento', query_string=query).get_json()
|
||||
assert listing['paginacion']['total_items'] == 6
|
||||
assert client.get('/cama/pacientes/1', query_string=query).get_json()['item'] == rows[0]
|
||||
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||
assert aggregate['revision'] == listing['revision']
|
||||
application.config['CAMA_COHORT_READER'] = None
|
||||
assert client.get('/cama/seguimiento', query_string=query).status_code == 503
|
||||
@@ -0,0 +1,466 @@
|
||||
"""What this module covers: CaMa's follow-up list and its file (`webapi.cama_follow_up`): who is in the BI-RADS cohort
|
||||
at a cut-off, the window and filters, suppression of small selections, pages, revision and request validation.
|
||||
|
||||
Fixtures: `app`, a Flask app with only the follow-up blueprint over a CaMa database loaded from `insertar` through the
|
||||
cycle up to `event_models` (needs `DBT_MANIFEST`: the cohort view comes from dbt's manifest). `insertar` writes 17
|
||||
invented patients with the cases below; their names (`P01`...) are the source ids. Nothing here touches real data.
|
||||
|
||||
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
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from core.cama.models import BiopsiaMama, Mastografia, Paciente
|
||||
from flask import Flask
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.cama_follow_up import cohort, listing
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
CORTE = "2025-12-31"
|
||||
D = date
|
||||
|
||||
# patient -> (birth date, [(mammogram date, BI-RADS, report date or None)])
|
||||
PACIENTES = {
|
||||
"P01": (D(1960, 5, 5), [(D(2025, 12, 1), "B5", D(2025, 12, 8))]),
|
||||
"P02": (D(1975, 1, 1), [(D(2025, 11, 20), "B5", D(2025, 11, 27))]),
|
||||
"P03": (D(1975, 1, 1), [(D(2025, 11, 5), "B5", D(2025, 11, 12))]),
|
||||
"P04": (D(1976, 1, 1), [(D(2025, 10, 10), "B5", D(2025, 10, 17))]),
|
||||
"P05": (D(1980, 3, 3), [(D(2025, 9, 1), "B5", D(2025, 9, 8))]),
|
||||
"P06": (D(1950, 1, 1), [(D(2025, 8, 15), "B5", D(2025, 8, 22))]),
|
||||
"P07": (D(1975, 1, 1), [(D(2025, 12, 10), "B4A", D(2025, 12, 17))]),
|
||||
"P08": (D(1975, 1, 1), [(D(2025, 12, 2), "B4A", D(2025, 12, 9))]),
|
||||
"P09": (D(1965, 6, 6), [(D(2025, 11, 1), "B4A", D(2025, 11, 8))]),
|
||||
"P10": (D(1965, 6, 6), [(D(2025, 10, 1), "B4A", D(2025, 10, 8))]),
|
||||
"P11": (D(1965, 6, 6), [(D(2025, 7, 1), "B4A", D(2025, 7, 8))]),
|
||||
"P12": (D(1985, 1, 1), [(D(2025, 12, 15), "B6", D(2025, 12, 22))]),
|
||||
"P13": (D(1985, 1, 1), [(D(2025, 6, 1), "B6", D(2025, 6, 8))]),
|
||||
"P14": (D(1975, 1, 1), [(D(2025, 12, 20), "B4", D(2025, 12, 27))]),
|
||||
"P15": (D(1975, 1, 1), [(D(2025, 6, 1), "B5", D(2025, 6, 8)), (D(2025, 12, 5), "B2", D(2025, 12, 12))]),
|
||||
"P16": (D(1975, 1, 1), [(D(2025, 5, 1), "B1", D(2025, 5, 8)), (D(2025, 12, 20), "B5", D(2026, 1, 5))]),
|
||||
"P17": (D(1975, 1, 1), [(D(2025, 12, 12), "B4A", D(2025, 12, 19)), (D(2025, 12, 12), "B5", D(2025, 12, 19))]),
|
||||
}
|
||||
# (patient, index of its mammogram, request date, report date, grade)
|
||||
BIOPSIAS = (
|
||||
("P01", 0, D(2025, 12, 5), D(2025, 12, 20), "CARCINOMA_INVASOR"),
|
||||
("P02", 0, D(2025, 12, 1), D(2026, 1, 10), "CARCINOMA_IN_SITU"), # reported after the cut-off
|
||||
("P04", 0, D(2025, 10, 15), D(2025, 10, 30), "BENIGNO"),
|
||||
("P05", 0, D(2025, 9, 10), D(2025, 9, 25), None), # a report without a grade
|
||||
("P06", 0, D(2025, 9, 1), D(2025, 9, 10), "BENIGNO"), # two biopsies of one mammogram: the later report is shown
|
||||
("P06", 0, D(2025, 10, 1), D(2025, 10, 20), "CARCINOMA_IN_SITU"),
|
||||
)
|
||||
EN_COHORTE = {f"P{n:02d}" for n in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17)}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n)
|
||||
for h, (n, _) in PACIENTES.items()}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
mastografias: dict[tuple[str, int], Mastografia] = {}
|
||||
for hospital, (_, tomas) in PACIENTES.items():
|
||||
for indice, (toma, birads, reporte) in enumerate(tomas):
|
||||
mastografias[hospital, indice] = Mastografia(
|
||||
pac_id=pacientes[hospital].pac_id, pac_id_hospital=hospital, mast_fecha_toma=toma,
|
||||
mast_calidad_imagen="SATISFACTORIO", mast_birads=birads, mast_fecha_reporte=reporte)
|
||||
sesion.add_all(mastografias.values())
|
||||
sesion.flush()
|
||||
for hospital, indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
m = mastografias[hospital, indice]
|
||||
sesion.add(BiopsiaMama(pac_id=m.pac_id, pac_id_hospital=hospital, mast_id=m.mast_id, bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte, bx_grado_histologico=grado))
|
||||
sesion.commit()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de("cama", tmp_path_factory.mktemp("cama"), datos=insertar)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(base):
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
|
||||
return flask.test_client()
|
||||
|
||||
|
||||
def get(app, ruta="/cama/seguimiento", **params):
|
||||
return app.get(ruta, query_string={"corte": CORTE, "meses": 0, **params})
|
||||
|
||||
|
||||
def pacs(respuesta) -> list[str]:
|
||||
return [i["pac_id"] for i in respuesta.get_json()["items"]]
|
||||
|
||||
|
||||
def hospital_de(base) -> dict[str, str]:
|
||||
"""pac_id (text) -> the source id, to translate the invented names back."""
|
||||
with Session(base.motor) as sesion:
|
||||
return {str(p.pac_id): p.pac_id_hospital for p in sesion.exec(select(Paciente))}
|
||||
|
||||
|
||||
def test_the_cohort_holds_each_patient_once_through_her_latest_reported_mammogram(base, app):
|
||||
"""Pins down: the cohort at 2025-12-31 is exactly the patients whose latest mammogram reported by then is BI-RADS
|
||||
4 to 6, once each: P15's latest is a 2 and P16's 5 is reported after the cut-off. Fails if a patient is listed twice,
|
||||
if an earlier BI-RADS 5 outlives a later 2, or if a report after the cut-off counts."""
|
||||
cuerpo = get(app, page_size=200).get_json()
|
||||
nombres = hospital_de(base)
|
||||
assert {nombres[p] for p in pacs(get(app, page_size=200))} == EN_COHORTE
|
||||
assert len(pacs(get(app, page_size=200))) == len(set(pacs(get(app, page_size=200)))) == 15
|
||||
assert cuerpo["paginacion"]["total_items"] == 15
|
||||
|
||||
|
||||
def test_the_same_data_gives_the_same_cohort_and_a_later_cutoff_adds_what_was_reported(base, app):
|
||||
"""Pins down: asking twice gives the same rows in the same order, including P17 (two mammograms the same day, one
|
||||
row), and a cut-off after P16's report brings its BI-RADS 5 in. Fails if the choice depends on row order, or if the
|
||||
cut-off doesn't move the cohort."""
|
||||
primero, segundo = get(app, page_size=200).get_json(), get(app, page_size=200).get_json()
|
||||
assert primero["items"] == segundo["items"]
|
||||
nombres = hospital_de(base)
|
||||
despues = get(app, corte="2026-01-31", page_size=200)
|
||||
assert "P16" in {nombres[p] for p in pacs(despues)}
|
||||
assert [i["birads"] for i in despues.get_json()["items"] if nombres[i["pac_id"]] == "P16"] == ["BIRADS_5"]
|
||||
|
||||
|
||||
def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
|
||||
"""Pins down: P01's invasive carcinoma shows with its report date; P02's biopsy, reported in 2026, doesn't exist at
|
||||
2025-12-31 and does at 2026-01-31; P05's report without a grade shows its date and no result. Fails if a later
|
||||
biopsy leaks into an earlier cut-off or a gradeless report is read as no biopsy."""
|
||||
nombres = hospital_de(base)
|
||||
en = lambda r: {nombres[i["pac_id"]]: i for i in r.get_json()["items"]}
|
||||
antes, despues = en(get(app, page_size=200)), en(get(app, corte="2026-01-31", page_size=200))
|
||||
assert (antes["P01"]["biopsia"], antes["P01"]["biopsia_fecha"]) == ("CARCINOMA_INVASOR", "2025-12-20")
|
||||
assert (antes["P02"]["biopsia"], antes["P02"]["biopsia_fecha"]) == (None, None)
|
||||
assert (despues["P02"]["biopsia"], despues["P02"]["biopsia_fecha"]) == ("CARCINOMA_IN_SITU", "2026-01-10")
|
||||
assert (antes["P05"]["biopsia"], antes["P05"]["biopsia_fecha"]) == (None, "2025-09-25")
|
||||
assert (antes["P06"]["biopsia"], antes["P06"]["biopsia_fecha"]) == ("CARCINOMA_IN_SITU", "2025-10-20")
|
||||
|
||||
|
||||
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, the clinical scenario, the provisional status and priority of her pathway and the days from the mammogram to
|
||||
the diagnosis: no pseudonym, and no source id anywhere in the body. Fails if a field is added or dropped, or the
|
||||
hospital's identifier leaks."""
|
||||
respuesta = get(app, page_size=200)
|
||||
cuerpo = respuesta.get_json()
|
||||
assert cuerpo["simulado"] is True
|
||||
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
|
||||
"escenario_clinico", "estatus", "prioridad", "dias_mastografia_diagnostico"} for i in cuerpo["items"])
|
||||
assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"}
|
||||
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
|
||||
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
|
||||
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
|
||||
assert respuesta.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_age_groups_come_from_the_platform_parameter_at_the_cutoff(base, app):
|
||||
"""Pins down: groups are `cama.grupos_edad` (`<40`, `40-49`, `50-59`, `60-69`, `70+`); a patient born on 1976-01-01 is
|
||||
still 49 on 2025-12-31 and turns 50 the next day; a missing or later birth date is `SIN_DATO`. Fails if the age is
|
||||
counted in years of birth or the groups are written in the code."""
|
||||
nombres = hospital_de(base)
|
||||
edad = lambda c: {nombres[i["pac_id"]]: i["grupo_edad"] for i in get(app, corte=c, page_size=200).get_json()["items"]}
|
||||
assert edad(CORTE)["P04"] == "40-49" and edad(CORTE)["P01"] == "60-69" and edad(CORTE)["P06"] == "70+"
|
||||
assert edad("2026-01-31")["P04"] == "50-59"
|
||||
grupos = listing.grupos_de_edad(Session(base.motor))
|
||||
assert grupos == ["<40", "40-49", "50-59", "60-69", "70+"]
|
||||
assert cohort.grupo_de_edad(None, D(2025, 1, 1), []) == cohort.SIN_DATO
|
||||
assert cohort.grupo_de_edad(D(2026, 1, 1), D(2025, 1, 1), []) == cohort.SIN_DATO
|
||||
|
||||
|
||||
def test_filters_combine_with_and_and_the_window_follows_the_mammogram_date(base, app):
|
||||
"""Pins down: BI-RADS 5 selects six patients; adding the biopsy filter narrows with AND (a group of fewer than five
|
||||
is then refused); a one-month window keeps the mammograms of December. Fails if filters are ORed or the window
|
||||
reads another date."""
|
||||
# P01-P06 and, when it wins the tie of its two mammograms, P17.
|
||||
assert len(pacs(get(app, birads="BIRADS_5", page_size=200))) in (6, 7)
|
||||
assert len(pacs(get(app, birads="BIRADS_4A", page_size=200))) in (5, 6)
|
||||
assert get(app, birads="BIRADS_5", biopsia="BENIGNO").status_code == 403
|
||||
un_mes = get(app, meses=1, page_size=200)
|
||||
assert un_mes.status_code == 200
|
||||
assert {i["mastografia_fecha"][:7] for i in un_mes.get_json()["items"]} == {"2025-12"}
|
||||
assert un_mes.get_json()["ventana"] == {"meses": 1, "desde": "2025-12-01", "hasta": CORTE}
|
||||
|
||||
|
||||
def test_a_selection_of_fewer_than_five_is_never_served_by_any_route(base, app):
|
||||
"""Pins down: groups of 1 to 4 (BI-RADS 6, BI-RADS 4 without subcategory, a rare combination) and filtered
|
||||
selections of none get 403 with the reason `supresion`, on the list and on the file alike. Fails if a filter or a
|
||||
window combination isolates a small group, or the file skips the rule the list applies."""
|
||||
for ruta in ("/cama/seguimiento", "/cama/seguimiento/exportacion"):
|
||||
for filtros in ({"birads": "BIRADS_6"}, {"birads": "BIRADS_4"}, {"birads": "BIRADS_5", "biopsia": "SIN_DATO"},
|
||||
{"grupo_edad": "<40"}):
|
||||
respuesta = get(app, ruta, **filtros)
|
||||
assert respuesta.status_code == 403, (ruta, filtros)
|
||||
assert respuesta.get_json()["motivo"] == "supresion"
|
||||
assert get(app, meses=1, birads="BIRADS_5").status_code == 403 # a window is a filter too
|
||||
|
||||
|
||||
def test_the_whole_cohort_is_refused_when_it_has_one_to_four_patients_and_is_empty_when_it_has_none(base, app):
|
||||
"""Pins down: the only selection that may be empty is the whole cohort with no window and no filter; with two
|
||||
patients it is refused. Fails if a small whole cohort is published or an empty one is an error."""
|
||||
assert get(app, corte="2025-06-20").status_code == 403
|
||||
vacia = get(app, corte="2025-01-01")
|
||||
assert vacia.status_code == 200 and vacia.get_json()["items"] == []
|
||||
assert vacia.get_json()["paginacion"] == {"page": 1, "page_size": 50, "total_items": 0, "total_pages": 0}
|
||||
assert vacia.get_json()["ventana"]["desde"] == "2025-01-01"
|
||||
|
||||
|
||||
def test_pages_are_stable_and_a_page_past_the_last_is_a_404(base, app):
|
||||
"""Pins down: three pages of six give 15 rows in the same order as one big page, newest mammogram first and `pac_id`
|
||||
after; page 4 is 404. Fails if pages overlap or reorder, or a page beyond the end answers 200."""
|
||||
todo = pacs(get(app, page_size=200))
|
||||
paginas = [pacs(get(app, page_size=6, page=n)) for n in (1, 2, 3)]
|
||||
assert [p for pagina in paginas for p in pagina] == todo
|
||||
assert [len(p) for p in paginas] == [6, 6, 3]
|
||||
assert get(app, page_size=6, page=4).status_code == 404
|
||||
fechas = [i["mastografia_fecha"] for i in get(app, page_size=200).get_json()["items"]]
|
||||
assert fechas == sorted(fechas, reverse=True)
|
||||
|
||||
|
||||
def test_the_file_has_the_rows_of_the_pages_and_a_size_limit(base, app, monkeypatch):
|
||||
"""Pins down: `/seguimiento/exportacion` returns every row of the selection with the list's header; it is refused
|
||||
over `EXPORTACION_MAXIMA` (413). Fails if the file and the list disagree about who is selected."""
|
||||
archivo = get(app, "/cama/seguimiento/exportacion").get_json()
|
||||
assert [i["pac_id"] for i in archivo["items"]] == pacs(get(app, page_size=200)) and archivo["total_items"] == 15
|
||||
assert archivo["revision"] == get(app).get_json()["revision"]
|
||||
monkeypatch.setattr(listing, "EXPORTACION_MAXIMA", 3)
|
||||
assert get(app, "/cama/seguimiento/exportacion").status_code == 413
|
||||
|
||||
|
||||
def test_the_revision_names_cohort_version_data_and_cutoff(base, app):
|
||||
"""Pins down: quoting the revision read opens the same list; another cut-off, a new load of data and another
|
||||
cohort give another revision, and a stale one is a 409. Fails if the revision ignores a part, or a client can read a
|
||||
list under a revision that isn't the server's."""
|
||||
cuerpo = get(app).get_json()
|
||||
contexto = {k: cuerpo[k] for k in ("cohorte", "escenario", "revision")}
|
||||
assert re.fullmatch(r"[0-9a-f]{64}", cuerpo["revision"])
|
||||
assert get(app, **contexto).status_code == 200
|
||||
otro_corte = get(app, corte="2026-01-31").get_json()["revision"]
|
||||
assert otro_corte != cuerpo["revision"]
|
||||
assert get(app, **{**contexto, "revision": otro_corte}).status_code == 409
|
||||
assert get(app, **{**contexto, "cohorte": "otra"}).status_code == 409
|
||||
assert get(app, **{**contexto, "escenario": "otro"}).status_code == 409
|
||||
assert get(app, **{**contexto, "revision": ""}).status_code == 400
|
||||
assert get(app, cohorte=contexto["cohorte"]).status_code == 400 # the three go together
|
||||
|
||||
|
||||
def test_new_loaded_rows_change_the_revision_and_a_load_without_changes_does_not(base, app):
|
||||
"""Pins down: a load that added rows gives the cohort a new build and so a new revision; a load that added or changed
|
||||
none (a recalculation) leaves it. Fails if every cycle invalidates the clients' pages, or new data goes unnoticed."""
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
antes = get(app).get_json()["revision"]
|
||||
with Session(base.motor) as sesion:
|
||||
sesion.add(TABLAS.Carga(fuente="mastografia", inicio=datetime(2026, 1, 1, tzinfo=timezone.utc), filas_nuevas=0, filas_cambiadas=0, filas_sin_cambio=9))
|
||||
sesion.commit()
|
||||
assert get(app).get_json()["revision"] == antes
|
||||
sesion.add(TABLAS.Carga(fuente="mastografia", inicio=datetime(2026, 1, 2, tzinfo=timezone.utc), filas_nuevas=1))
|
||||
sesion.commit()
|
||||
assert get(app).get_json()["revision"] != antes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("params", [
|
||||
{"corte": "31/12/2025"}, {"corte": "2025-02-30"}, {"corte": "2999-01-01"}, {"meses": 2}, {"meses": "x"},
|
||||
{"page": 0}, {"page_size": 201}, {"birads": "BIRADS_9"}, {"grupo_edad": "20-29"}, {"biopsia": "MALIGNO"},
|
||||
{"estatus": "ALTA"}, {"prioridad": "ALTA"}, {"birads": ""},
|
||||
])
|
||||
def test_a_badly_written_request_is_a_400_before_anything_is_counted(app, params):
|
||||
"""Pins down: a malformed date, a future one, a window or page out of range, an unknown parameter (the retired
|
||||
status and priority included) or filter value is a 400, never a small-group 403. Fails if validation moves after
|
||||
the selection."""
|
||||
assert get(app, **params).status_code == 400
|
||||
|
||||
|
||||
def test_a_repeated_parameter_is_a_400(app):
|
||||
"""Pins down: `birads` twice is refused, so a request can't hide a filter. Fails if the first or last one is taken."""
|
||||
assert app.get("/cama/seguimiento?corte=2025-12-31&meses=0&birads=BIRADS_5&birads=BIRADS_6").status_code == 400
|
||||
|
||||
|
||||
def test_the_defaults_are_today_and_a_three_month_window(app):
|
||||
"""Pins down: without `corte` the cut-off is today and without `meses` the window is three months; none of the
|
||||
invented 2025 mammograms is that recent, so the window selects nobody and is refused. Fails if the defaults change."""
|
||||
respuesta = app.get("/cama/seguimiento")
|
||||
assert respuesta.status_code == 403 and respuesta.get_json()["motivo"] == "supresion"
|
||||
assert json.loads(get(app).get_data())["ventana"]["meses"] == 0
|
||||
assert date.today() - timedelta(days=1) > D(2025, 12, 31)
|
||||
|
||||
|
||||
def test_without_the_cohort_view_the_answer_is_an_informative_503(tmp_path):
|
||||
"""Pins down: a database whose indicator cycle hasn't created the event views answers 503 with the reason `cohorte`
|
||||
on both routes, not a server error. Fails if a missing view surfaces as a 500 or an empty list."""
|
||||
sin_ciclo = base_de("cama", tmp_path, datos=insertar)
|
||||
try:
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(follow_up_blueprint(lambda: Session(sin_ciclo.motor)), url_prefix="/cama")
|
||||
cliente = flask.test_client()
|
||||
for ruta in ("/cama/seguimiento", "/cama/seguimiento/exportacion"):
|
||||
respuesta = cliente.get(ruta, query_string={"corte": CORTE, "meses": 0})
|
||||
assert respuesta.status_code == 503 and respuesta.get_json()["motivo"] == "cohorte"
|
||||
finally:
|
||||
sin_ciclo.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def con_vista_a_mano(tmp_path):
|
||||
"""A CaMa database with the platform's parameters and the cohort's candidates written by hand: the view is replaced by
|
||||
a table, so a test can hold the contradictory duplicates that staging can't produce."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
|
||||
base = base_de("cama", tmp_path, datos=lambda sesion: None)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
from sqlalchemy import text
|
||||
|
||||
def escribir(filas):
|
||||
with base.motor.begin() as c:
|
||||
c.execute(text("drop view cama_cohorte_birads"))
|
||||
c.execute(text("create table cama_cohorte_birads (pac_id integer, procedimiento_id integer, fuente_id text, fecha_toma date, "
|
||||
"reporte_id integer, fecha_reporte date, birads text, fecha_nacimiento date, biopsia_id integer, "
|
||||
"biopsia_fuente_id text, biopsia_fecha_reporte date, biopsia_grado text)"))
|
||||
for fila in filas:
|
||||
c.execute(text("insert into cama_cohorte_birads values (:pac_id, :procedimiento_id, :fuente_id, :fecha_toma, :reporte_id, "
|
||||
":fecha_reporte, :birads, :fecha_nacimiento, :biopsia_id, :biopsia_fuente_id, :biopsia_fecha_reporte, :biopsia_grado)"),
|
||||
{"biopsia_id": None, "biopsia_fuente_id": None, "biopsia_fecha_reporte": None, "biopsia_grado": None, **fila})
|
||||
yield base, escribir
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
MAMOGRAFIA = {"pac_id": 1, "procedimiento_id": 10, "fuente_id": "10", "fecha_toma": "2025-11-01", "reporte_id": 11,
|
||||
"fecha_reporte": "2025-11-08", "fecha_nacimiento": "1970-01-01"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("orden", [1, -1])
|
||||
def test_contradictory_duplicates_resolve_the_same_way_whatever_the_row_order(con_vista_a_mano, orden):
|
||||
"""Pins down: one report with two different BI-RADS (4A and 5) counts as the more severe, a biopsy report with two
|
||||
grades on the same date shows the more severe, identical rows repeated by a join count once, and the answer doesn't
|
||||
depend on the order the rows come in. Fails if the first row read wins, a patient appears twice, or the choice
|
||||
changes with the order."""
|
||||
base, escribir = con_vista_a_mano
|
||||
filas = [
|
||||
{**MAMOGRAFIA, "birads": "B4A", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "BENIGNO"},
|
||||
{**MAMOGRAFIA, "birads": "B5", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "CARCINOMA_INVASOR"},
|
||||
{**MAMOGRAFIA, "birads": "B5", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "CARCINOMA_INVASOR"},
|
||||
]
|
||||
escribir(filas[::orden])
|
||||
with Session(base.motor) as sesion:
|
||||
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
|
||||
assert len(cohorte_) == 1
|
||||
assert (cohorte_[0].birads, cohorte_[0].biopsia) == ("BIRADS_5", "CARCINOMA_INVASOR")
|
||||
|
||||
|
||||
def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_stay_two(con_vista_a_mano):
|
||||
"""Pins down: a mammogram with two reports counts through the later report; two patients stay two rows. Fails if both
|
||||
reports become two rows of one patient."""
|
||||
base, escribir = con_vista_a_mano
|
||||
escribir([
|
||||
{**MAMOGRAFIA, "birads": "B4A", "reporte_id": 11, "fecha_reporte": "2025-11-08"},
|
||||
{**MAMOGRAFIA, "birads": "B5", "reporte_id": 12, "fecha_reporte": "2025-11-15"},
|
||||
{**MAMOGRAFIA, "pac_id": 2, "procedimiento_id": 30, "fuente_id": "30", "reporte_id": 31, "birads": "B6"},
|
||||
])
|
||||
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"]
|
||||
@@ -0,0 +1,310 @@
|
||||
"""What this module covers: the three CaMa measures of L3, answered on request from dbt's semantic layer over the follow-up
|
||||
fixture's invented patients (plus three on a period boundary and the diagnosing notes of the cases below): the detection
|
||||
rate (`CAMA_TASA_DETECCION_HISTOPATOLOGICA`, C1), the time from the mammogram's result to the diagnosis
|
||||
(`CAMA_DIAS_RESULTADO_DIAGNOSTICO`, C3r) and the histopathological result by BI-RADS (`CAMA_HISTOPATOLOGIA_BIRADS`, C2
|
||||
stratified by BI-RADS). Every number here is worked out by hand from the cases, not read from the measure.
|
||||
|
||||
Fixtures: `base`, the CaMa database loaded from `insertar_l3` through the cycle up to `event_models` (dbt's views, the three
|
||||
new ones included); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it). Suppression is off (threshold 1).
|
||||
|
||||
Cases added to the follow-up fixture's (see `test_cama_follow_up.py`):
|
||||
- P18 / P19 / P20: biopsies reported on the last day of a semester (06-30), the first day of the next (07-01) and the last
|
||||
day of the year (12-31): which period each report counts in, and the inclusive event cut-off.
|
||||
- Notes (a diagnosing note is a CIE-10 of the list written by oncologic surgery): P01 12 days after her report, P07 the
|
||||
same day, P08 a note between her mammogram and her report (not counted) and one 37 days after it, P09 193 days after
|
||||
(beyond the horizon), P03 an earlier breast cancer note (leaves her out), P04 a note by a specialty that doesn't
|
||||
diagnose, P12 the same day, P20 39 days after.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, Paciente
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from test_cama_follow_up import UNTIL_MODELS, insertar
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.fhir.measures import measure_report
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
|
||||
D = date
|
||||
TASA = "cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA"
|
||||
DIAS = "cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO"
|
||||
HISTO = "cama/CAMA_HISTOPATOLOGIA_BIRADS"
|
||||
BIRADS_PACIENTE = "cama/CAMA_BIRADS456_PACIENTE"
|
||||
DIAS_TOMA = "cama/CAMA_DIAS_TOMA_DIAGNOSTICO"
|
||||
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
|
||||
NUEVOS = {
|
||||
"P18": (D(1970, 1, 1), [(D(2025, 6, 20), "B4A", D(2025, 6, 25))]),
|
||||
"P19": (D(1970, 1, 1), [(D(2025, 6, 25), "B5", D(2025, 6, 28))]),
|
||||
"P20": (D(1970, 1, 1), [(D(2025, 12, 20), "B5", D(2025, 12, 24))]),
|
||||
}
|
||||
# (patient, request date, report date, grade): the mammogram of each of them is its first
|
||||
BIOPSIAS_NUEVAS = (
|
||||
("P18", D(2025, 6, 26), D(2025, 6, 30), "BENIGNO"),
|
||||
("P19", D(2025, 6, 29), D(2025, 7, 1), "CARCINOMA_INVASOR"),
|
||||
("P20", D(2025, 12, 28), D(2025, 12, 31), "CARCINOMA_IN_SITU"),
|
||||
)
|
||||
# (patient, date, CIE-10, specialty)
|
||||
NOTAS = (
|
||||
("P01", D(2025, 12, 20), "R92", ONCOLOGIA),
|
||||
("P07", D(2025, 12, 17), "N60", ONCOLOGIA),
|
||||
("P08", D(2025, 12, 5), "R92", ONCOLOGIA),
|
||||
("P08", D(2026, 1, 15), "R92", ONCOLOGIA),
|
||||
("P09", D(2026, 5, 20), "R92", ONCOLOGIA),
|
||||
("P03", D(2025, 1, 10), "C50", FAMILIAR),
|
||||
("P03", D(2025, 12, 1), "R92", ONCOLOGIA),
|
||||
("P04", D(2025, 11, 10), "R92", FAMILIAR),
|
||||
("P12", D(2025, 12, 22), "Z123", ONCOLOGIA),
|
||||
("P20", D(2026, 2, 1), "R92", ONCOLOGIA),
|
||||
)
|
||||
CORTE = D(2025, 12, 31)
|
||||
|
||||
|
||||
def insertar_l3(sesion: Session) -> None:
|
||||
insertar(sesion)
|
||||
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n) for h, (n, _) in NUEVOS.items()}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
mastografias = {}
|
||||
for hospital, (_, tomas) in NUEVOS.items():
|
||||
toma, birads, reporte = tomas[0]
|
||||
mastografias[hospital] = Mastografia(pac_id=pacientes[hospital].pac_id, pac_id_hospital=hospital, mast_fecha_toma=toma,
|
||||
mast_calidad_imagen="SATISFACTORIO", mast_birads=birads, mast_fecha_reporte=reporte)
|
||||
sesion.add_all(mastografias.values())
|
||||
sesion.flush()
|
||||
for hospital, solicitud, reporte, grado in BIOPSIAS_NUEVAS:
|
||||
m = mastografias[hospital]
|
||||
sesion.add(BiopsiaMama(pac_id=m.pac_id, pac_id_hospital=hospital, mast_id=m.mast_id, bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte, bx_grado_histologico=grado))
|
||||
todos = {p.pac_id_hospital: p for p in sesion.exec(select(Paciente))}
|
||||
sesion.add_all(NotaMedica(pac_id=todos[h].pac_id, pac_id_hospital=h, nm_id_hospital=f"NM-{i:03d}", nm_fecha=fecha,
|
||||
nm_cie_codigo=cie, nm_especialidad=esp) for i, (h, fecha, cie, esp) in enumerate(NOTAS, start=1))
|
||||
sesion.commit()
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory, manifest):
|
||||
carpeta = tmp_path_factory.mktemp("cama_l3")
|
||||
sin_supresion = carpeta / "parametros.toml"
|
||||
sin_supresion.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
||||
base = base_de("cama", carpeta, datos=insertar_l3)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, "history": d.history_repository,
|
||||
"queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def proporcion(base, manifest, periodo, corte=None):
|
||||
r = answer("cama", measure_definitions(manifest)[TASA], Question(TASA, periodo, corte), **repositories(base))
|
||||
return r.numerator, r.denominator
|
||||
|
||||
|
||||
def duracion(base, manifest, periodo, corte=None, url=DIAS):
|
||||
return answer_duration("cama", duration_definitions(manifest)[url], Question(url, periodo, corte), **repositories(base))
|
||||
|
||||
|
||||
def composicion(base, manifest, periodo, corte=None, conocimiento=None, url=HISTO):
|
||||
return answer_composition("cama", composition_definitions(manifest)[url], Question(url, periodo, corte, conocimiento),
|
||||
**repositories(base))
|
||||
|
||||
|
||||
def matriz(resultado) -> dict:
|
||||
return {(b, c): n for b, por in resultado.strata["birads"].items() for c, n in por.items()}
|
||||
|
||||
|
||||
# --- the detection rate -----------------------------------------------------------------------------------------------
|
||||
|
||||
def test_the_detection_rate_counts_biopsy_reports_with_a_known_result_by_the_day_of_the_report(base, manifest):
|
||||
"""Pins down: the rate's units are biopsy reports dated by the report, over those with a known grade. The semester 1 holds
|
||||
P18's benign report of 06-30 (the last day); the semester 2 holds P19's invasive of 07-01 (the first), P20's in situ of 12-31
|
||||
(the last), P01's invasive, P04's benign and P06's two (benign and in situ): 6 known and 4 malignant; P05's has no grade, so it
|
||||
is outside both parts. Fails if a boundary day falls in the wrong period, a report without grade enters the denominator, or
|
||||
each patient (P06 has two reports) counts once instead of each report."""
|
||||
assert proporcion(base, manifest, "2025-S1") == (0, 1)
|
||||
assert proporcion(base, manifest, "2025-S2") == (4, 6)
|
||||
|
||||
|
||||
def test_the_detection_rate_by_month_adds_up_to_the_semesters_and_the_cutoff_is_inclusive(base, manifest):
|
||||
"""Pins down: the months of a semester hold the same reports as the semester (every report is in exactly one month), and a
|
||||
cut-off on the day of a report counts it while the day before doesn't. Fails if the monthly and the semester counts drift
|
||||
or the event cut-off excludes its own day."""
|
||||
meses = ["2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"]
|
||||
por_mes = [proporcion(base, manifest, m) for m in meses]
|
||||
assert (sum(n for n, _ in por_mes), sum(d for _, d in por_mes)) == proporcion(base, manifest, "2025-S2")
|
||||
assert proporcion(base, manifest, "2025-12") == (2, 2)
|
||||
assert proporcion(base, manifest, "2025-12", D(2025, 12, 31)) == (2, 2)
|
||||
assert proporcion(base, manifest, "2025-12", D(2025, 12, 30)) == (1, 1)
|
||||
|
||||
|
||||
def test_the_detection_rate_is_a_proportion_among_biopsies_and_not_the_confirmation_of_suspicious_mammograms(base, manifest):
|
||||
"""Pins down: the rate and the confirmation proportion answer different questions over the same data. In the semester 2 the
|
||||
rate counts 6 biopsy reports with a result; the confirmation counts mammograms of suspicion with a biopsy (its denominator
|
||||
is mammograms, not reports). Fails if the two measures end up with the same counts."""
|
||||
confirmacion = "cama/CAMA_CONFIRMACION_BIRADS45"
|
||||
r = answer("cama", measure_definitions(manifest)[confirmacion], Question(confirmacion, "2025-S2"), **repositories(base))
|
||||
assert (r.numerator, r.denominator) != (4, 6)
|
||||
assert r.denominator >= 15, "its denominator is the mammograms of suspicion of the period"
|
||||
|
||||
|
||||
def test_the_detection_flags_of_the_view_follow_the_parameters(base):
|
||||
"""Pins down: the view's flags are the grade lists of dbt's vars, which a test keeps equal to the parameter table's: known
|
||||
result = the catalog's grades, malignant = `cama.biopsia_cancer`. Fails if the two copies drift apart."""
|
||||
import tomllib
|
||||
|
||||
reglas = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
|
||||
with base.motor.connect() as c:
|
||||
flags = {(g, k, m) for g, k, m in c.execute(text("select distinct grado, con_resultado, maligno from cama_deteccion_biopsia"))}
|
||||
cancer = set(reglas["cama"]["biopsia_cancer"]["valor"])
|
||||
catalogo = {x["clave"] for x in reglas["cama"]["catalogos"]["biopsia"]["valor"]}
|
||||
assert flags == {(g, int(g in catalogo), int(g in cancer)) for g in {f[0] for f in flags}}
|
||||
assert {None, "BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"} == {f[0] for f in flags}
|
||||
assert (None, 0, 0) in flags
|
||||
|
||||
|
||||
# --- the time from the result to the diagnosis -------------------------------------------------------------------------
|
||||
|
||||
def test_the_time_from_result_to_diagnosis_counts_from_the_report_to_the_first_note_on_or_after_it(base, manifest):
|
||||
"""Pins down, in the semester 2 (16 mammograms with a report, P03's left out by her earlier breast cancer note): five have a
|
||||
diagnosing note within the horizon: P01 12 days, P07 and P12 the same day (0), P08 37 (her 12-05 note is before her report
|
||||
and doesn't count) and P20 39; the other eleven are excluded and counted (P09's note is 193 days after, P04's is of a
|
||||
specialty that doesn't diagnose, the rest have none). Median 12. Fails if a note before the report is used, the horizon
|
||||
isn't applied, a non-diagnosing specialty counts or an excluded mammogram isn't counted."""
|
||||
r = duracion(base, manifest, "2025-S2")
|
||||
assert (r.initial, r.n, r.excluded, r.median) == (16, 5, 11, 12.0)
|
||||
|
||||
|
||||
def test_the_event_cutoff_leaves_out_the_notes_after_it_and_does_not_measure_what_is_still_inside_the_horizon(base, manifest):
|
||||
"""Pins down, at 2025-12-31: the notes of 2026 don't exist yet (P08's and P20's) and every mammogram of the semester is
|
||||
still inside its horizon (180 days from its report), so those without a note are neither measured nor excluded: three
|
||||
observations (0, 0 and 12 days, median 0) are the whole population. The same rule as the mammogram-to-result measure: a
|
||||
mammogram is excluded only once its horizon has passed without a note. Fails if a note after the cut-off is measured or if
|
||||
a mammogram that can still get its note is counted as excluded."""
|
||||
r = duracion(base, manifest, "2025-S2", CORTE)
|
||||
assert (r.initial, r.n, r.excluded, r.median) == (3, 3, 0, 0.0)
|
||||
# Once every horizon of the semester has passed (the last report is 2025-12-27) the unmeasured are excluded and counted.
|
||||
tarde = duracion(base, manifest, "2025-S2", D(2026, 7, 1))
|
||||
assert (tarde.initial, tarde.n, tarde.excluded) == (16, 5, 11)
|
||||
|
||||
|
||||
def test_the_result_to_diagnosis_days_are_the_mammogram_to_diagnosis_days_minus_the_days_to_the_report(base):
|
||||
"""Pins down: for a mammogram whose first note is on or after its report, the days from the report equal the days of the
|
||||
mammogram-to-diagnosis measure minus the days from the mammogram to its report (the same note, another origin): P01 19-7,
|
||||
P07 7-7, P12 7-7. P08 is the difference by design (that measure takes her 12-05 note, this one her 01-15 note). Fails if the
|
||||
two measures read different notes where they should read the same."""
|
||||
with base.motor.connect() as c:
|
||||
nuevo = {h: d for h, d in c.execute(text(
|
||||
"select p.pac_id_hospital, r.dias_reporte_diagnostico from cama_resultado_diagnostico r join paciente p on p.pac_id = r.pac_id"))}
|
||||
viejo = {h: (d, t) for h, d, t in c.execute(text(
|
||||
"select p.pac_id_hospital, m.dias_toma_diagnostico, m.dias_toma_reporte from cama_tomas_mastografia m "
|
||||
"join paciente p on p.pac_id = m.pac_id"))}
|
||||
for h in ("P01", "P07", "P12"):
|
||||
assert nuevo[h] == viejo[h][0] - viejo[h][1], h
|
||||
assert (nuevo["P08"], viejo["P08"][0]) == (37, 3)
|
||||
|
||||
|
||||
def test_a_mammogram_without_a_report_is_not_in_the_population_and_the_report_date_gives_the_period(base):
|
||||
"""Pins down: the model holds one row per mammogram with a report, dated by it: all 24 mammograms of the fixture have one,
|
||||
and P16's second (reported 2026-01-05) is dated 2026, outside the semester of its mammogram. Fails if the period is read from
|
||||
the date of the mammogram."""
|
||||
with base.motor.connect() as c:
|
||||
filas = c.execute(text("select p.pac_id_hospital, r.fecha_toma, r.fecha_reporte from cama_resultado_diagnostico r "
|
||||
"join paciente p on p.pac_id = r.pac_id where p.pac_id_hospital = 'P16' order by 2")).all()
|
||||
assert [tuple(map(str, f[1:])) for f in filas] == [("2025-05-01", "2025-05-08"), ("2025-12-20", "2026-01-05")]
|
||||
|
||||
|
||||
# --- the histopathological result by BI-RADS ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_matrix_of_the_semester_2_at_the_cutoff(base, manifest):
|
||||
"""Pins down, at 2025-12-31, one patient through her most severe mammogram of the semester: BI-RADS 5 (P01 invasive, P02
|
||||
without biopsy because hers is reported in 2026, P03 and P17 without biopsy, P04 benign, P05 a biopsy without grade, P06 in
|
||||
situ from her two biopsies, P20 in situ reported that same day), 4A (P07-P11 without biopsy), 6 (P12) and 4 without subcategory
|
||||
(P14). P15's semester-2 mammogram is a 2 and P16's 5 is reported in 2026: neither enters. P19 (a semester-1 mammogram) is out.
|
||||
Fails if the chosen mammogram, the biopsy of it, the cut-off or the grouping change."""
|
||||
r = composicion(base, manifest, "2025-S2", CORTE)
|
||||
assert matriz(r) == {
|
||||
("B5", "CARCINOMA_INVASOR"): 1, ("B5", "CARCINOMA_IN_SITU"): 2, ("B5", "BENIGNO"): 1, ("B5", "SIN_DATO"): 1, ("B5", "SIN_BIOPSIA"): 3,
|
||||
("B4A", "SIN_BIOPSIA"): 5, ("B6", "SIN_BIOPSIA"): 1, ("B4", "SIN_BIOPSIA"): 1,
|
||||
}
|
||||
assert sum(r.categories.values()) == 15
|
||||
|
||||
|
||||
def test_without_a_cutoff_the_biopsy_reported_later_and_the_late_report_count(base, manifest):
|
||||
"""Pins down: with no event cut-off P02's biopsy (reported 2026-01-10, in situ) is hers and P16's BI-RADS 5 (reported
|
||||
2026-01-05) is her semester's: one more in situ, and one more without biopsy. Fails if a cut-off is applied by default."""
|
||||
r = composicion(base, manifest, "2025-S2")
|
||||
assert matriz(r)[("B5", "CARCINOMA_IN_SITU")] == 3 and matriz(r)[("B5", "SIN_BIOPSIA")] == 3
|
||||
assert sum(r.categories.values()) == 16
|
||||
|
||||
|
||||
def test_the_semester_1_matrix_holds_each_patient_once(base, manifest):
|
||||
"""Pins down: P13 (BI-RADS 6, no biopsy), P15 (BI-RADS 5 of June, no biopsy), P18 (4A with her benign report of 06-30) and P19
|
||||
(BI-RADS 5 with her invasive report of 07-01, in the next semester: the biopsy belongs to her mammogram, not to the period of
|
||||
its report); P16's BI-RADS 1 is not admitted. Fails if a biopsy reported in the next period is lost."""
|
||||
r = composicion(base, manifest, "2025-S1", CORTE)
|
||||
assert matriz(r) == {("B6", "SIN_BIOPSIA"): 1, ("B5", "SIN_BIOPSIA"): 1, ("B4A", "BENIGNO"): 1, ("B5", "CARCINOMA_INVASOR"): 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("periodo", ["2025-S1", "2025-S2", "2025-06", "2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"])
|
||||
def test_the_matrix_counts_the_same_patients_as_the_birads_measure_in_every_period(base, manifest, periodo):
|
||||
"""Pins down: each period's BI-RADS strata equal the patients per category of CAMA_BIRADS456_PACIENTE (same rule: her most
|
||||
severe mammogram of the period), so Resumen's two cards never count different patients. Fails if the two measures choose
|
||||
other mammograms."""
|
||||
histo = composicion(base, manifest, periodo, CORTE)
|
||||
birads = composicion(base, manifest, periodo, CORTE, url=BIRADS_PACIENTE)
|
||||
por_birads = {b: sum(cs.values()) for b, cs in histo.strata["birads"].items()}
|
||||
assert por_birads == {b: n for b, n in birads.categories.items() if n}
|
||||
assert sum(histo.categories.values()) == sum(birads.categories.values())
|
||||
|
||||
|
||||
def test_a_knowledge_cutoff_later_the_same_day_still_sees_the_biopsies(base, manifest):
|
||||
"""Pins down the datetime compare of the biopsy's knowledge date: with a knowledge cut-off one second after the last load (the
|
||||
same day as the loads) every biopsy is known, as with none; with one before the first load nothing is. Fails if the biopsy's
|
||||
date is compared as text against the cut-off (`...T...` against `... ...`), which hid every biopsy on the day of the load."""
|
||||
with base.motor.connect() as c:
|
||||
ultima = c.execute(text("select max(inicio) from carga")).scalar()
|
||||
primera = c.execute(text("select min(inicio) from carga")).scalar()
|
||||
ultima = datetime.fromisoformat(str(ultima)).replace(tzinfo=timezone.utc) if isinstance(ultima, str) else ultima.replace(tzinfo=timezone.utc)
|
||||
primera = datetime.fromisoformat(str(primera)).replace(tzinfo=timezone.utc) if isinstance(primera, str) else primera.replace(tzinfo=timezone.utc)
|
||||
sin = composicion(base, manifest, "2025-S2", CORTE)
|
||||
con = composicion(base, manifest, "2025-S2", CORTE, ultima + timedelta(seconds=1))
|
||||
assert matriz(con) == matriz(sin)
|
||||
antes = composicion(base, manifest, "2025-S2", CORTE, primera - timedelta(days=1))
|
||||
assert antes.categories == {}
|
||||
|
||||
|
||||
def test_the_report_publishes_the_cross_of_birads_and_result_as_two_components(base, manifest):
|
||||
"""Pins down the FHIR report of the matrix: a stratifier coded by BI-RADS and by the biopsy grade whose strata carry the two
|
||||
components and the patients of each cell; the categories stratifier keeps the totals. Fails if the cross is published as
|
||||
marginals (the page couldn't rebuild the matrix) or a cell's count is not the matrix's."""
|
||||
definicion = composition_definitions(manifest)[HISTO]
|
||||
periodo = base.dominio.dim_periodo_repository.get("2025-S2")
|
||||
resultado = composicion(base, manifest, "2025-S2", CORTE)
|
||||
informe = measure_report(definicion, Question(HISTO, "2025-S2", CORTE), resultado, periodo, datetime.now(timezone.utc))
|
||||
grupo = informe["group"][0]
|
||||
assert [[c["coding"][0]["code"] for c in s["code"]] for s in grupo["stratifier"]] == [["biopsia_grado"], ["birads", "biopsia_grado"]]
|
||||
celdas = {tuple(c["value"]["coding"][0]["code"] for c in s["component"]): s["population"][0]["count"]
|
||||
for s in grupo["stratifier"][1]["stratum"]}
|
||||
assert celdas == matriz(resultado)
|
||||
assert sum(celdas.values()) == grupo["population"][0]["count"] == 15
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Isolated compiled-SQL regressions: repeated reports and identities across sources."""
|
||||
import json
|
||||
import sqlite3
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from test_cama_l3_measures import manifest
|
||||
|
||||
|
||||
def sql(manifest, name):
|
||||
nodes = json.loads(manifest.read_text())["nodes"].values()
|
||||
return next(n["compiled_code"] for n in nodes if n["name"] == name)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("days,expected", [(179, 179), (180, None)])
|
||||
def test_one_mammogram_uses_first_report_and_exclusive_180_day_horizon(manifest, days, expected):
|
||||
db = sqlite3.connect(":memory:")
|
||||
db.executescript('''
|
||||
create table cama_mastografias(procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id, reporte_id);
|
||||
create table cama_linea_de_tiempo(pac_id, tipo, fecha, conocida_en);
|
||||
create table dim_fecha(fecha, dia_num);
|
||||
create table carga(carga_id, inicio);
|
||||
create table procedimiento(procedimiento_id, fuente_tabla, fuente_id, pac_id, fecha, carga_id, padre_id, estudio_id, clase);
|
||||
create table observacion_clinica(procedimiento_id, resultado_id, valor_id, valor_fuente, carga_id);
|
||||
insert into carga values(1, '2026-11-17 00:00:00');
|
||||
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-06-20',1,10);
|
||||
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-07-10',1,11);
|
||||
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-06-20',1,12);
|
||||
insert into cama_linea_de_tiempo values(1,'diagnostico','2025-06-19','2026-11-17');
|
||||
insert into procedimiento values(1,'source','1',1,'2025-06-01',1,null,'mastografia','toma');
|
||||
insert into procedimiento select reporte_id,'source',cast(reporte_id as text),pac_id,fecha_reporte,reporte_carga_id,procedimiento_id,'mastografia','reporte' from cama_mastografias;
|
||||
''')
|
||||
start = date(2025, 6, 20)
|
||||
end = start + timedelta(days=days)
|
||||
db.execute("insert into cama_linea_de_tiempo values(1,'diagnostico',?,'2026-11-17')", (end.isoformat(),))
|
||||
for i in range(-30, 210):
|
||||
db.execute("insert into dim_fecha values(?,?)", ((start + timedelta(days=i)).isoformat(), i))
|
||||
db.execute("create view cama_resultado_diagnostico as " + sql(manifest, "cama_resultado_diagnostico"))
|
||||
assert db.execute('select procedimiento_id, fecha_reporte, dias_reporte_diagnostico from cama_resultado_diagnostico').fetchall() == [(1, '2025-06-20', expected)]
|
||||
# A note between reports belongs to the selected first report, never yields a negative interval.
|
||||
db.execute("insert into cama_linea_de_tiempo values(1,'diagnostico','2025-06-25','2026-11-17')")
|
||||
assert db.execute('select dias_reporte_diagnostico from cama_resultado_diagnostico').fetchall() == [(5,)]
|
||||
|
||||
|
||||
def test_detection_uses_platform_report_identity_even_when_source_ids_collide(manifest):
|
||||
db = sqlite3.connect(":memory:")
|
||||
db.executescript('''
|
||||
create table cama_reportes_biopsia(procedimiento_id, fuente_id, pac_id, fecha_reporte, grado, reporte_conocido_en);
|
||||
insert into cama_reportes_biopsia values(1,'7',1,'2025-06-30','BENIGNO','2026-11-17');
|
||||
insert into cama_reportes_biopsia values(2,'7',2,'2025-07-01','CARCINOMA_INVASOR','2026-11-17');
|
||||
insert into cama_reportes_biopsia values(3,'7',3,'2025-07-01',null,'2026-11-17');
|
||||
''')
|
||||
db.execute('create view cama_deteccion_biopsia as ' + sql(manifest, 'cama_deteccion_biopsia'))
|
||||
assert db.execute('select sum(maligno), sum(con_resultado), count(distinct procedimiento_id) from cama_deteccion_biopsia').fetchone() == (1, 2, 3)
|
||||
from webapi.metrics import measure_definitions
|
||||
d = measure_definitions(manifest)['cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA']
|
||||
assert d.denominator.measure_expr == d.numerator.measure_expr == 'procedimiento_id'
|
||||
@@ -0,0 +1,94 @@
|
||||
"""What this module covers: the publication metadata of CaMa's FHIR `Measure`s (figures and category captions), read
|
||||
from dbt's manifest alone.
|
||||
|
||||
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
|
||||
reference parameters, whose CaMa catalogs hold the captions and colours the dbt definitions repeat.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.fhir.measures import CATEGORY_LABEL, FIGURES, labels, measure_resource
|
||||
from webapi.kpis import definitions_of
|
||||
|
||||
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measures(manifest):
|
||||
"""Each CaMa measure as the API serves it, by its FHIR id."""
|
||||
titles = labels(manifest)
|
||||
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
|
||||
for d in definitions_of("cama", manifest).values()}
|
||||
|
||||
|
||||
def figures(measure: dict) -> list[str]:
|
||||
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
|
||||
|
||||
|
||||
def captions(measure: dict) -> dict[str, tuple[str, str]]:
|
||||
"""The measure's declared categories, in order: code -> (caption, colour)."""
|
||||
found = {}
|
||||
for e in measure["extension"]:
|
||||
if e["url"] == CATEGORY_LABEL:
|
||||
part = {p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
|
||||
found[part["codigo"]] = (part["etiqueta"], part["color"])
|
||||
return found
|
||||
|
||||
|
||||
def catalog(name: str) -> dict[str, tuple[str, str]]:
|
||||
with REFERENCE.open("rb") as f:
|
||||
entries = tomllib.load(f)["cama"]["catalogos"][name]["valor"]
|
||||
return {e["clave"]: (e["etiqueta"], e["color"]) for e in entries}
|
||||
|
||||
|
||||
def no_data() -> tuple[str, str]:
|
||||
with REFERENCE.open("rb") as f:
|
||||
v = tomllib.load(f)["cama"]["catalogos"]["sin_dato"]["valor"]
|
||||
return v["etiqueta"], v["color"]
|
||||
|
||||
|
||||
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
|
||||
"""Pins down: a distribution offers the donut and the bars, a duration its box plot, and the proportion and the
|
||||
analysis' measure none. Fails if a figure is declared that the page has no builder for, or one is dropped."""
|
||||
expected = {"CAMA-BIOPSIAS": ["fig_c2_donas", "fig_c2_barras"], "CAMA-BIRADS": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CAMA-BIRADS456-MASTOGRAFIA": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CAMA-BIRADS456-PACIENTE": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CAMA-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-EU38A": ["fig_c3r_caja"],
|
||||
"CAMA-CONFIRMACION-BIRADS45": [], "CAMA-BIRADS-CANCER-INVASOR": [],
|
||||
"CAMA-DIAS-RESULTADO-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-TASA-DETECCION-HISTOPATOLOGICA": [],
|
||||
"CAMA-HISTOPATOLOGIA-BIRADS": []}
|
||||
assert {i: figures(m) for i, m in measures.items()} == expected
|
||||
|
||||
|
||||
def test_the_category_captions_are_the_reference_catalogs(measures):
|
||||
"""Pins down: the captions, colours and order the dbt definitions publish equal `cama.catalogos.*` in the
|
||||
reference parameters (BI-RADS, BI-RADS 4 to 6, biopsy grade, plus «Sin dato» where a unit can lack the value).
|
||||
Fails if either side is edited without the other."""
|
||||
sin_dato = {"SIN_DATO": no_data()}
|
||||
assert captions(measures["CAMA-BIRADS"]) == {**catalog("birads"), **sin_dato}
|
||||
assert captions(measures["CAMA-BIRADS456-PACIENTE"]) == catalog("birads_4_a_6")
|
||||
assert captions(measures["CAMA-BIRADS456-MASTOGRAFIA"]) == catalog("birads_4_a_6")
|
||||
assert captions(measures["CAMA-BIOPSIAS"]) == {**catalog("biopsia"), **sin_dato}
|
||||
assert list(captions(measures["CAMA-BIRADS"])) == [*catalog("birads"), "SIN_DATO"]
|
||||
# The histopathological result by BI-RADS: the biopsy grades, then the patients without a biopsy and without a grade.
|
||||
assert captions(measures["CAMA-HISTOPATOLOGIA-BIRADS"]) == {**catalog("biopsia"), "SIN_BIOPSIA": ("Sin biopsia reportada", "#C9CDD2"), **sin_dato}
|
||||
|
||||
|
||||
def test_the_measures_without_categories_declare_none(measures):
|
||||
"""Pins down: proportions and durations carry no category captions. Fails if one is attached to a measure that
|
||||
has no categories."""
|
||||
for fhir_id in ("CAMA-CONFIRMACION-BIRADS45", "CAMA-DIAS-TOMA-DIAGNOSTICO", "CAMA-EU38A", "CAMA-DIAS-RESULTADO-DIAGNOSTICO",
|
||||
"CAMA-TASA-DETECCION-HISTOPATOLOGICA"):
|
||||
assert captions(measures[fhir_id]) == {}
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Verify default persistent cohort setup with retained legacy configuration."""
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from webapi.cama_runtime import configure_cama_cohort
|
||||
|
||||
|
||||
def test_default_reader_uses_shared_persistence(monkeypatch):
|
||||
"""The reader is registered without special cohort environment variables."""
|
||||
for key in ('CAMA_COHORT_SYNTHETIC', 'CAMA_COHORT_SECRET', 'CAMA_COHORT_ACCESS_TOKEN'):
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
app = Flask(__name__)
|
||||
configure_cama_cohort(app)
|
||||
assert callable(app.config['CAMA_COHORT_READER'])
|
||||
assert 'CAMA_COHORT_ACCESS' not in app.config
|
||||
|
||||
|
||||
def test_application_starts_with_retained_obsolete_configuration(monkeypatch):
|
||||
"""Retained synthetic settings cannot prevent the health endpoint starting."""
|
||||
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
|
||||
monkeypatch.delenv('CAMA_COHORT_SECRET', raising=False)
|
||||
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'invalid')
|
||||
from webapi import create_app
|
||||
|
||||
assert create_app().test_client().get('/health').get_json() == {'status': 'ok'}
|
||||
@@ -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) == {}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""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), and a note of 2025-08-04 with stage IIA.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from conftest import base_de
|
||||
from sqlalchemy import text
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.fhir.measures import _label
|
||||
from webapi.metrics import Question
|
||||
|
||||
BIRADS = "cama/CAMA_BIRADS_CANCER_INVASOR"
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@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, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
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),
|
||||
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, 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(f"select tipo from ({node['compiled_code']}) e")).scalars())
|
||||
|
||||
|
||||
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_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_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():
|
||||
"""Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from
|
||||
`resto_etiqueta`. Fails if `_label` reads labels only from a map."""
|
||||
spec = {"valores": [{"valor": "II", "etiqueta": "Estadio II", "si": []}], "resto": "SIN_DATO",
|
||||
"resto_etiqueta": "Sin dato"}
|
||||
assert (_label(spec, "II"), _label(spec, "SIN_DATO"), _label(spec, "IV")) == ("Estadio II", "Sin dato", None)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""`commit_discovered_fields`: writes captions no known field claims
|
||||
straight into `procedimiento`/`observacion`, tagged apart from every
|
||||
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
|
||||
patient's discovered fields stop landing there, or if an unmatched one
|
||||
stops growing the catalog instead of being silently dropped.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||
return ExtractedRecord(
|
||||
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_catalog(tmp_path, monkeypatch):
|
||||
"""`add_resultado`/`sync` write real rows and a real file:
|
||||
kept off the checked-in `cacu.toml` and off any other domain's data."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text(
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def known_patient(wire_domain):
|
||||
wire_domain("cacu")
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
return "DOC-FB-1"
|
||||
|
||||
|
||||
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
|
||||
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
|
||||
assert procedimiento.fuente_id == known_patient
|
||||
|
||||
|
||||
def test_an_unmatched_field_is_counted_and_the_catalog_left_untouched(cacu_catalog, known_patient):
|
||||
"""A caption the catalog doesn't know is counted, not written, and the
|
||||
catalog file isn't edited: it's versioned with the code. Fails if the
|
||||
import path mints catalog entries again."""
|
||||
before = cacu_catalog.read_text(encoding="utf-8")
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_minted, result.fields_unmatched) == (0, 0, 1)
|
||||
assert cacu_catalog.read_text(encoding="utf-8") == before
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
assert sesion.exec(select(carga_repository.observacion)).all() == []
|
||||
|
||||
|
||||
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.records_without_patient) == (0, 1)
|
||||
|
||||
|
||||
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
|
||||
assert result.records_written == 0
|
||||
|
||||
|
||||
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
|
||||
"""A static label printed on several pages of the same document (a date,
|
||||
a signature line) discovers as one `DiscoveredField` per occurrence,
|
||||
on purpose (`discover_captions`'s docstring). Fails if this stops
|
||||
folding repeats before writing: `observacion` has one row per
|
||||
`(procedimiento, resultado_id)`, so a second occurrence of the same
|
||||
resultado_id raises `IntegrityError` and the whole record's fields —
|
||||
including the ones that weren't duplicated — are lost."""
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
|
||||
proyecto="cacu",
|
||||
estudio_id="citologia",
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
@@ -0,0 +1,90 @@
|
||||
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
|
||||
catalog field for an OCR caption that's clearly the same thing worded
|
||||
differently, or if an unmatched caption stops being added to the catalog
|
||||
and silently drops its value instead.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _field(caption: str, value: str) -> DiscoveredField:
|
||||
return DiscoveredField(caption, value, EVIDENCE)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo() -> Catalogo:
|
||||
tablas = tablas_de("cacu")
|
||||
return Catalogo(
|
||||
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
|
||||
resultados=[
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
|
||||
etiqueta="Calidad de la muestra", tipo_valor="codigo",
|
||||
),
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
|
||||
etiqueta="Células glandulares", tipo_valor="texto",
|
||||
),
|
||||
],
|
||||
valores=[
|
||||
tablas.CatValor(
|
||||
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
|
||||
etiqueta="Satisfactoria", orden=1, estado="vigente",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_toml(tmp_path, monkeypatch):
|
||||
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
|
||||
assert matched.observacion["valor_id"] == "SATISFACTORIO"
|
||||
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
|
||||
|
||||
|
||||
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.is_new and matched.resultado_id.startswith("citologia.")
|
||||
assert matched.observacion["valor_texto"] == "Formol"
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
|
||||
|
||||
|
||||
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
|
||||
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
|
||||
|
||||
|
||||
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
|
||||
fecha, numero, texto = match_or_mint(
|
||||
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
|
||||
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
|
||||
)
|
||||
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
|
||||
assert numero.observacion["valor_numerico"] == 12.5
|
||||
assert texto.observacion["valor_texto"] == "ninguna"
|
||||
@@ -0,0 +1,77 @@
|
||||
"""`add_resultado`: adds a new field to a project's catalog TOML file on
|
||||
disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a
|
||||
field no catalog entry matches closely enough. Each test pins down one
|
||||
rule of that append; fails if any of them regresses into losing data or
|
||||
duplicating an entry that's already there.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
|
||||
def escribir(contenido: str) -> None:
|
||||
(tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8")
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file):
|
||||
catalogo_file('[citologia]\netiqueta = "Citología"\n')
|
||||
|
||||
resultado_id = catalogos.add_resultado(
|
||||
"prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto"
|
||||
)
|
||||
|
||||
assert resultado_id == "citologia.nuevo_campo"
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives
|
||||
assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"}
|
||||
|
||||
|
||||
def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file):
|
||||
catalogo_file("")
|
||||
|
||||
catalogos.add_resultado(
|
||||
"prueba",
|
||||
estudio_id="documento_externo",
|
||||
nombre="campo",
|
||||
etiqueta="Campo",
|
||||
tipo_valor="fecha",
|
||||
estudio_etiqueta="Documento externo",
|
||||
)
|
||||
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["documento_externo"]["etiqueta"] == "Documento externo"
|
||||
assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha"
|
||||
|
||||
|
||||
def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file):
|
||||
"""Fails if re-discovering the same field on a later row duplicates it
|
||||
or rewrites what a human already edited in the file."""
|
||||
original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n'
|
||||
catalogo_file(original)
|
||||
|
||||
catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero")
|
||||
|
||||
assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_an_unknown_tipo_valor_is_rejected(catalogo_file):
|
||||
catalogo_file("")
|
||||
with pytest.raises(catalogos.CatalogoInvalido):
|
||||
catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe")
|
||||
|
||||
|
||||
def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file):
|
||||
"""Fails if a caption or label read off a document (arbitrary text)
|
||||
produces TOML the next `catalogo_desde_toml` can't parse."""
|
||||
catalogo_file("")
|
||||
catalogos.add_resultado(
|
||||
"prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto"
|
||||
)
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"'
|
||||
@@ -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")]
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The dbt target and environment derived from the deployment's database URLs (`webapi.dbt_manifest`).
|
||||
|
||||
No dbt runs here: only the mapping the entrypoint relies on to compile the manifest against the right engine.
|
||||
No fixtures."""
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.dbt_manifest import dbt_executable, environment, target_of
|
||||
|
||||
URLS_MSSQL = {
|
||||
"cacu": "mssql+pymssql://usuario:clave@servidor:1433/isss_cacu",
|
||||
"cama": "mssql+pymssql://usuario:clave@servidor:1433/isss_cama",
|
||||
"tea": "mssql+pymssql://usuario:clave@servidor:1433/isss_tea",
|
||||
}
|
||||
|
||||
|
||||
def test_sqlite_urls_keep_the_image_manifest():
|
||||
"""SQLite URLs give the `sqlite` target, which the entrypoint treats as "keep the image's manifest". Fails if
|
||||
`target_of` stops recognising SQLite or maps it elsewhere."""
|
||||
urls = {d: f"sqlite:////data/{d}.db" for d in ("cacu", "cama", "tea")}
|
||||
assert target_of(urls) == "sqlite"
|
||||
assert environment(urls, "sqlite")["TEA_DB_PATH"] == "/data/tea.db"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheme, target", [("mssql+pymssql", "sqlserver"), ("postgresql+psycopg2", "postgres"),
|
||||
("mysql+pymysql", "mysql"), ("mariadb+pymysql", "mysql")])
|
||||
def test_each_engine_maps_to_its_dbt_target(scheme, target):
|
||||
"""Every engine the platform runs on has a dbt target. Fails if a backend name is dropped from `TARGETS`."""
|
||||
urls = {d: f"{scheme}://u:p@h:1/{d}" for d in ("cacu", "cama", "tea")}
|
||||
assert target_of(urls) == target
|
||||
|
||||
|
||||
def test_mixed_engines_are_refused():
|
||||
"""One manifest serves the three domains, so their databases must share an engine. Fails if `target_of`
|
||||
silently picks one of several engines."""
|
||||
urls = {**URLS_MSSQL, "tea": "sqlite:////data/tea.db"}
|
||||
with pytest.raises(ValueError, match="one engine"):
|
||||
target_of(urls)
|
||||
|
||||
|
||||
def test_environment_feeds_profiles_yml():
|
||||
"""The server, port, credentials and each domain's database name reach dbt through the variables
|
||||
`Transformation/profiles.yml` reads. Fails if a variable name changes on either side."""
|
||||
env = environment(URLS_MSSQL, "sqlserver")
|
||||
assert env == {"CACU_DBT_DATABASE": "isss_cacu", "CAMA_DBT_DATABASE": "isss_cama", "TEA_DBT_DATABASE": "isss_tea",
|
||||
"DBT_HOST": "servidor", "DBT_PORT": "1433", "DBT_USER": "usuario", "DBT_PASSWORD": "clave"}
|
||||
|
||||
|
||||
def test_mysql_has_its_own_environment(tmp_path):
|
||||
"""dbt-mysql pins an older dbt-core, so the image keeps it in `.venv-mysql`. Fails if the executable lookup
|
||||
stops distinguishing MySQL."""
|
||||
assert dbt_executable(tmp_path, "mysql") == tmp_path / ".venv-mysql" / "bin" / "dbt"
|
||||
assert dbt_executable(tmp_path, "sqlserver") == tmp_path / ".venv" / "bin" / "dbt"
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Options that let one document source cope with however its rows are
|
||||
stored: columns carried through as field values, a column grouping rows
|
||||
into records, filters that pick which documents feed a target, documents
|
||||
kept as hex or base64 text, unreadable rows, and queries that a derived
|
||||
table can't hold as written.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database) and
|
||||
`documents_table`, a SQLite table built per test whose rows carry two
|
||||
reports of one order, a third report of the same patient under another
|
||||
order, and an unrelated kind of report.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.document import document_bytes
|
||||
from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
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 documents_table(tmp_path):
|
||||
"""Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is
|
||||
a report of order 11 of the same patient, and row 4 is a report of a
|
||||
kind the CaCu cytology target doesn't take. No body prints the
|
||||
patient id the structured columns hold."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
rows = [
|
||||
(1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"),
|
||||
(2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"),
|
||||
(3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"),
|
||||
(4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"),
|
||||
]
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)"))
|
||||
for row in rows:
|
||||
conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row)))
|
||||
return url
|
||||
|
||||
|
||||
def _payload(url: str, **sql) -> dict:
|
||||
base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}
|
||||
return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"}
|
||||
|
||||
|
||||
def _extract(client, payload: dict) -> dict:
|
||||
response = client.post("/imports/sources/document/extract", json=payload)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table):
|
||||
"""Rows sharing `group_column` become one record; the same patient's
|
||||
other order stays its own record. Fails if `group_column` stops
|
||||
reaching `record_keys`."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(
|
||||
documents_table,
|
||||
fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"},
|
||||
group_column="order_ref",
|
||||
)
|
||||
| {"exclude_pattern": "otra especialidad"},
|
||||
)
|
||||
by_key = {record["key"]: record for record in body["records"]}
|
||||
assert set(by_key) == {"10", "11"}
|
||||
assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1"
|
||||
|
||||
|
||||
def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table):
|
||||
"""`include_pattern` keeps only matching documents, matched without
|
||||
regard to case or accents, and the rest are listed as skipped. Fails
|
||||
if the filters stop applying or `skipped` stops reporting them."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"},
|
||||
)
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["4"]
|
||||
|
||||
|
||||
def test_a_filter_that_matches_nothing_is_an_error(client, documents_table):
|
||||
"""Filtering out every document is reported instead of returning an
|
||||
empty import. Fails if `_extract` stops refusing an empty selection."""
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_an_invalid_filter_is_a_bad_request(client, documents_table):
|
||||
"""A filter that isn't a valid regular expression is rejected with a
|
||||
message naming it. Fails if `_compile_filter` lets `re.error` through."""
|
||||
response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("})
|
||||
assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_documents_stored_as_hex_or_base64_text_are_decoded():
|
||||
"""A PDF kept in a text column as hex (with or without `0x`) or base64
|
||||
reaches the readers as the PDF itself, and ordinary text stays text.
|
||||
Fails if `document_bytes` stops recognizing either encoding."""
|
||||
pdf = text_pdf([["Expediente: X-1"]])
|
||||
assert document_bytes("0x" + pdf.hex()) == pdf
|
||||
assert document_bytes(pdf.hex().upper()) == pdf
|
||||
assert document_bytes(base64.b64encode(pdf).decode()) == pdf
|
||||
assert document_bytes("Expediente: X-1") == b"Expediente: X-1"
|
||||
|
||||
|
||||
def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path):
|
||||
"""One corrupt document among readable ones is listed as skipped while
|
||||
the rest are extracted. Fails if a single unreadable row aborts the
|
||||
whole source again."""
|
||||
url = f"sqlite:///{tmp_path / 'mixed.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"})
|
||||
conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])})
|
||||
body = _extract(client, _payload(url))
|
||||
assert [record["key"] for record in body["records"]] == ["X-2"]
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["1"]
|
||||
|
||||
|
||||
def test_repeated_key_column_values_still_name_rows_apart(tmp_path):
|
||||
"""Two rows with the same `key_column` value get distinct names, so
|
||||
neither one's fields or pages overwrite the other's. Fails if
|
||||
`_files_from_sql` stops suffixing repeated names."""
|
||||
from webapi.imports.connectors.document import _files_from_sql
|
||||
|
||||
url = f"sqlite:///{tmp_path / 'r.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')"))
|
||||
documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"})
|
||||
assert [name for name, _ in documents.files] == ["7", "7#2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query,kept",
|
||||
[
|
||||
("SELECT a FROM t ORDER BY a", "SELECT a FROM t"),
|
||||
("SELECT TOP 5 a FROM t ORDER BY a", None),
|
||||
("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None),
|
||||
("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None),
|
||||
("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"),
|
||||
],
|
||||
)
|
||||
def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept):
|
||||
"""SQL Server refuses `ORDER BY` inside a derived table unless TOP or
|
||||
OFFSET goes with it, so one that only sorts is dropped; one that picks
|
||||
rows, or sits inside a subquery or a string, stays. Fails if
|
||||
`_without_trailing_order_by` drops an `ORDER BY` that chooses rows or
|
||||
keeps one that would make the wrapped query invalid."""
|
||||
assert _without_trailing_order_by(query, "mssql") == (kept or query)
|
||||
|
||||
|
||||
def test_a_named_instance_or_embedded_port_reaches_the_driver():
|
||||
"""`host\\instance` leaves the port unset for the server to resolve,
|
||||
and `host,port` or `host:port` fill it in. Fails if `server_url` stops
|
||||
parsing addresses or goes back to forcing the default port on a named
|
||||
instance."""
|
||||
named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"})
|
||||
assert (named.host, named.port) == ("db.example\\INST", None)
|
||||
comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"})
|
||||
assert (comma.host, comma.port) == ("db.example", 1500)
|
||||
colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"})
|
||||
assert (colon.host, colon.port) == ("db.example", 6543)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""`DocumentConnector` reading its documents from a SQL source instead of
|
||||
uploaded files: one document per row, read from a column that may hold a
|
||||
PDF (a binary column) or already be plain text, both without a filesystem
|
||||
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||
plain-text column stops reaching the same field extraction a PDF does.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
REPORT = text_pdf(
|
||||
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table with one row per study, its
|
||||
report in a binary column, plus a plain-text variant of the same
|
||||
report in another row, both alongside the row's own key column."""
|
||||
db_path = tmp_path / "estudios.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{"id": "ROW-1", "reporte": REPORT},
|
||||
)
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{
|
||||
"id": "ROW-2",
|
||||
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
||||
},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[first, second] = body["records"]
|
||||
assert first["key"] == "SQL-0001"
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||
"""Fails if a source whose bundle is a plain string (not binary at
|
||||
all) stops producing fields, since a source's column may not always
|
||||
be a PDF (`extraction.readers.TextReader`)."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[_, second] = body["records"]
|
||||
assert second["key"] == "SQL-0002"
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
||||
"label": "estudios",
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
|
||||
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
||||
)
|
||||
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
payload = _sql_payload(sqlite_studies_table)
|
||||
del payload["column"]
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||
fijador`) but the project's catalog does still reaches the silver
|
||||
layer through the open-catalog path, alongside the recognized fields
|
||||
`commit_sources` writes as before, when the source asks for it with
|
||||
`catalog_fallback`. Fails if `/imports/commit` stops wiring that second
|
||||
path in, or runs it for a source that didn't ask.
|
||||
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||
the module's other tests sharing this `client`'s database."""
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import create_engine, text as sa_text
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
catalog = (
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.tipo_de_fijador]\netiqueta = "Tipo de fijador"\ntipo_valor = "texto"\n'
|
||||
)
|
||||
(tmp_path / "cacu.toml").write_text(catalog, encoding="utf-8")
|
||||
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||
|
||||
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
||||
with create_engine(db_url).begin() as conn:
|
||||
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
||||
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
||||
"label": "estudios_extra",
|
||||
}
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1, body
|
||||
assert not [r for r in body.get("catalog_fallback", []) if r["label"] == "estudios_extra"]
|
||||
|
||||
body = client.post("/imports/commit", json={"sources": [{**source, "catalog_fallback": True}], "on_conflict": "upsert"}).get_json()
|
||||
[fallback] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert (fallback["records_written"], fallback["fields_matched"], fallback["fields_minted"]) == (1, 1, 0)
|
||||
assert (tmp_path / "cacu.toml").read_text(encoding="utf-8") == catalog
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[written] = list(
|
||||
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
||||
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
||||
)))
|
||||
)
|
||||
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
|
||||
@@ -0,0 +1,118 @@
|
||||
"""What this module covers: the cycle's `analyze_eeg` step (TEA's EEG analysis before the silver load) and how the
|
||||
cycle gets its analysis (`webapi.orchestration.eeg`).
|
||||
|
||||
Fixtures: `tea_base`, a migrated TEA database (`base_de`) holding one patient (`pac_id` 1, born 2024-01-01) and one
|
||||
EEG `e-1` with an EDF and no analysis; `fake_analysis`, an analysis that writes sleep and 21 channels on `e-1`, as
|
||||
the real one would, and notes whether a silver load existed when it ran.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from models.eeg_analysis import Summary
|
||||
from webapi.orchestration import cycle, run, steps_of
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.eeg import CLUSTER_ENV, live_eeg_analysis
|
||||
|
||||
|
||||
def _rows(sesion):
|
||||
from core.tea.models import Eeg, Pacientes
|
||||
|
||||
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2024, 1, 1)))
|
||||
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_id_registro_laboratorio="LAB-1", eeg_fecha_estudio=date(2025, 6, 1),
|
||||
eeg_estudio=b"edf"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tea_base(tmp_path):
|
||||
"""Patient 1 and EEG `e-1` (an EDF, nothing analysed) in a migrated TEA database."""
|
||||
from conftest import base_de
|
||||
|
||||
base = base_de("tea", tmp_path, datos=_rows)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_analysis(tea_base):
|
||||
"""Writes `eeg_con_sueno` 1 and `eeg_canales` 21 on `e-1`; `calls` records the loads that existed at each call."""
|
||||
from core.tea.indicadores.models import Carga
|
||||
from core.tea.models import Eeg
|
||||
|
||||
calls = []
|
||||
|
||||
def analysis():
|
||||
with Session(tea_base.motor) as sesion:
|
||||
calls.append(len(sesion.exec(select(Carga)).all()))
|
||||
eeg = sesion.get(Eeg, "e-1")
|
||||
eeg.eeg_con_sueno, eeg.eeg_canales = 1, 21
|
||||
sesion.add(eeg)
|
||||
sesion.commit()
|
||||
return Summary(pending=1, valid=1, not_valid=0, failed=0)
|
||||
|
||||
analysis.calls = calls
|
||||
return analysis
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_the_eeg_analysis_runs_before_the_silver_load(proyecto):
|
||||
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema 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 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", "score_ados2"}
|
||||
order = steps_of(proyecto)
|
||||
assert order.index("analyze_eeg") < order.index("load")
|
||||
|
||||
|
||||
def test_without_an_analysis_the_step_does_nothing():
|
||||
"""Pins down: a context without `eeg_analysis` (CaCu, CaMa, the tests' cycles) makes the step a no-op.
|
||||
|
||||
Fails if the step starts running an analysis nobody configured.
|
||||
"""
|
||||
pasos = run(Context("cacu", 2025, 2025), only=["analyze_eeg"])
|
||||
assert [(p.name, p.summary) for p in pasos] == [("analyze_eeg", {})]
|
||||
|
||||
|
||||
def test_what_the_analysis_writes_is_loaded_by_the_same_cycle(tea_base, fake_analysis):
|
||||
"""Pins down: the cycle runs the analysis once, before any silver load, and `load` then carries what it wrote
|
||||
into the EEG's silver observations.
|
||||
|
||||
Fails if the analysis runs after `load` or more than once, or its summary stops being the step's.
|
||||
"""
|
||||
from core.tea.indicadores.models import Observacion, Procedimiento
|
||||
|
||||
pasos = tea_base.run("analyze_eeg", "catalogs", "load", eeg_analysis=fake_analysis)
|
||||
assert pasos["analyze_eeg"] == {"pending": 1, "valid": 1, "not_valid": 0, "failed": 0}
|
||||
assert fake_analysis.calls == [0]
|
||||
with Session(tea_base.motor) as sesion:
|
||||
toma = sesion.exec(select(Procedimiento).where(Procedimiento.estudio_id == "eeg",
|
||||
Procedimiento.clase == "toma")).one()
|
||||
valores = {o.resultado_id: o.valor_numerico for o in sesion.exec(
|
||||
select(Observacion).where(Observacion.procedimiento_id == toma.procedimiento_id))}
|
||||
assert valores["eeg.canales"] == 21
|
||||
|
||||
|
||||
def test_only_tea_has_an_analysis_and_it_can_be_turned_off(monkeypatch):
|
||||
"""Pins down: TEA's cycle gets the analysis, with the cluster `EEG_ANALYSIS_CLUSTER` names; the other domains
|
||||
get none, `off` leaves it out, and an unknown value is refused.
|
||||
|
||||
Fails if another domain starts analysing EEGs, `off` stops leaving the analysis out, or a mistyped cluster is
|
||||
silently taken as the default.
|
||||
"""
|
||||
monkeypatch.delenv(CLUSTER_ENV, raising=False)
|
||||
assert live_eeg_analysis("tea").keywords == {"cluster": "auto"}
|
||||
assert live_eeg_analysis("cacu") is None
|
||||
monkeypatch.setenv(CLUSTER_ENV, "sync")
|
||||
assert live_eeg_analysis("tea").keywords == {"cluster": "sync"}
|
||||
monkeypatch.setenv(CLUSTER_ENV, "off")
|
||||
assert live_eeg_analysis("tea") is None
|
||||
monkeypatch.setenv(CLUSTER_ENV, "everywhere")
|
||||
with pytest.raises(ValueError, match=CLUSTER_ENV):
|
||||
live_eeg_analysis("tea")
|
||||
@@ -0,0 +1,178 @@
|
||||
"""What this module covers: catalog results read from a staging row's text (`silver.extracted`). The catalog's
|
||||
`etiquetas_fuente` and `alias` checked when it's read; a report's text, a PDF's text layer and a note turned into
|
||||
codes, numbers and their sources; a spelling the catalog doesn't know kept as text and turned into a code by a
|
||||
catalog change alone; and CaMa's load putting them in silver and dbt's timeline.
|
||||
|
||||
Fixtures: `catalogo_en`, a copy of CaMa's catalog in `tmp_path` that the catalog functions read instead of Core's;
|
||||
`cargada`, the CaMa fixture database (`staging/cama.py`: H-003's texts and pathology PDF, H-101's unknown density)
|
||||
loaded, with dbt's views when `DBT_MANIFEST` is set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from staging.cama import INFORME_DE_PATOLOGIA, pdf_de
|
||||
from webapi.orchestration.reference import catalogs
|
||||
from webapi.orchestration.reference.catalogs import CatalogoInvalido, catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.silver import cama
|
||||
from webapi.orchestration.silver.extracted import DesdeTexto
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
DENSIDAD = """
|
||||
[mastografia]
|
||||
etiqueta = "Mastografía"
|
||||
|
||||
[mastografia.resultados.densidad]
|
||||
etiqueta = "Densidad"
|
||||
tipo_valor = "codigo"
|
||||
etiquetas_fuente = ["Densidad mamaria"]
|
||||
valores = [
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C"] },
|
||||
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D"] },
|
||||
]
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_en(tmp_path, monkeypatch):
|
||||
"""Writes a catalog for `cama` in `tmp_path` and points the catalog functions at it. Returns a writer."""
|
||||
ruta = tmp_path / "cama.toml"
|
||||
monkeypatch.setattr(catalogs, "ruta_de_catalogo", lambda proyecto: ruta)
|
||||
|
||||
def escribir(contenido: str):
|
||||
ruta.write_text(contenido, encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proyecto():
|
||||
return "cama"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cargada(base):
|
||||
pasos = ("catalogs", "load", "event_models") if os.environ.get("DBT_MANIFEST") else ("catalogs", "load")
|
||||
base.run(*pasos)
|
||||
return base
|
||||
|
||||
|
||||
def observaciones(base, resultado_prefijo: str) -> dict[str, tuple]:
|
||||
"""`resultado_id` -> (valor_id, valor_numerico, valor_fuente) of the observations whose result starts so."""
|
||||
with base.motor.connect() as con:
|
||||
filas = con.execute(text(
|
||||
"SELECT resultado_id, valor_id, valor_numerico, valor_fuente FROM observacion_clinica "
|
||||
"WHERE resultado_id LIKE :p AND (valor_id IS NOT NULL OR valor_numerico IS NOT NULL OR valor_fuente IS NOT NULL)"
|
||||
), {"p": resultado_prefijo + "%"}).all()
|
||||
return {f.resultado_id: (f.valor_id, f.valor_numerico, f.valor_fuente) for f in filas}
|
||||
|
||||
|
||||
# --- the catalog ---
|
||||
|
||||
def test_the_catalog_lists_cama_s_extractable_results_as_provisional():
|
||||
"""Pins down: every CaMa result with captions is extractable and marked provisional, and the catalog still
|
||||
loads with them. Fails if `resultados_extraibles` drops a result or the new keys break `catalogo_desde_toml`."""
|
||||
extraibles = catalogs.resultados_extraibles("cama")
|
||||
assert set(extraibles) >= {"mastografia.densidad", "biopsia.her2", "nota_medica.estadio_clinico"}
|
||||
assert all(e.provisional for e in extraibles.values())
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo("cama"), tablas=tablas_de("cama"))
|
||||
assert {r.resultado_id for r in catalogo.resultados} >= set(extraibles)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cambio, error", [
|
||||
(('alias = ["Tipo D"]', 'alias = ["Tipo C"]'), "se escribe igual"),
|
||||
(('etiquetas_fuente = ["Densidad mamaria"]', 'etiquetas_fuente = []'), "lista de textos"),
|
||||
(('etiquetas_fuente = ["Densidad mamaria"]\n', ''), "solo sirven con etiquetas_fuente"),
|
||||
])
|
||||
def test_an_ambiguous_or_incomplete_mapping_is_rejected(catalogo_en, cambio, error):
|
||||
"""Pins down: one spelling on two values, empty captions, or aliases without captions stop the catalog from
|
||||
loading. Fails if a check is dropped and an alias could turn into either of two codes."""
|
||||
ruta = catalogo_en(DENSIDAD.replace(*cambio))
|
||||
with pytest.raises(CatalogoInvalido, match=error):
|
||||
catalogo_desde_toml(ruta, tablas=tablas_de("cama"))
|
||||
|
||||
|
||||
# --- reading text ---
|
||||
|
||||
def test_a_report_s_text_gives_codes_with_their_spelling_and_numbers():
|
||||
"""Pins down: a caption followed by a known spelling gives its code and that spelling as source; a number
|
||||
after its caption gives the number. Fails if the catalog's aliases stop reaching Extraction's field specs."""
|
||||
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(
|
||||
mast_interpretacion="Densidad mamaria: heterogéneamente densas (C).\nTamaño de la lesión: 14 mm."))
|
||||
assert leido == {"mastografia.densidad": ("C", "heterogéneamente densas"), "mastografia.tamano_lesion_mm": (14.0, None)}
|
||||
|
||||
|
||||
def test_an_unknown_spelling_is_kept_as_its_source_without_a_code():
|
||||
"""Pins down: what follows a caption that matches no alias is kept as source text, with no code. Fails if it's
|
||||
dropped (it couldn't be found and mapped later) or forced into a code."""
|
||||
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E"))
|
||||
assert leido["mastografia.densidad"] == (None, "tipo E")
|
||||
|
||||
|
||||
def test_a_stage_is_found_in_a_note_without_a_caption():
|
||||
"""Pins down: a result marked `buscar_en_texto` is found as a mention in narrative text. Fails if the flag
|
||||
stops reaching `scan_free_text`."""
|
||||
leido = cama.DE_LA_NOTA.leer(SimpleNamespace(
|
||||
nm_diagnostico_texto="Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)", nm_pronostico=None))
|
||||
assert leido["nota_medica.estadio_clinico"] == ("EIIA", "estadio clínico IIA")
|
||||
|
||||
|
||||
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 (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": "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.tamano_tumor_mm": None,
|
||||
}
|
||||
|
||||
|
||||
def test_no_text_gives_no_values():
|
||||
"""Pins down: a row without text (or a PDF that can't be read) gives every result empty. Fails if an empty
|
||||
text or broken bytes raise during a load."""
|
||||
assert set(cama.DE_LA_NOTA.leer(SimpleNamespace(nm_diagnostico_texto=None, nm_pronostico=None)).values()) == {(None, None)}
|
||||
assert set(cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=b"not a pdf")).values()) == {(None, None)}
|
||||
|
||||
|
||||
def test_adding_an_alias_maps_the_same_text_on_the_next_read(catalogo_en):
|
||||
"""Pins down: an unknown spelling becomes a code by adding it to the catalog, with nothing else changed. Fails
|
||||
if the mapping is cached across catalog reads or lives anywhere but the catalog."""
|
||||
fila = SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E")
|
||||
catalogo_en(DENSIDAD)
|
||||
antes = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
|
||||
catalogo_en(DENSIDAD.replace('alias = ["Tipo D"]', 'alias = ["Tipo D", "Tipo E"]'))
|
||||
despues = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
|
||||
assert antes["mastografia.densidad"] == (None, "tipo E")
|
||||
assert despues["mastografia.densidad"] == ("D", "tipo E")
|
||||
|
||||
|
||||
# --- the load ---
|
||||
|
||||
def test_the_load_puts_the_extracted_results_in_silver(cargada):
|
||||
"""Pins down: CaMa's load writes the results read from the interpretation, the pathology PDF and the note, and
|
||||
an unknown spelling as an out-of-catalog source. Fails if `cama.DESDE_STAGING` stops wiring a `DesdeTexto`."""
|
||||
with cargada.motor.connect() as con:
|
||||
densidades = sorted(con.execute(text(
|
||||
"SELECT coalesce(valor_id, '?') || ':' || valor_fuente FROM observacion_clinica "
|
||||
"WHERE resultado_id = 'mastografia.densidad' AND valor_fuente IS NOT NULL")).scalars())
|
||||
assert densidades == ["?:tipo E", "C:heterogéneamente densas"]
|
||||
assert observaciones(cargada, "biopsia.her2") == {"biopsia.her2": ("H3", None, "3+")}
|
||||
assert observaciones(cargada, "biopsia.ki67_pct") == {"biopsia.ki67_pct": (None, 25.0, None)}
|
||||
assert observaciones(cargada, "nota_medica.estadio_clinico") == {
|
||||
"nota_medica.estadio_clinico": ("EIIA", None, "estadio clínico IIA")}
|
||||
|
||||
|
||||
def test_the_timeline_carries_the_extracted_results(cargada):
|
||||
"""Pins down: the timeline declares the new results, so H-003's stage, receptors and density are rows of it.
|
||||
Fails if a source line is missing from `cama_linea_de_tiempo.yml`."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
filas = cargada.ctx.repos.silver.timeline.read()
|
||||
valores = {(f["tipo"], f["valor_codigo"] or f["valor_numerico"]) for f in filas}
|
||||
assert {("estadio_clinico", "EIIA"), ("her2", "H3"), ("receptor_estrogeno_pct", 90.0),
|
||||
("densidad_mamaria", "C"), ("densidad_mamaria", "tipo E")} <= valores
|
||||
@@ -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]
|
||||
@@ -0,0 +1,161 @@
|
||||
"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cacu`): a patient's
|
||||
current risk as a FHIR R4 `RiskAssessment` in a `searchset` Bundle, as TEA's patient resources are served: the
|
||||
resource's shape (status, subject, method, one prediction per horizon from the risk's 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 CaCu demonstration
|
||||
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a surveillance build with two of its patients, one
|
||||
with a confirmed batch whose risks 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("cacu", 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 and 3 years, the
|
||||
3-year one with an interval. Returns (scored patient, member without risks)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
scored, unscored = [p.pac_id for p in cacu.persona_repository.list(limit=2)]
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk", 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="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (scored, unscored)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_mas", [(scored, MODEL_INDEX, 3.0, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.0, 0.08, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.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"/cacu/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"/cacu/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"] == "cacu-cin2_pim" and risk["method"]["coding"][0]["version"] == "3"
|
||||
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["cin2_mas", "cin2_mas"]
|
||||
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
|
||||
(0.08, {"start": "2026-06-01", "end": "2026-06-01"}), (0.21, {"start": "2026-06-01", "end": "2029-06-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"/cacu/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"/cacu/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: CaCu'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("/cacu/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"]
|
||||
|
||||
|
||||
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
|
||||
@@ -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"]
|
||||
@@ -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-"))
|
||||
@@ -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"] == 7
|
||||
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()
|
||||
|
||||
@@ -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"}
|
||||
@@ -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)
|
||||
+100
-6
@@ -9,6 +9,7 @@ Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes ex
|
||||
shows the alterations (`TEA_ALTERACIONES_VALIDADAS`).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
@@ -168,8 +169,9 @@ def test_the_follow_up_filters(client, query, n):
|
||||
def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
|
||||
"""Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT,
|
||||
ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality
|
||||
observations; no metric observation while the alterations are hidden. Fails if an included resource drops out or
|
||||
the alterations leak."""
|
||||
observations, one per check of its analysis (clean windows, usable scalp, triage level, line noise) as the
|
||||
analysis's own report writes them; no metric observation while the alterations are hidden. Fails if an included
|
||||
resource drops out, a check stops reaching the report or changes shape, or the alterations leak."""
|
||||
body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*")
|
||||
included = resources(body, mode="include")
|
||||
kinds = {r["resourceType"] for r in included}
|
||||
@@ -177,11 +179,49 @@ def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
|
||||
assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient")
|
||||
reports = [r for r in included if r["resourceType"] == "DiagnosticReport"]
|
||||
assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"}
|
||||
assert all(len(r["result"]) == 5 for r in reports)
|
||||
assert all(len(r["result"]) == 4 for r in reports)
|
||||
assert all(r["conclusionCode"][1]["coding"][0] == {"system": "urn:tea:validation", "code": "valid"} for r in reports)
|
||||
quality = [r for r in included if r["resourceType"] == "Observation" and r["id"].startswith("calidad-")]
|
||||
assert {r["code"]["coding"][0]["system"] for r in quality} == {"urn:tea:validation"}
|
||||
clean = next(r for r in quality if r["code"]["coding"][0]["code"] == "clean-windows")
|
||||
assert (clean["valueQuantity"]["value"], clean["referenceRange"][0]["low"]["value"]) == (95.0, 60.0)
|
||||
assert clean["interpretation"][0]["coding"][0]["code"] == "N"
|
||||
assert clean["component"] == [{"code": {"text": "decisive"}, "valueBoolean": True}]
|
||||
triage = next(r for r in quality if r["code"]["coding"][0]["code"] == "triage-level")
|
||||
assert triage["valueString"] == "completo"
|
||||
ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"]
|
||||
assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2)
|
||||
|
||||
|
||||
def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client):
|
||||
"""Pins down, on a bad EEG's rows as dbt's views give them (too few clean windows, a dead channel at T3): the report
|
||||
says MALO and the analysis's not-valid with the triage level; the clean windows are abnormal and decisive; the
|
||||
dead channel is an abnormal observation with its electrode as a component; every resource conforms to FHIR.
|
||||
Fails if a failed check or a bad channel stops reaching FHIR, or loses its electrode or decisive flag."""
|
||||
from webapi.fhir import tea
|
||||
|
||||
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial",
|
||||
"duracion_min": 25.0, "edad_meses": None, "canales": 19}
|
||||
checks = [
|
||||
{"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None,
|
||||
"bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"},
|
||||
{"procedimiento_id": 9, "criterio": "dead_channel", "electrodo": "T3", "valor": None,
|
||||
"valor_texto": "dead channel", "bajo": None, "alto": None, "anormal": 1, "decisivo": 0,
|
||||
"etiqueta": "Canal muerto", "unidad": None},
|
||||
]
|
||||
resources = tea.eeg_resources(eeg, "P-X", [], [], False, checks)
|
||||
report = next(r for r in resources if r["resourceType"] == "DiagnosticReport")
|
||||
assert [c["coding"][0]["code"] for c in report["conclusionCode"]] == ["MALO", "not-valid"]
|
||||
assert report["conclusion"].endswith("(nivel de triaje: parcial).")
|
||||
clean, dead = (r for r in resources if r["resourceType"] == "Observation")
|
||||
assert (clean["interpretation"][0]["coding"][0]["code"], clean["component"][-1]["valueBoolean"]) == ("A", True)
|
||||
assert dead["id"] == "calidad-dead-channel-T3-9" and dead["valueString"] == "dead channel"
|
||||
assert dead["component"] == [{"code": {"text": "electrode"}, "valueString": "T3"},
|
||||
{"code": {"text": "decisive"}, "valueBoolean": False}]
|
||||
for resource in resources:
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
|
||||
|
||||
def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch):
|
||||
"""Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's
|
||||
slow posterior rhythm). Fails if the filter leaks alterations before validation."""
|
||||
@@ -207,8 +247,9 @@ def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(c
|
||||
def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch):
|
||||
"""Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first
|
||||
good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated,
|
||||
the metrics against their reference and the electrode values. Fails if the summary takes another EEG or shows the
|
||||
alterations before validation."""
|
||||
the metrics against their age baseline (p5 as the low end of the reference, the median as a component) and each
|
||||
electrode's z-score; and its episode, with the age group. Fails if the summary takes another EEG, shows the
|
||||
alterations before validation, maps the electrodes' raw values or loses the age group."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
|
||||
(child_1,) = episodes
|
||||
path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea"
|
||||
@@ -225,8 +266,61 @@ def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, mon
|
||||
metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")]
|
||||
rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-"))
|
||||
assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5
|
||||
assert {c["code"]["coding"][0]["code"]: c["valueQuantity"]["value"] for c in rhythm["component"]} == {
|
||||
"z": -4.08, "mediana": 5.75}
|
||||
(episode,) = resources(shown, "EpisodeOfCare")
|
||||
assert episode["extension"][0]["valueCoding"]["code"] == "16_23"
|
||||
electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-"))
|
||||
assert [c["code"]["coding"][0]["code"] for c in electrodes["component"]] == ["O1", "O2", "Pz"]
|
||||
assert [(c["code"]["coding"][0]["code"], c["valueQuantity"]["value"]) for c in electrodes["component"]] == [
|
||||
("O1", -2.8), ("O2", -2.4), ("Pz", -1.1)]
|
||||
|
||||
|
||||
def test_a_metric_the_baseline_couldnt_score_keeps_its_value():
|
||||
"""Pins down: a metric with a value but no z (no baseline in production, or an age it doesn't cover) keeps its
|
||||
value and has no interpretation nor reference; one without a value is `not-performed`. Fails if an unscored metric
|
||||
loses its value (the summary couldn't tell it from one never measured) or gets an interpretation it doesn't have."""
|
||||
from webapi.fhir import tea
|
||||
|
||||
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-05-20"}
|
||||
row = {"procedimiento_id": 9, "ref_min": None, "ref_mediana": None, "ref_max": None, "grupo_edad_eeg": "16_23",
|
||||
"estado": "no_evaluable", "valor_z": None}
|
||||
unscored, unmeasured = tea.metric_observations(eeg, [{**row, "metrica": "ritmo_posterior", "valor": 6.8},
|
||||
{**row, "metrica": "husos_sueno_n3", "valor": None}],
|
||||
[], "P-X", False)[::-1]
|
||||
assert unscored["valueQuantity"]["value"] == 6.8
|
||||
assert not {"interpretation", "referenceRange", "dataAbsentReason", "component"} & set(unscored)
|
||||
assert unmeasured["dataAbsentReason"]["coding"][0]["code"] == "not-performed" and "valueQuantity" not in unmeasured
|
||||
|
||||
|
||||
def test_the_quality_checks_are_a_code_system_of_the_analysis(client):
|
||||
"""Pins down: `CodeSystem/tea-eeg-criterio` is the EEG analysis's code system (`urn:tea:validation`) with every
|
||||
check code and the catalog's label, and each metric has a text for every state, normal included.
|
||||
|
||||
Fails if a check code the quality observations use has no concept, or a metric loses its normal effect.
|
||||
"""
|
||||
from core.tea.enums import CriterioEeg
|
||||
|
||||
checks = get(client, "/tea/fhir/CodeSystem/tea-eeg-criterio")
|
||||
assert checks["url"] == "urn:tea:validation"
|
||||
assert {c["code"] for c in checks["concept"]} == {c.value for c in CriterioEeg}
|
||||
assert next(c for c in checks["concept"] if c["code"] == "clean-windows")["display"] == "Ventanas limpias"
|
||||
metrics = get(client, "/tea/fhir/CodeSystem/tea-eeg-metrica")
|
||||
assert all(any(p["code"] == "efecto-normal" for p in c["property"]) for c in metrics["concept"])
|
||||
|
||||
|
||||
def test_an_answer_that_doesnt_conform_to_fhir_never_leaves(client):
|
||||
"""Pins down: `fhir()` validates every answer against R4B; one that doesn't conform is a 500 `OperationOutcome`.
|
||||
|
||||
Fails if a malformed resource reaches a client, or the check stops running.
|
||||
"""
|
||||
from webapi import create_app
|
||||
from webapi.fhir.common import fhir
|
||||
|
||||
with create_app().test_request_context():
|
||||
bad = fhir({"resourceType": "Observation", "id": "x"}) # no status, no code
|
||||
good = fhir({"resourceType": "Observation", "id": "x", "status": "final", "code": {"text": "t"}})
|
||||
assert (bad.status_code, json.loads(bad.data)["resourceType"]) == (500, "OperationOutcome")
|
||||
assert (good.status_code, json.loads(good.data)["status"]) == (200, "final")
|
||||
|
||||
|
||||
def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client):
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
"""Endpoint tests for `/governance/*`."""
|
||||
"""Endpoint tests for `/governance/*`: model versions and their promotion, downloading what a version's run stored,
|
||||
notebooks run on a cohort build, and the OCR review queue.
|
||||
|
||||
Fixtures: `client`, the app over a CaCu and a governance database with one patient and a SQLite-backed MLflow in a
|
||||
temporary folder (module scope); `notebooks`, a cohort build's file under a `COHORTS_DIR`, the Jupyter renderer and
|
||||
notebooks run in the request instead of in the background. `_trained` registers a version the way training does: a run
|
||||
that records each routine and saves its model.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -81,42 +91,70 @@ def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def _upload(client, domain: str, scenario: str, version: str, kind: str = "BALANCE_CLASES", name: str = "smote.json", data: bytes = b"{}"):
|
||||
files = {"file": (__import__("io").BytesIO(data), name), "kind": kind}
|
||||
return client.post(f"/governance/model-versions/{domain}/{scenario}/{version}/artifacts", data=files, content_type="multipart/form-data")
|
||||
class Echo(mlflow.pyfunc.PythonModel):
|
||||
def predict(self, context, model_input, params=None):
|
||||
return model_input
|
||||
|
||||
|
||||
def _trained(tag: str, scenario: str, **reports) -> str:
|
||||
"""A PROD version as training leaves it: every routine recorded and the model saved."""
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import ROUTINE_KINDS, TrainingRun
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario=scenario, environment="PROD", cohorte_armado_id=_armado(tag))
|
||||
for kind in ROUTINE_KINDS:
|
||||
run.log_routine(kind, {"method": "prueba"})
|
||||
run.log_model(Echo())
|
||||
return registry.register_run(run.finish(metrics={"auc": 0.8}), **reports)
|
||||
|
||||
|
||||
REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html"}
|
||||
|
||||
|
||||
def test_model_version_lifecycle_over_http(client):
|
||||
first = _register(client, "v1", scenario="lifecycle")
|
||||
assert first["status"] == "candidata"
|
||||
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{first['version']}/checks").get_json()
|
||||
"""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-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote")
|
||||
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"])
|
||||
|
||||
uploaded = _upload(client, "cacu", "lifecycle", first["version"])
|
||||
assert uploaded.status_code == 201
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote").get_json()["status"] == "produccion"
|
||||
|
||||
second = _register(client, "v2", scenario="lifecycle", metrics={"auc": 0.86})
|
||||
_upload(client, "cacu", "lifecycle", second["version"])
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/promote")
|
||||
first = _trained("v1", "lifecycle", **REPORTS)
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first}/promote").get_json()["status"] == "produccion"
|
||||
second = _trained("v2", "lifecycle", **REPORTS)
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second}/promote")
|
||||
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
|
||||
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
assert statuses[first] == "retirada" and statuses[second] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second}/lineage").get_json()
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
|
||||
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
|
||||
assert lineage["artifacts"]
|
||||
assert lineage["routines"]["MUESTREO"] == {"method": "prueba"}
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
|
||||
def test_a_versions_files_download(client):
|
||||
"""ML-01b: a routine record downloads as itself, the model folder as a zip, and a path the run doesn't hold is 404.
|
||||
Fails if the endpoint stops going through `registry.artifact`."""
|
||||
version = _trained("v-desc", "descargas")
|
||||
base = f"/governance/model-versions/cacu/descargas/{version}/artifacts"
|
||||
record = client.get(f"{base}/rutinas/MUESTREO.json")
|
||||
assert record.status_code == 200 and record.get_json(force=True) == {"method": "prueba"}
|
||||
assert "attachment" in record.headers["Content-Disposition"]
|
||||
model = client.get(f"{base}/model")
|
||||
assert model.status_code == 200 and 'model.zip' in model.headers["Content-Disposition"]
|
||||
assert client.get(f"{base}/../../mlflow.db").status_code == 404
|
||||
assert client.get(f"{base}/rutinas/OTRO.json").status_code == 404
|
||||
|
||||
|
||||
def test_reports_can_be_attached_later(client):
|
||||
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
|
||||
response = client.patch(
|
||||
@@ -127,17 +165,72 @@ def test_reports_can_be_attached_later(client):
|
||||
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
|
||||
|
||||
|
||||
def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
def test_bad_registrations_are_rejected(client):
|
||||
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
|
||||
dev = client.post("/governance/model-versions", json={"domain": "cacu", "scenario": "malas-subidas", "environment": "DEV"}).get_json()
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="NOPE").status_code == 400
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="ONNX_CHECKPOINT", name="m.onnx", data=b"junk").status_code == 400
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404
|
||||
|
||||
|
||||
def test_training_needs_a_dbt_manifest(client, monkeypatch):
|
||||
"""Pins down: with no `DBT_MANIFEST`, `/train` refuses before running anything. Fails if it tries to train with
|
||||
no manifest configured instead of failing fast."""
|
||||
monkeypatch.delenv("DBT_MANIFEST", raising=False)
|
||||
|
||||
response = client.post("/governance/model-versions/cacu/cin2_logistic/train")
|
||||
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_training_runs_the_same_pipeline_entrenar_does(client, monkeypatch):
|
||||
"""Pins down: `/train` calls `models.__main__.main` with exactly the arguments the `entrenar` compose profile
|
||||
runs (export from dbt, PROD, train, promote), reading the manifest path from `DBT_MANIFEST`, and returns its
|
||||
captured output on success. Fails if the route drifts from that one-shot invocation, or stops using the
|
||||
deployment's own manifest."""
|
||||
monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json")
|
||||
calls = []
|
||||
|
||||
def fake_main(argv):
|
||||
calls.append(argv)
|
||||
print("trained: version 1, from dbt/1.parquet")
|
||||
print("in production: version 1")
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr("models.__main__.main", fake_main)
|
||||
|
||||
response = client.post("/governance/model-versions/cacu/cin2_logistic/train")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert calls == [["run", "cacu", "cin2_logistic", "--export", "--source", "dbt", "--manifest",
|
||||
"/data/dbt/manifest.json", "--environment", "prod", "--train", "--promote"]]
|
||||
assert "in production: version 1" in response.get_json()["output"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stderr, expected_status", [
|
||||
("no such model: cacu/ninguno\n", 404),
|
||||
("not promoted, missing: MLD-01 (reporte de pruebas técnicas)\n", 409),
|
||||
("a query of cacu/cohorte_vigilancia failed (no such table: cohorte_armado)\n", 503),
|
||||
])
|
||||
def test_training_failures_map_to_their_status(client, monkeypatch, stderr, expected_status):
|
||||
"""Pins down: an unknown model is 404, a trained-but-unpromotable version is 409 (attach reports, then
|
||||
`/promote`), and anything else operational is 503. Fails if a failure that needs a human step (missing reports)
|
||||
reads the same as a hard, transient failure, or either is swallowed as success."""
|
||||
import sys
|
||||
|
||||
def fake_main(argv):
|
||||
sys.stderr.write(stderr)
|
||||
return 1
|
||||
|
||||
monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json")
|
||||
monkeypatch.setattr("models.__main__.main", fake_main)
|
||||
|
||||
response = client.post("/governance/model-versions/cacu/cin2_logistic/train")
|
||||
|
||||
assert response.status_code == expected_status
|
||||
assert response.get_json()["error"] == stderr.strip()
|
||||
|
||||
|
||||
def test_ocr_run_unknown_job_is_404(client):
|
||||
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
|
||||
assert response.status_code == 404
|
||||
@@ -168,6 +261,35 @@ def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
assert again["skipped_already_done"] >= 1
|
||||
|
||||
|
||||
def test_eeg_run_analyses_at_most_the_limit_with_the_configured_cluster(client, monkeypatch):
|
||||
"""Pins down: `POST /governance/eeg/run` runs the EEG analysis in the request with the body's `limit` (5 by
|
||||
default), `all` and the cluster `EEG_ANALYSIS_CLUSTER` names, and answers its summary.
|
||||
|
||||
Fails if the route stops bounding the batch (a request could then run for hours) or ignores the body.
|
||||
"""
|
||||
import models.eeg_analysis
|
||||
from models.eeg_analysis import Summary
|
||||
|
||||
calls = []
|
||||
monkeypatch.setattr(models.eeg_analysis, "analyze_pending",
|
||||
lambda **kwargs: calls.append(kwargs) or Summary(pending=2, valid=1, not_valid=1, failed=0))
|
||||
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "sync")
|
||||
body = client.post("/governance/eeg/run", json={}).get_json()
|
||||
assert body == {"pending": 2, "valid": 1, "not_valid": 1, "failed": 0}
|
||||
client.post("/governance/eeg/run", json={"limit": 1, "all": True, "cluster": "local"})
|
||||
assert calls == [{"everything": False, "limit": 5, "cluster": "sync"},
|
||||
{"everything": True, "limit": 1, "cluster": "local"}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [{"limit": 0}, {"limit": "many"}, {"cluster": "everywhere"}])
|
||||
def test_eeg_run_refuses_a_bad_limit_or_cluster(client, body):
|
||||
"""Pins down: a limit that isn't a positive whole number, or an unknown cluster, is a 400 before anything runs.
|
||||
|
||||
Fails if the route starts an analysis on a body it can't honour.
|
||||
"""
|
||||
assert client.post("/governance/eeg/run", json=body).status_code == 400
|
||||
|
||||
|
||||
def test_list_ocr_jobs(client):
|
||||
body = client.get("/governance/ocr/jobs").get_json()
|
||||
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
|
||||
@@ -241,3 +363,135 @@ def test_ocr_correct_rejects_unknown_column(client):
|
||||
|
||||
def test_ocr_blob_not_found_for_unknown_row(client):
|
||||
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
|
||||
|
||||
|
||||
def _notebook(*sources: str) -> bytes:
|
||||
cells = [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": s} for s in sources]
|
||||
return json.dumps({"cells": cells, "metadata": {}, "nbformat": 4, "nbformat_minor": 5}).encode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def notebooks(tmp_path, monkeypatch):
|
||||
"""Build 4 of dbt's `cacu/cohorte_vigilancia` under `COHORTS_DIR`, the Jupyter renderer, and `submit` running the
|
||||
notebook before the request answers."""
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from datetime import datetime, timezone
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from webapi.blueprints import governance
|
||||
|
||||
row = {"pac_id": 1, "fecha_indice": date(2025, 1, 1), "fecha": date(2025, 1, 1),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
||||
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "S1"}
|
||||
table = pa.Table.from_pandas(pd.DataFrame([row], columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "4.parquet"
|
||||
path.parent.mkdir(parents=True)
|
||||
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "4", "datos_as_of": "2025-12-31",
|
||||
"n_members": "1"}
|
||||
pq.write_table(table.replace_schema_metadata(metadata), path)
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
monkeypatch.setattr(governance, "submit", lambda job, *args: job(*args))
|
||||
|
||||
|
||||
def _run(client, notebook: bytes, *, scenario="exploracion", **fields):
|
||||
form = {"file": (io.BytesIO(notebook), "analisis.ipynb"), "domain": "cacu", "scenario": scenario,
|
||||
"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "4", **fields}
|
||||
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
|
||||
|
||||
|
||||
def test_the_builds_a_notebook_can_run_on_are_listed(client, notebooks):
|
||||
"""Fails if `/cohort-files` stops listing exported builds from their files."""
|
||||
builds = client.get("/governance/cohort-files", query_string={"domain": "cacu"}).get_json()["builds"]
|
||||
assert builds == [{"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": 4, "datos_as_of": "2025-12-31",
|
||||
"n_members": "1"}]
|
||||
|
||||
|
||||
def test_an_uploaded_notebook_runs_on_the_build_and_its_page_is_sandboxed(client, notebooks):
|
||||
"""The upload answers 202 with the run; the notebook reads the build through `models.notebook`; its page is served
|
||||
with a sandbox policy and its files download. Fails if the endpoint stops handing the build to the run or serves
|
||||
the notebook's page as part of the app's origin."""
|
||||
started = _run(client, _notebook("from models.notebook import experiment\n"
|
||||
"print('miembros', experiment().cohort().pac_id.nunique())"))
|
||||
assert started.status_code == 202, started.get_json()
|
||||
run_id = started.get_json()["run_id"]
|
||||
run = client.get(f"/governance/experiments/{run_id}").get_json()
|
||||
assert run["status"] == "terminado" and run["cohort"]["build"] == "4" and run["notebook"] == "analisis"
|
||||
page = client.get(f"/governance/experiments/{run_id}/page")
|
||||
assert "miembros 1" in page.get_data(as_text=True) and "sandbox" in page.headers["Content-Security-Policy"]
|
||||
source = client.get(f"/governance/experiments/{run_id}/artifacts/notebook/analisis.ipynb")
|
||||
assert source.status_code == 200 and "attachment" in source.headers["Content-Disposition"]
|
||||
listed = client.get("/governance/experiments", query_string={"domain": "cacu", "scenario": "exploracion"}).get_json()
|
||||
assert run_id in [r["run_id"] for r in listed["experiments"]]
|
||||
|
||||
|
||||
def test_a_failing_notebook_reports_its_error(client, notebooks):
|
||||
"""Fails if a notebook whose cell raises is reported as finished or without its error."""
|
||||
run_id = _run(client, _notebook("raise ValueError('sin datos')")).get_json()["run_id"]
|
||||
run = client.get(f"/governance/experiments/{run_id}").get_json()
|
||||
assert run["status"] == "fallido" and "sin datos" in run["error"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fields, notebook", [
|
||||
({"build": "99"}, None),
|
||||
({"url": "tea/otra"}, None),
|
||||
({"build": "x"}, None),
|
||||
({"version": "999"}, None),
|
||||
({}, b"no es json"),
|
||||
({}, b'{"cells": [], "nbformat": 3}'),
|
||||
])
|
||||
def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
|
||||
"""A build that isn't exported, a cohort of another domain, an unknown version, or a file that isn't a notebook is
|
||||
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
|
||||
|
||||
@@ -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"]
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
@@ -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"}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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"
|
||||
|
||||
@@ -76,14 +76,16 @@ def _font(size: int = 34):
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
|
||||
"""A scanned-like page with two text blocks at known pixel positions and
|
||||
no text layer, so only the OCR/region path applies."""
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str, nacimiento: str = "1980-05-17") -> bytes:
|
||||
"""A scanned-like page with three text blocks on one line at known pixel
|
||||
positions and no text layer, so only the OCR/region path applies. The birth
|
||||
date is there because a patient row is not valid without it."""
|
||||
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
draw.text((40, 100), id_hospital, fill="black", font=font)
|
||||
draw.text((400, 100), sexo, fill="black", font=font)
|
||||
draw.text((560, 100), nacimiento, fill="black", font=font)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
@@ -99,6 +101,7 @@ def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
|
||||
|
||||
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
|
||||
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
|
||||
_NACIMIENTO_BBOX = (540 / _IMG_W, 60 / _IMG_H, 880 / _IMG_W, 180 / _IMG_H)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
@@ -229,6 +232,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
regions = [
|
||||
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
|
||||
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
|
||||
{"target_field": "pac_fecha_nacimiento", "page_numbers": [1], "bbox": list(_NACIMIENTO_BBOX)},
|
||||
]
|
||||
extract_response = client.post(
|
||||
"/imports/sources/pdf/regions/extract",
|
||||
@@ -236,13 +240,13 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
)
|
||||
assert extract_response.status_code == 200
|
||||
extract_body = extract_response.get_json()
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}]
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1980-05-17"}]
|
||||
assert extract_body["warnings"] == []
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "regions",
|
||||
|
||||
@@ -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"}
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""The live estimators the recomputation worker hands the cycle (`webapi.orchestration.estimators`,
|
||||
`webapi.recomputation`).
|
||||
|
||||
Fixtures: `base` (conftest) gives a migrated CaCu database with the synthetic staging; the registry and the live
|
||||
estimators are stubbed so no MLflow store or model is needed. The stub estimator is the cycle tests' `EstimadorFijo`.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orchestration import estimators
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
|
||||
|
||||
|
||||
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` offers a scenario the registry does not list as in production."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: [])
|
||||
assert estimators.live_estimators("cacu") == {}
|
||||
|
||||
|
||||
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, "in_production", lambda domain: ["cancer_pim", "cin2_pim", "no_such_model"])
|
||||
live = estimators.live_estimators("cacu")
|
||||
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):
|
||||
live[cohort][0].procedencia()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monkeypatch):
|
||||
"""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()]})
|
||||
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"]
|
||||
with base.motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo_lote")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT MIN(estado) FROM evaluacion_riesgo")).scalar_one() == "preliminary"
|
||||
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo")).scalar_one() > 0
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Derived fields and document columns inside an ordinary mapping: target
|
||||
fields computed from several source columns (joined, split, picked, read
|
||||
out of a longer text or translated), files kept in a column of a CSV or
|
||||
SQL source read for the fields the plain mapping left empty, and the
|
||||
captions nothing used, as the import report lists them.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database). Sources are
|
||||
built inline: CSV text through `_csv`, SQLite tables under `tmp_path`.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.mapping.derived import build_derivation, parse_derived
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _csv(content: str, **source) -> dict:
|
||||
return {"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": _b64(content.encode())}, **source}
|
||||
|
||||
|
||||
ROW = {"nombre": " ana maría ", "paterno": "Pérez", "materno": "", "completo": "Ana María Pérez López", "dir": "Calle 5, CP 64000"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rule,expected",
|
||||
[
|
||||
({"op": "concat", "columns": ["nombre", "paterno", "materno"]}, "ana maría Pérez"),
|
||||
({"op": "concat", "columns": ["paterno", "nombre"], "separator": ", ", "case": "upper"}, "PÉREZ, ANA MARÍA"),
|
||||
({"op": "template", "template": "{paterno} {materno} / {nombre}"}, "Pérez / ana maría"),
|
||||
({"op": "split", "column": "completo", "start": 0, "stop": -2}, "Ana María"),
|
||||
({"op": "split", "column": "completo", "start": -2, "stop": -1}, "Pérez"),
|
||||
({"op": "coalesce", "columns": ["materno", "paterno"]}, "Pérez"),
|
||||
({"op": "extract", "column": "dir", "pattern": r"CP\s*(\d{5})", "group": 1}, "64000"),
|
||||
({"op": "map", "column": "paterno", "values": {"pérez": "P"}}, "P"),
|
||||
({"op": "map", "column": "nombre", "values": {"x": "y"}, "keep_unmatched": False}, None),
|
||||
({"op": "column", "column": "paterno"}, "Pérez"),
|
||||
],
|
||||
)
|
||||
def test_each_operation_computes_its_value(rule, expected):
|
||||
"""Pins what every registered operation returns for one row, blanks
|
||||
skipped and spaces collapsed. Fails if an operation's semantics change
|
||||
(`start`/`stop` counting, separators, `case`, unmatched values)."""
|
||||
assert build_derivation(rule).apply(ROW) == expected
|
||||
|
||||
|
||||
def test_rules_are_checked_before_any_row_is_read():
|
||||
"""Unknown operations, missing parameters, bad patterns and fields the
|
||||
target lacks are refused up front. Fails if `parse_derived` lets a
|
||||
malformed rule through to fail row by row."""
|
||||
for bad in ({"op": "nope"}, {"op": "concat"}, {"op": "extract", "column": "a", "pattern": "("}, {"op": "split", "column": "a", "case": "x"}):
|
||||
with pytest.raises(ConnectorError):
|
||||
build_derivation(bad)
|
||||
with pytest.raises(ConnectorError):
|
||||
parse_derived({"no_such_field": "a"}, {"pac_sexo"})
|
||||
|
||||
|
||||
def test_short_forms_name_a_column_or_join_several():
|
||||
"""A rule given as a column name reads it; a list of columns joins them.
|
||||
Fails if `rule_from` stops accepting the short forms."""
|
||||
rules = parse_derived({"a": "paterno", "b": ["nombre", "paterno"]}, {"a", "b"})
|
||||
assert rules["a"].apply(ROW) == "Pérez" and rules["b"].apply(ROW) == "ana maría Pérez"
|
||||
|
||||
|
||||
def test_derived_fields_reach_validation_and_the_mapped_preview(client):
|
||||
"""A source whose id is split over two columns and whose sex comes
|
||||
coded validates cleanly once `derived` joins and translates them, and
|
||||
`/imports/mapped-preview` shows the rows as they would be written.
|
||||
Fails if `ImportSource.rows` stops applying `derived`."""
|
||||
source = _csv(
|
||||
"serie,numero,sx,cp,nac\nA,001,1,64000,1980-01-02\nB,002,2,64100,1975-03-04\n",
|
||||
column_mapping={"cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_id_hospital": {"op": "concat", "columns": ["serie", "numero"], "separator": "-"},
|
||||
"pac_sexo": {"op": "map", "column": "sx", "values": {"1": "F", "2": "M"}},
|
||||
},
|
||||
)
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert [(r["pac_id_hospital"], r["pac_sexo"]) for r in rows] == [("A-001", "F"), ("B-002", "M")]
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def test_a_field_cannot_be_both_mapped_and_derived(client):
|
||||
"""Fails if a field fed twice (mapping and `derived`) stops being refused."""
|
||||
source = _csv("a\n1\n", column_mapping={"a": "pac_id_hospital"}, derived={"pac_id_hospital": "a"})
|
||||
assert client.post("/imports/validate", json={"source": source}).status_code == 400
|
||||
|
||||
|
||||
def test_the_operations_are_listed_for_clients(client):
|
||||
"""`/imports/derivations` lists every operation with its parameters, so
|
||||
the import screen builds its forms from the server. Fails if an
|
||||
operation is registered without being described."""
|
||||
body = client.get("/imports/derivations").get_json()
|
||||
ops = {d["op"]: d for d in body["derivations"]}
|
||||
assert {"column", "concat", "template", "split", "coalesce", "extract", "map"} <= set(ops)
|
||||
assert [p["name"] for p in ops["split"]["params"]] == ["column", "separator", "start", "stop"]
|
||||
assert body["cases"] == ["upper", "lower", "title"]
|
||||
|
||||
|
||||
def _documents_table(tmp_path) -> str:
|
||||
"""Two rows of one order of patient P-7, one with its report as a PDF
|
||||
and one as base64 text, and a third row with no document."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
report = text_pdf([["VPH alto riesgo: POSITIVO"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, orden INTEGER, archivo BLOB, texto TEXT)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-7', 5, :f, NULL)"), {"f": report})
|
||||
conn.execute(
|
||||
text("INSERT INTO t VALUES ('P-7', 5, NULL, :t)"), {"t": _b64(text_pdf([["Genotipo 16: DETECTADO"]]))}
|
||||
)
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-8', 6, NULL, NULL)"))
|
||||
return url
|
||||
|
||||
|
||||
def _sql_source(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"column_mapping": {"pid": "pac_id_hospital", "orden": "ord_numero_hospital"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_a_sql_preview_flags_the_columns_that_hold_documents(client, tmp_path):
|
||||
"""Binary files and files written as base64 text are both flagged;
|
||||
plain values aren't. Fails if `document_columns` stops reaching the
|
||||
preview."""
|
||||
url = _documents_table(tmp_path)
|
||||
body = client.post("/imports/sources/sql/preview", json={"connection_string": url, "table": "t"}).get_json()
|
||||
assert set(body["document_columns"]) == {"archivo", "texto"}
|
||||
|
||||
|
||||
def test_document_columns_fill_what_the_mapping_leaves_empty(client, tmp_path):
|
||||
"""The mapped id and order are kept; the documents of both rows of the
|
||||
order add the fields they print; a row without documents passes
|
||||
through mapped. Fails if `documents` stops reading cells of an
|
||||
ordinary mapping, or loses the rows that have none."""
|
||||
source = _sql_source(_documents_table(tmp_path), documents={"columns": ["archivo", "texto"], "group_by": "orden"})
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
by_patient = {row["pac_id_hospital"]: row for row in rows}
|
||||
assert by_patient["P-7"]["ord_numero_hospital"] == 5
|
||||
assert by_patient["P-7"]["cit_vph_resultado"] == "POSITIVO"
|
||||
assert by_patient["P-7"]["cit_vph_genotipo_16"] == 1
|
||||
assert by_patient["P-8"]["ord_numero_hospital"] == 6
|
||||
|
||||
|
||||
def test_documents_of_a_mapping_can_be_reviewed_and_committed(client, tmp_path):
|
||||
"""`/imports/sources/document/extract` with `{source}` reviews the same
|
||||
records the commit writes, with the record's pages in `file_field`.
|
||||
Fails if the review and the commit read document columns differently."""
|
||||
source = _sql_source(
|
||||
_documents_table(tmp_path),
|
||||
documents={"columns": "archivo", "group_by": "orden", "file_field": "cit_pdf_blob"},
|
||||
label="t",
|
||||
)
|
||||
report = client.post("/imports/sources/document/extract", json={"source": source}).get_json()
|
||||
[record] = report["records"]
|
||||
assert record["fields"]["pac_id_hospital"]["method"] == "columna_fuente"
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
stored = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100)}
|
||||
assert stored["P-7"].cit_vph_resultado == "POSITIVO"
|
||||
assert stored["P-7"].cit_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_a_csv_column_of_base64_documents_is_read_like_a_sql_one(client):
|
||||
"""Document columns are not tied to SQL: a CSV whose column carries
|
||||
base64 PDFs feeds the same extraction. Fails if `documents` only works
|
||||
for one kind of source."""
|
||||
report = _b64(text_pdf([["VPH alto riesgo: NEGATIVO"]]))
|
||||
source = _csv(
|
||||
f"exp,doc\nC-1,{report}\n",
|
||||
target="cacu.CitologiaCervical",
|
||||
column_mapping={"exp": "pac_id_hospital"},
|
||||
documents={"columns": "doc"},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert row["pac_id_hospital"] == "C-1" and row["cit_vph_resultado"] == "NEGATIVO"
|
||||
|
||||
|
||||
def _id_and_file_table(tmp_path) -> str:
|
||||
"""Each row has only an id and a file; every other value is printed
|
||||
in the file under captions no target field knows."""
|
||||
url = f"sqlite:///{tmp_path / 'files.db'}"
|
||||
report = text_pdf([["Tipo de persona: Mujer", "Domicilio actual: Calle 5, C.P. 64000", "Nacida el: 02/01/1980"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, archivo BLOB)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('Q-1', :f)"), {"f": report})
|
||||
return url
|
||||
|
||||
|
||||
def _paciente_from_file(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"documents": {"columns": "archivo"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_captions_printed_in_documents_are_offered_as_columns(client, tmp_path):
|
||||
"""`/imports/sources/document/columns` lists the source's own columns
|
||||
and every caption its documents print, with their values. Fails if
|
||||
discovered captions stop becoming columns of the source."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/columns", json={"source": _paciente_from_file(_id_and_file_table(tmp_path))}
|
||||
).get_json()
|
||||
names = [column["name"] for column in body["columns"]]
|
||||
assert {"pid", "Tipo de persona", "Domicilio actual", "Nacida el"} <= set(names)
|
||||
[row] = body["sample_rows"]
|
||||
assert row["Tipo de persona"] == "Mujer"
|
||||
|
||||
|
||||
def test_mapping_and_rules_reach_what_the_documents_print(client, tmp_path):
|
||||
"""A caption maps onto a field like a column does, and derived rules
|
||||
translate or cut values read from the page. Fails if the mapping and
|
||||
`derived` stop running over the record's document values."""
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path),
|
||||
column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_sexo": {"op": "map", "column": "Tipo de persona", "values": {"mujer": "F", "hombre": "M"}},
|
||||
"pac_codigo_postal": {"op": "extract", "column": "Domicilio actual", "pattern": r"\d{5}"},
|
||||
},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert (row["pac_id_hospital"], row["pac_sexo"], row["pac_codigo_postal"]) == ("Q-1", "F", "64000")
|
||||
assert row["pac_fecha_nacimiento"] == "02/01/1980"
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def _last_report() -> dict:
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()[-1]
|
||||
|
||||
|
||||
def test_the_import_report_lists_unused_captions_never_their_values(client, tmp_path, monkeypatch):
|
||||
"""Captions the documents print that nothing in the import used are
|
||||
listed with how many records print them, and none of their values
|
||||
reaches the report. Below the minimum count they are only counted.
|
||||
Fails if `unused_captions` stops reaching the audit, lists a caption
|
||||
the mapping uses, or lets a value through."""
|
||||
import json
|
||||
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path), column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"}
|
||||
)
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "1")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {"Tipo de persona": 1, "Domicilio actual": 1}
|
||||
text = json.dumps(_last_report(), ensure_ascii=False)
|
||||
assert "Mujer" not in text and "64000" not in text and "02/01/1980" not in text
|
||||
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "2")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {} and report["etiquetas_sin_usar_poco_frecuentes"] == 2
|
||||
@@ -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"
|
||||
|
||||
|
||||
|
||||
@@ -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"]
|
||||
@@ -15,6 +15,7 @@ from sqlalchemy import create_engine, text
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.project import cohort_urls
|
||||
from webapi.orchestration.connection import point_to
|
||||
|
||||
ANIO = 2025
|
||||
@@ -65,16 +66,24 @@ 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_su_cohorte_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 (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":
|
||||
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
urls = set(cohort_urls(proyecto, ctx.dbt_manifest))
|
||||
if not urls:
|
||||
assert "cohorts" not in [p.name for p in pasos]
|
||||
return
|
||||
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
|
||||
armados = [p.summary for p in pasos if p.name == "cohorts"][0]
|
||||
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() == 1
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
|
||||
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
|
||||
for armado_id, _ in armados.values():
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado WHERE armado_id = :a"),
|
||||
{"a": armado_id}).scalar_one() == con.execute(
|
||||
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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: its seven measures, without strata; TEA: the age group and its
|
||||
# ten measures.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7, "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": 7, "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
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
@@ -33,8 +35,16 @@ def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
assert {"load", "catalogs"} <= antes(deps, "check_silver")
|
||||
|
||||
|
||||
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
|
||||
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
|
||||
def test_las_cohortes_son_las_del_manifiesto_de_dbt(tmp_path, monkeypatch):
|
||||
"""Pins down: a project builds cohorts and estimates only if dbt's manifest has a cohort of it (`meta.cohort` of
|
||||
a population query), today only CaCu's; without a manifest no project does. Fails if the cycle reads cohort
|
||||
definitions from anywhere else than dbt."""
|
||||
manifest = tmp_path / "manifest.json"
|
||||
nodo = {"config": {"meta": {"cohort": "cacu/cohorte_vigilancia", "kind": "population"}}}
|
||||
manifest.write_text(json.dumps({"nodes": {"model.p.cacu_surveillance_all_patients": nodo}}))
|
||||
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu", manifest))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto, manifest))
|
||||
monkeypatch.delenv("DBT_MANIFEST", raising=False)
|
||||
assert not {"cohorts", "estimate"} & set(steps_of("cacu"))
|
||||
|
||||
@@ -75,7 +75,9 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
|
||||
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
|
||||
"valores": len(catalogo.valores)}
|
||||
|
||||
assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
|
||||
conteos = base.run("catalogs")["catalogs"]
|
||||
assert conteos.pop("mapeos_nuevos") > 0
|
||||
assert conteos == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
@@ -83,7 +85,8 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.run("catalogs")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
assert base.run("catalogs")["catalogs"]["retirados"] == 0
|
||||
conteos = base.run("catalogs")["catalogs"]
|
||||
assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0)
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ class EstimadorFijo:
|
||||
|
||||
def estimar(self, columnas, filas):
|
||||
self.columnas = columnas
|
||||
return [(fila[0], self.horizonte, self.probabilidad, None, None) for fila in filas]
|
||||
return [(fila[0], fila[1], self.horizonte, self.probabilidad, None, None) for fila in filas]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -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"])
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1,99 +0,0 @@
|
||||
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
|
||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
||||
there.
|
||||
|
||||
Fixtures: `client`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`:
|
||||
a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the
|
||||
same app without `DEV_REVISION`.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
|
||||
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"}
|
||||
HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def seeded(client):
|
||||
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
|
||||
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", 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="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (scored, unscored)])
|
||||
session.flush()
|
||||
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
|
||||
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in
|
||||
ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which
|
||||
would break the WebApp's validation."""
|
||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
||||
|
||||
body = response.get_json()
|
||||
assert response.status_code == 200 and body["simulado"] is True
|
||||
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
|
||||
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
|
||||
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
|
||||
horizons = body["riesgo"]["horizontes"]
|
||||
assert all(set(h) == HORIZON_KEYS for h in horizons)
|
||||
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
|
||||
|
||||
|
||||
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
||||
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
|
||||
null. Fails if either case errors or invents a risk."""
|
||||
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
|
||||
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
|
||||
|
||||
assert member["cohorte"] is not None and member["riesgo"] is None
|
||||
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
|
||||
|
||||
|
||||
def test_an_unknown_patient_is_404(client, seeded):
|
||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
||||
|
||||
|
||||
def test_outside_dev_the_route_does_not_exist(fuera_de_dev):
|
||||
"""Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside
|
||||
the simulated DEV deployment."""
|
||||
assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Extraction's ranker in WebApi: the document review reports each field's
|
||||
alternatives, whether the record is about the target and which extraction
|
||||
version read it; an import whose records a person corrected teaches the
|
||||
domain's ranker once it is written (`webapi.imports.services.
|
||||
review_learning`); and `python -m webapi.nlp` scores and trains against an
|
||||
answer key.
|
||||
|
||||
Fixtures: `client` (the app over fresh CaCu, CaMa and TEA databases),
|
||||
`registry` (a SQLite MLflow per test with its files in `tmp_path`, the
|
||||
ranker and learning switched on, and learning run synchronously). Documents are made up inline with
|
||||
`text_pdf`.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
from concurrent.futures import Future
|
||||
|
||||
import pytest
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
from webapi import nlp
|
||||
from webapi.imports.services import review_learning
|
||||
|
||||
REPORT = text_pdf([["LABORATORIO DE CITOLOGÍA", "Expediente: RV-0001", "No. de orden: 9001", "Prueba de VPH por PCR: POSITIVO",
|
||||
"Observaciones: se sugiere colposcopía; en caso de VPH negativo repetir en un año."]])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("cama")
|
||||
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
|
||||
|
||||
|
||||
class _Now:
|
||||
"""An executor that runs each task as it is submitted."""
|
||||
|
||||
def submit(self, fn, *args):
|
||||
future = Future()
|
||||
future.set_result(fn(*args))
|
||||
return future
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def registry(tmp_path, monkeypatch):
|
||||
import mlflow
|
||||
|
||||
from models.io import extraction_ranker
|
||||
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
mlflow.set_tracking_uri(uri)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("EXTRACTION_RANKER", "auto")
|
||||
monkeypatch.setenv("EXTRACTION_LEARNING", "1")
|
||||
monkeypatch.setattr(extraction_ranker, "_cache", {})
|
||||
monkeypatch.setattr(review_learning, "_executor", _Now())
|
||||
from models.io.registry import registry as models_registry
|
||||
|
||||
yield models_registry
|
||||
|
||||
|
||||
def _source(**options) -> dict:
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital",
|
||||
"cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"files": [{"name": "r.pdf", "file_base64": base64.b64encode(REPORT).decode()}], **options},
|
||||
"label": "documentos",
|
||||
}
|
||||
|
||||
|
||||
def test_the_review_reports_alternatives_topic_and_version(client):
|
||||
"""Fails if the review loses the other readings a person can pick, the
|
||||
subject check, or the extraction version that will be stored."""
|
||||
body = client.post("/imports/sources/document/extract", json={"files": _source()["payload"]["files"], "target": "cacu.CitologiaCervical"}).get_json()
|
||||
[record] = body["records"]
|
||||
assert record["on_topic"] is True
|
||||
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert record["fields"]["cit_vph_resultado"]["assertion"] == "afirmado"
|
||||
assert body["nlp_version"].startswith("extraction ")
|
||||
assert all(isinstance(options, list) for options in record["alternatives"].values())
|
||||
|
||||
|
||||
def test_a_corrected_import_teaches_the_ranker(client, registry):
|
||||
"""Committing a document source with a correction registers a new DEV
|
||||
version of the domain's ranker, learned from that record. Fails if
|
||||
`commit_sources` stops calling `learn_from_reviews` or the examples are
|
||||
lost on the way."""
|
||||
source = _source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert result["ok"], result
|
||||
[version] = registry.versions("cacu", "extraccion")
|
||||
assert version["status"] == "desarrollo"
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
assert current("cacu").examples > 0
|
||||
|
||||
|
||||
def test_imports_without_corrections_or_with_learning_off_teach_nothing(client, registry, monkeypatch):
|
||||
"""Fails if an untouched import, or one made with
|
||||
`EXTRACTION_LEARNING=0`, creates ranker versions."""
|
||||
client.post("/imports/commit", json={"sources": [_source()]})
|
||||
monkeypatch.setenv("EXTRACTION_LEARNING", "0")
|
||||
client.post("/imports/commit", json={"sources": [_source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})]})
|
||||
assert registry.versions("cacu", "extraccion") == []
|
||||
|
||||
|
||||
def test_the_command_scores_and_trains_against_an_answer_key(tmp_path, registry):
|
||||
"""`evaluate` scores per field and overall without printing values
|
||||
unless asked; `train` estimates on held-out documents, then registers
|
||||
a version. Fails if the command's key format or outputs change."""
|
||||
folder = tmp_path / "documentos"
|
||||
folder.mkdir()
|
||||
(folder / "a.pdf").write_bytes(REPORT)
|
||||
(folder / "b.pdf").write_bytes(text_pdf([["Biopsia cervical dirigida", "Diagnóstico:", "NIC I"]]))
|
||||
key = {
|
||||
"a.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": "POSITIVO", "pac_id_hospital": "RV-0001"}},
|
||||
"b.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": None}, "cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG"}},
|
||||
}
|
||||
(tmp_path / "clave.json").write_text(json.dumps(key))
|
||||
paths = {"documents": str(folder), "key": str(tmp_path / "clave.json")}
|
||||
evaluated = nlp.command_evaluate(argparse.Namespace(**paths, with_values=False, no_ranker=True))
|
||||
assert evaluated["global"]["f1"] == 1.0
|
||||
assert evaluated["errores"] == []
|
||||
trained = nlp.command_train(argparse.Namespace(**paths))
|
||||
assert set(trained) == {"sin_ranker", "estimacion_dejando_uno_fuera", "versiones"}
|
||||
assert trained["versiones"] == {"cacu": "1"}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: `GET /cacu/riesgos/lotes` and the confirm/void routes (`webapi.risk_batches`): which
|
||||
batches are listed, that confirming or voiding moves a batch off the list and that the route rejects a missing
|
||||
reason or an unknown batch. The reads and writes behind it are Persistance's, tested there.
|
||||
|
||||
Fixtures: `client`, the app over the kit's CaCu demonstration database (`conftest.cliente_de`); `batches`, two
|
||||
batches over a fresh surveillance build, both still preliminary.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def batches(client):
|
||||
"""Three preliminary batches over one patient of the demo data: `older` and `newer` are confirmed/voided by
|
||||
the tests that exercise those routes; `untouched` stays preliminary for the tests that must not change a
|
||||
batch's state (an unknown id, a missing reason)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
pac_id = cacu.persona_repository.list(limit=1)[0].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(2026, 12, 31), huella="risk-batches", marco_sha="m",
|
||||
n_miembros=1, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=pac_id, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id)))
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
provenance = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"}
|
||||
|
||||
def batch(version, risk, ahora):
|
||||
lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version},
|
||||
"cin2_12m", [(pac_id, date(2025, 1, 1), 1.0, risk, None, None)], ahora=ahora)
|
||||
return lote_id
|
||||
|
||||
older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
newer = batch("2", 0.2, datetime(2026, 10, 2, tzinfo=timezone.utc))
|
||||
untouched = batch("3", 0.3, datetime(2026, 10, 3, tzinfo=timezone.utc))
|
||||
return older, newer, untouched
|
||||
|
||||
|
||||
def test_pending_batches_are_listed_newest_first(client, batches):
|
||||
"""Pins down: every preliminary batch is listed, newest first, with the fields the WebApp reads. Fails if the
|
||||
order is reversed or a field is renamed."""
|
||||
older, newer, untouched = batches
|
||||
|
||||
body = client.get("/cacu/riesgos/lotes").get_json()
|
||||
|
||||
assert [b["lote_id"] for b in body if b["lote_id"] in batches] == [untouched, newer, older]
|
||||
listed = next(b for b in body if b["lote_id"] == untouched)
|
||||
assert set(listed) == {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "n_evaluaciones"}
|
||||
assert (listed["modelo_nombre"], listed["modelo_version"], listed["n_evaluaciones"]) == ("cacu-cin2_logistic", "3", 1)
|
||||
|
||||
|
||||
def test_confirming_drops_a_batch_off_the_pending_list(client, batches):
|
||||
"""Pins down: confirming a batch moves its evaluations to `final` and it stops being listed as pending. Fails if
|
||||
it stays listed, or the evaluations aren't actually changed."""
|
||||
older, _, _ = batches
|
||||
|
||||
response = client.post(f"/cacu/riesgos/lotes/{older}/confirmar", json={"reason": "revisado por clínica"})
|
||||
|
||||
assert response.status_code == 200 and response.get_json() == {"lote_id": older, "evaluaciones_cambiadas": 1}
|
||||
assert older not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()]
|
||||
|
||||
|
||||
def test_voiding_also_drops_a_batch_off_the_pending_list(client, batches):
|
||||
"""Pins down: voiding is the other way out of the pending list, distinct from confirming. Fails if it confirms
|
||||
instead of voiding, or leaves the batch pending."""
|
||||
_, newer, _ = batches
|
||||
|
||||
response = client.post(f"/cacu/riesgos/lotes/{newer}/anular", json={"reason": "modelo equivocado"})
|
||||
|
||||
assert response.status_code == 200 and response.get_json()["evaluaciones_cambiadas"] == 1
|
||||
assert newer not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()]
|
||||
|
||||
|
||||
def test_a_decision_needs_a_reason(client, batches):
|
||||
"""Pins down: confirming or voiding with no reason is refused and changes nothing. Fails if the batch moves
|
||||
anyway, which would leave a decision with no recorded motive (ADR-MD-008)."""
|
||||
_, _, untouched = batches
|
||||
|
||||
response = client.post(f"/cacu/riesgos/lotes/{untouched}/confirmar", json={"reason": " "})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert untouched in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()]
|
||||
|
||||
|
||||
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
|
||||
@@ -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
|
||||
|
||||
+141
-18
@@ -1,32 +1,30 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y siempre simulada.
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: cuándo existe, la forma y los códigos de error.
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: que existe sin `DEV_REVISION`, la forma y los códigos
|
||||
de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostración de CaCu.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
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", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
"""Fija: sin `DEV_REVISION` la ruta existe, con la forma del contrato y `simulado: true`. Falla si la ruta
|
||||
vuelve a depender de una variable de entorno o cambia un campo."""
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||
@@ -34,7 +32,9 @@ def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
|
||||
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
|
||||
assert all(i["prioridad"] is None for i in cuerpo["items"])
|
||||
assert "pac_id" not in response.get_data(as_text=True)
|
||||
# The patient key is the platform's `pac_id`, the one the risk route takes; the hospital's id never leaves.
|
||||
assert all(i["pac_id"].isdigit() and i["id_seudonimo"] == i["pac_id"] for i in cuerpo["items"])
|
||||
assert "pac_id_hospital" not in response.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_el_pedido_se_respeta(client):
|
||||
@@ -42,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}")
|
||||
@@ -63,5 +64,127 @@ def test_una_pagina_de_mas_da_404(client):
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
|
||||
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
|
||||
def test_in_dev_esta_obsoleta():
|
||||
"""Fija: `in_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
|
||||
from webapi.follow_up.routes import in_dev
|
||||
|
||||
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"]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Exercise regular and cohort follow-up with an authorized synthetic reader."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
|
||||
from webapi.cama_analysis import analysis, revision_of
|
||||
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""A fixed six-person cohort and a server-controlled access callback."""
|
||||
rows = [dict(pac_id=str(n + 1), mastografia_fecha='2026-10-15',
|
||||
birads='BIRADS_5', grupo_edad='50-59', biopsia=None,
|
||||
biopsia_fecha=None) for n in range(6)]
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(analysis, url_prefix='/cama')
|
||||
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
|
||||
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=lambda cutoff: rows,
|
||||
CAMA_COHORT_ACCESS=lambda request: request.headers.get('X-Test') == 'yes')
|
||||
return app.test_client()
|
||||
|
||||
|
||||
def test_regular_list_detail_and_export_use_the_same_selection(client):
|
||||
"""Pagination, detail and export resolve the same filtered persistent cohort."""
|
||||
headers = {'X-Test': 'yes'}
|
||||
query = '?corte=2026-10-20&meses=3&birads=BIRADS_5'
|
||||
page = client.get('/cama/seguimiento' + query + '&page_size=2', headers=headers).get_json()
|
||||
assert page['paginacion']['total_items'] == 6
|
||||
assert page['cohorte'] == 'cama_birads_v1'
|
||||
context = '&cohorte=' + page['cohorte'] + '&escenario=' + page['escenario'] + '&revision=' + page['revision']
|
||||
rows = []
|
||||
for number in (1, 2, 3):
|
||||
rows.extend(client.get('/cama/seguimiento' + query + context + f'&page_size=2&page={number}', headers=headers).get_json()['items'])
|
||||
exported = client.get('/cama/seguimiento/exportacion' + query + context, headers=headers).get_json()
|
||||
assert exported['items'] == rows
|
||||
assert client.get('/cama/pacientes/' + rows[0]['pac_id'] + query + context, headers=headers).get_json()['item'] == rows[0]
|
||||
assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store'
|
||||
|
||||
|
||||
def test_regular_followup_checks_access_and_suppression(client):
|
||||
"""The ordinary route cannot bypass authorization or suppression."""
|
||||
assert client.get('/cama/seguimiento').status_code == 403
|
||||
headers = {'X-Test': 'yes'}
|
||||
assert client.get('/cama/seguimiento?corte=2026-10-20&birads=BIRADS_4', headers=headers).status_code == 403
|
||||
assert client.get('/cama/seguimiento?corte=2026-10-20&estatus=BENIGNO', headers=headers).status_code == 400
|
||||
assert client.get('/cama/seguimiento?revision=' + '0' * 64, headers=headers).status_code == 400
|
||||
client.application.config['CAMA_COHORT_ACCESS'] = 'invalid'
|
||||
assert client.get('/cama/seguimiento', headers=headers).status_code == 403
|
||||
|
||||
|
||||
def test_disabled_provider_and_empty_window(client):
|
||||
"""Unavailable sources fail closed and an empty unfiltered window stays empty."""
|
||||
headers = {'X-Test': 'yes'}
|
||||
body = client.get('/cama/seguimiento?corte=2025-01-01&meses=3', headers=headers).get_json()
|
||||
assert body['items'] == [] and body['paginacion']['total_items'] == 0
|
||||
client.application.config['CAMA_COHORT_READER'] = None
|
||||
assert client.get('/cama/seguimiento', headers=headers).status_code == 503
|
||||
|
||||
|
||||
def test_provider_failure_does_not_break_other_routes(client):
|
||||
"""A failing cohort source returns unavailable while the app can serve other requests."""
|
||||
def fail(_cutoff):
|
||||
raise RuntimeError('provider unavailable')
|
||||
|
||||
client.application.add_url_rule('/health', 'health', lambda: {'status': 'ok'})
|
||||
client.application.config['CAMA_COHORT_READER'] = fail
|
||||
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
|
||||
assert client.get('/cama/seguimiento?corte=2026-10-20', headers={'X-Test': 'yes'}).status_code == 503
|
||||
assert client.get('/health').get_json() == {'status': 'ok'}
|
||||
@@ -78,22 +78,17 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
|
||||
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
|
||||
_json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"),
|
||||
_json([{"met_id": "met-1", "met_eeg_id": "eeg-1", "met_codigo": "RITMO_POSTERIOR", "met_valor": 5.5}], "tea.EegMetrica"),
|
||||
_json([{"mel_met_id": "met-1", "mel_electrodo": "O1", "mel_valor": -1.2}], "tea.EegMetricaElectrodo"),
|
||||
_json([{"neu_id": "neu-1", "neu_ord_id": "ord-1", "neu_pac_id": 1}], "tea.EvaluacionNeuropediatrica"),
|
||||
]
|
||||
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.tea import (
|
||||
ados2_repository,
|
||||
eeg_metrica_electrodo_repository,
|
||||
eeg_metrica_repository,
|
||||
eeg_repository,
|
||||
)
|
||||
from persistance.tea import ados2_repository, eeg_repository, evaluacion_neuropediatrica_repository
|
||||
|
||||
metrica = eeg_metrica_repository.get(eeg_metrica_electrodo_repository.list()[0].mel_met_id)
|
||||
assert eeg_repository.get(metrica.met_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
assert eeg_repository.get("eeg-1").eeg_ord_id == "ord-1"
|
||||
assert eeg_repository.get("eeg-1").eeg_id_registro_laboratorio == "L-1"
|
||||
assert ados2_repository.get("ado-1").ado_ord_id == "ord-1"
|
||||
assert evaluacion_neuropediatrica_repository.get("neu-1").neu_ord_id == "ord-1"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`):
|
||||
many forms to one code, no code for an unknown form, the same form read per source system and per date, and two
|
||||
codes for one form rejected when they're in force together; every catalog's TOML passing that check; and, in each
|
||||
domain's database, the catalog step seeding `cat_mapeo` without touching a stored row and `register` refusing a
|
||||
mapping that breaks the function.
|
||||
|
||||
Fixtures: `base` (conftest), each domain's migrated fixture database; the other tests build their rows.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
from webapi.orchestration.reference.source_mapping import (
|
||||
CATALOG, SourceForm, ambiguities, check_function, from_result, normalize, register, resolve,
|
||||
)
|
||||
|
||||
HER2 = "biopsia.her2"
|
||||
LAB_A = [SourceForm("lab_a", HER2, "3+", "H3", None, date(2026, 12, 31)),
|
||||
SourceForm("lab_a", HER2, "Positivo", "H3", None, date(2026, 12, 31))]
|
||||
LAB_B = [SourceForm("lab_b", HER2, "Positivo (score 3)", "H3", date(2027, 1, 1)),
|
||||
SourceForm("lab_b", HER2, "Positivo", "H2", date(2027, 1, 1))]
|
||||
|
||||
|
||||
def test_many_forms_give_one_code_and_an_unknown_form_none():
|
||||
"""Pins down: the mapping isn't injective and is partial: several spellings, compared without case, accents or
|
||||
extra spaces, give the same code; a spelling with no mapping gives None. Fails if `normalize` stops folding or
|
||||
`resolve` invents a code."""
|
||||
assert {resolve(LAB_A, "lab_a", HER2, f) for f in ("3+", " positivo ", "POSITIVO")} == {"H3"}
|
||||
assert resolve(LAB_A, "lab_a", HER2, "Equívoco") is None
|
||||
assert normalize(" Positívo (score 3) ") == "POSITIVO (SCORE 3)"
|
||||
|
||||
|
||||
def test_a_form_is_read_per_source_system_and_per_date():
|
||||
"""Pins down: "Positivo" is H3 at lab A and H2 at lab B, and a mapping applies only to documents dated within its
|
||||
validity. Fails if `resolve` ignores the system or the dates, letting one lab's spelling leak into another's."""
|
||||
rows = LAB_A + LAB_B
|
||||
assert resolve(rows, "lab_a", HER2, "Positivo", date(2026, 6, 1)) == "H3"
|
||||
assert resolve(rows, "lab_b", HER2, "Positivo", date(2027, 2, 1)) == "H2"
|
||||
assert resolve(rows, "lab_b", HER2, "Positivo", date(2026, 6, 1)) is None
|
||||
assert ambiguities(rows) == []
|
||||
|
||||
|
||||
def test_two_codes_for_one_form_in_force_together_are_rejected():
|
||||
"""Pins down: a form mapped to two codes with overlapping validity breaks the function: `check_function` names
|
||||
it and `resolve` gives None rather than either code. Two codes in validities that don't overlap, or the same
|
||||
code twice, are fine. Fails if the overlap test or the code comparison is dropped."""
|
||||
clash = SourceForm("lab_b", HER2, "positivo", "H3", date(2027, 6, 1))
|
||||
with pytest.raises(ValueError, match="se escribe igual para 'H2' y 'H3'"):
|
||||
check_function(LAB_B + [clash])
|
||||
assert resolve(LAB_B + [clash], "lab_b", HER2, "Positivo", date(2027, 7, 1)) is None
|
||||
corrected = [LAB_B[1]._replace(valid_to=date(2027, 5, 31)), clash]
|
||||
check_function(corrected)
|
||||
assert resolve(corrected, "lab_b", HER2, "Positivo", date(2027, 7, 1)) == "H3"
|
||||
check_function(LAB_B + [LAB_B[0]._replace(form="POSITIVO (SCORE 3)")])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_every_catalog_s_spellings_are_a_function(proyecto):
|
||||
"""Pins down: in each domain's TOML, every result's codes, labels and aliases map to one value each. Fails when
|
||||
an edit to a catalog gives one spelling two values."""
|
||||
estudios = tomllib.loads(ruta_de_catalogo(proyecto).read_text(encoding="utf-8"))
|
||||
rows = [row for estudio_id, estudio in estudios.items()
|
||||
for nombre, resultado in estudio.get("resultados", {}).items()
|
||||
for row in from_result(f"{estudio_id}.{nombre}", resultado)]
|
||||
check_function(rows)
|
||||
|
||||
|
||||
# --- the stored mappings, in each domain ---
|
||||
|
||||
|
||||
def a_coded_result(base) -> tuple[str, str, str]:
|
||||
"""A coded result of the domain's catalog with two values: (resultado_id, first valor_id, second valor_id)."""
|
||||
estudios = tomllib.loads(ruta_de_catalogo(base.proyecto).read_text(encoding="utf-8"))
|
||||
for estudio_id, estudio in estudios.items():
|
||||
for nombre, resultado in estudio.get("resultados", {}).items():
|
||||
valores = resultado.get("valores", ())
|
||||
if len(valores) >= 2:
|
||||
return f"{estudio_id}.{nombre}", valores[0]["valor"], valores[1]["valor"]
|
||||
raise AssertionError("el catálogo no tiene un resultado codificado con dos valores")
|
||||
|
||||
|
||||
def test_the_catalog_step_seeds_the_mappings_and_keeps_what_a_person_changed(base):
|
||||
"""Pins down: the catalog step adds the catalog's own mappings (each value's code among them) and, run again,
|
||||
adds nothing and leaves a person's row for a new form as it is. Fails if the step stops seeding or a deploy
|
||||
replaces stored rows."""
|
||||
base.run("catalogs")
|
||||
mappings = base.ctx.repos.silver.mappings
|
||||
resultado, primero, segundo = a_coded_result(base)
|
||||
sembradas = mappings.forms(sistema_fuente_id=CATALOG, resultado_id=resultado, clase="valor")
|
||||
assert {(m.forma, m.valor_id) for m in sembradas} >= {(primero, primero), (segundo, segundo)}
|
||||
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=" forma del curador ", registrado_por="curador",
|
||||
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
assert base.run("catalogs")["catalogs"]["mapeos_nuevos"] == 0
|
||||
[mia] = mappings.forms(forma_normalizada="FORMA DEL CURADOR")
|
||||
assert (mia.forma, mia.valor_id, mia.registrado_por) == ("forma del curador", segundo, "curador")
|
||||
|
||||
|
||||
def test_register_refuses_a_second_code_for_a_form_in_force(base):
|
||||
"""Pins down: `register` checks the new row against the stored ones: the catalog's own code of one value can't
|
||||
be mapped to another value, and a lab's form can, once the first row's validity ends before the second's starts.
|
||||
Fails if the write path stops running `check_function`."""
|
||||
base.run("catalogs")
|
||||
mappings = base.ctx.repos.silver.mappings
|
||||
resultado, primero, segundo = a_coded_result(base)
|
||||
with pytest.raises(ValueError, match="se escribe igual"):
|
||||
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=primero, registrado_por="curador",
|
||||
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
viejo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="Código de laboratorio",
|
||||
registrado_por="curador", vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=primero)
|
||||
mappings.close(viejo.mapeo_id, date(2026, 12, 31))
|
||||
nuevo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="codigo de LABORATORIO",
|
||||
registrado_por="curador", vigente_desde=date(2027, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
filas = mappings.forms(forma_normalizada=normalize("Código de laboratorio"))
|
||||
assert [f.mapeo_id for f in filas] == [viejo.mapeo_id, nuevo.mapeo_id]
|
||||
@@ -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
|
||||
@@ -0,0 +1,148 @@
|
||||
"""What this module covers: what the EEG analysis writes to TEA's bronze, carried into silver
|
||||
(`webapi.orchestration.silver.tea`) and into dbt's views of the EEG's quality checks, metrics and electrodes
|
||||
(`tea_paciente_eeg_criterios`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`).
|
||||
|
||||
Fixtures: `loaded`, a TEA database (`base_de`) loaded up to the event models, with one patient and one analysed EEG
|
||||
`e-1`: valid, triage `completo`; three checks (95 % clean windows against a low limit of 60, the triage level as text,
|
||||
and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0, p5/median/p95 5/6/7 and the registered
|
||||
label of the baseline it was compared against, and its N2 spindles' value 2.5 with z -0.4 at Fz.
|
||||
"""
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
def _rows(sesion):
|
||||
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Mchat, Pacientes
|
||||
|
||||
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
|
||||
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
|
||||
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1, eeg_nivel="completo",
|
||||
eeg_fraccion_limpia=0.95, eeg_canales_malos=1, eeg_edad_meses=23.6, eeg_con_sueno=1))
|
||||
sesion.add_all([
|
||||
EegCriterio(cri_id="c-1", cri_eeg_id="e-1", cri_codigo="clean-windows", cri_valor=95.0, cri_unidad="%",
|
||||
cri_bajo=60.0, cri_decisivo=1, cri_anormal=0),
|
||||
EegCriterio(cri_id="c-2", cri_eeg_id="e-1", cri_codigo="triage-level", cri_valor_texto="completo",
|
||||
cri_decisivo=1, cri_anormal=0),
|
||||
EegCriterio(cri_id="c-3", cri_eeg_id="e-1", cri_codigo="dead-channel", cri_electrodo="T3",
|
||||
cri_valor_texto="dead channel", cri_decisivo=0, cri_anormal=1),
|
||||
])
|
||||
sesion.add_all([
|
||||
EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=1.2, met_fuera=0,
|
||||
met_p5=5.0, met_mediana=6.0, met_p95=7.0, met_modelo="tea-eeg-posterior-rhythm/3"),
|
||||
EegMetrica(met_id="n2", met_eeg_id="e-1", met_codigo="HUSOS_SUENO_N2", met_valor=2.5),
|
||||
EegMetricaElectrodo(mel_id="n2-fz", mel_met_id="n2", mel_electrodo="Fz", mel_valor=1.4, mel_z=-0.4),
|
||||
])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def loaded(tmp_path_factory):
|
||||
"""The database after the cycle's load and event models, with dbt's views created."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
|
||||
from conftest import base_de
|
||||
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea_eeg"), datos=_rows)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def _observations(base, clase: str) -> dict:
|
||||
from core.tea.indicadores.models import Observacion, Procedimiento
|
||||
|
||||
with Session(base.motor) as sesion:
|
||||
rows = sesion.exec(select(Procedimiento.codigo_fuente, Observacion).join(
|
||||
Observacion, Observacion.procedimiento_id == Procedimiento.procedimiento_id).where(
|
||||
Procedimiento.estudio_id == "eeg", Procedimiento.clase == clase)).all()
|
||||
return {(fuente, o.resultado_id): o.valor_numerico if o.valor_texto is None else o.valor_texto
|
||||
for fuente, o in rows}
|
||||
|
||||
|
||||
def test_the_verdict_and_study_checks_are_results_of_the_recording(loaded):
|
||||
"""Pins down: the EEG's verdict, triage level and each study-wide check (value, limit, out of range or not) are
|
||||
observations of its recording, under `eeg.calidad_<check>` in snake case; a check without a limit of that side
|
||||
gives none.
|
||||
|
||||
Fails if the silver mapping drops the verdict, stops turning check codes into catalog results, or the catalog
|
||||
loses one of them (the load skips a result the catalog doesn't have).
|
||||
"""
|
||||
toma = _observations(loaded, "toma")
|
||||
assert toma[None, "eeg.valido"] == 1 and toma[None, "eeg.nivel"] == "completo"
|
||||
assert (toma[None, "eeg.calidad_clean_windows"], toma[None, "eeg.calidad_clean_windows_bajo"],
|
||||
toma[None, "eeg.calidad_clean_windows_anormal"]) == (95.0, 60.0, 0)
|
||||
assert toma[None, "eeg.calidad_triage_level"] == "completo"
|
||||
assert (None, "eeg.calidad_clean_windows_alto") not in toma
|
||||
|
||||
|
||||
def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded):
|
||||
"""Pins down: a bad channel is a part of its EEG at its electrode with the analysis's reason; a metric's value at
|
||||
an electrode is a part with the value and its z.
|
||||
|
||||
Fails if the channel checks stop being parts, or the electrode z stops reaching silver.
|
||||
"""
|
||||
partes = _observations(loaded, "parte")
|
||||
assert partes["T3", "eeg.calidad_dead_channel"] == "dead channel"
|
||||
assert (partes["Fz", "eeg.husos_sueno_n2"], partes["Fz", "eeg.husos_sueno_n2_z"]) == (1.4, -0.4)
|
||||
|
||||
|
||||
def test_a_metric_carries_its_deviation_from_the_baseline(loaded):
|
||||
"""Pins down: a metric's z, -1/0/+1, the baseline's p5/median/p95 at the age and the baseline's registered label
|
||||
are results of the recording.
|
||||
|
||||
Fails if the silver mapping or the catalog drops one of the deviation's results or the label (the load skips a
|
||||
result the catalog doesn't have).
|
||||
"""
|
||||
toma = _observations(loaded, "toma")
|
||||
assert [toma[None, f"eeg.ritmo_posterior{s}"]
|
||||
for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95", "_modelo")] == \
|
||||
[6.8, 1.2, 0, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3"]
|
||||
|
||||
|
||||
def test_the_quality_view_lists_each_check_with_its_label(loaded):
|
||||
"""Pins down: `tea_paciente_eeg_criterios` has one row per check of the EEG, study-wide ones without an electrode
|
||||
and with their limit and decisive flag, the bad channel at its electrode as out of range and not decisive, each with the catalog's label; and the
|
||||
electrodes view keeps only metric values, not channel checks.
|
||||
|
||||
Fails if the view stops pivoting a check's observations, misses the channel parts, or the electrodes view starts
|
||||
reading the checks' parts as metrics.
|
||||
"""
|
||||
with loaded.motor.connect() as connection:
|
||||
rows = connection.execute(text(
|
||||
"select criterio, electrodo, valor, valor_texto, bajo, anormal, decisivo, etiqueta "
|
||||
"from tea_paciente_eeg_criterios "
|
||||
"order by criterio")).all()
|
||||
electrodes = connection.execute(text("select metrica, electrodo from tea_paciente_eeg_electrodos")).all()
|
||||
by_check = {r.criterio: r for r in rows}
|
||||
assert set(by_check) == {"clean_windows", "triage_level", "dead_channel"}
|
||||
assert (by_check["clean_windows"].valor, by_check["clean_windows"].bajo, by_check["clean_windows"].anormal,
|
||||
by_check["clean_windows"].decisivo) == (95.0, 60.0, 0, 1)
|
||||
assert (by_check["dead_channel"].electrodo, by_check["dead_channel"].anormal, by_check["dead_channel"].decisivo) == \
|
||||
("T3", 1, 0)
|
||||
assert by_check["clean_windows"].etiqueta == "Ventanas limpias"
|
||||
assert [tuple(e) for e in electrodes] == [("husos_sueno_n2", "Fz")]
|
||||
|
||||
|
||||
def test_a_metric_is_scored_by_the_analysis_s_deviation(loaded):
|
||||
"""Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state, the baseline's
|
||||
p5/median/p95 as the reference and the baseline's registered label; a metric without a z (no baseline in
|
||||
production) can't be evaluated. And the electrodes view carries each electrode's z next to its value.
|
||||
|
||||
Fails if dbt goes back to scoring metrics against fixed ranges of its own, drops the baseline label, or drops the
|
||||
electrode z.
|
||||
"""
|
||||
with loaded.motor.connect() as connection:
|
||||
metrics = {r.metrica: r for r in connection.execute(text(
|
||||
"select metrica, valor, ref_min, ref_mediana, ref_max, modelo, valor_z, estado "
|
||||
"from tea_paciente_eeg_metricas"))}
|
||||
(electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all()
|
||||
rhythm = metrics["ritmo_posterior"]
|
||||
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.modelo, rhythm.valor_z,
|
||||
rhythm.estado) == (6.8, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3", 1.2, "normal")
|
||||
assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
|
||||
assert tuple(electrode) == (1.4, -0.4)
|
||||
@@ -19,7 +19,7 @@ from sqlmodel import select
|
||||
|
||||
import staging.tea as fixture
|
||||
from conftest import base_de
|
||||
from core.tea.models import Ados2, Eeg, EegMetrica, Mchat
|
||||
from core.tea.models import Ados2, Eeg, EegCriterio, EegMetrica, Mchat
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
@@ -219,7 +219,7 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
|
||||
def without_the_good_eeg(session):
|
||||
fixture.insertar(session)
|
||||
session.flush()
|
||||
for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")):
|
||||
for model, key in ((EegMetrica, "met_eeg_id"), (EegCriterio, "cri_eeg_id"), (Eeg, "eeg_id")):
|
||||
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
|
||||
session.delete(row)
|
||||
|
||||
@@ -231,8 +231,7 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1,
|
||||
eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0,
|
||||
eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0,
|
||||
eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=1, eeg_nivel="completo",
|
||||
eeg_ruido_linea_db=3.5))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
|
||||
@@ -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()}
|
||||
@@ -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"
|
||||
@@ -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
|
||||
+43
-11
@@ -1,4 +1,5 @@
|
||||
import datetime as _dt
|
||||
import logging
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
@@ -10,7 +11,10 @@ from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.reports import reports_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint, in_dev
|
||||
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
|
||||
from webapi.cama_recurrence.routes import cama_recurrence_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
@@ -31,6 +35,9 @@ class IsoJSONProvider(DefaultJSONProvider):
|
||||
def create_app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.json = IsoJSONProvider(app)
|
||||
from webapi.cama_runtime import configure_cama_cohort
|
||||
|
||||
configure_cama_cohort(app)
|
||||
# File sources travel inside the request; cap them per request.
|
||||
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
|
||||
|
||||
@@ -84,18 +91,43 @@ def create_app() -> Flask:
|
||||
for domain in ("cacu", "cama", "tea"):
|
||||
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
|
||||
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
|
||||
# The same measures in FHIR R4, and TEA's patients only in DEV (simulated data).
|
||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=in_dev()),
|
||||
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
||||
url_prefix=f"/{domain}/fhir")
|
||||
# Patient-level follow-up list and individual risk: only in DEV, with simulated data.
|
||||
if in_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
# 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
|
||||
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
from persistance import cacu as cacu_repositories
|
||||
from webapi.model_analysis import model_analysis_blueprint, recurrence_blueprint
|
||||
from webapi.risk_batches import risk_batches_blueprint
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
||||
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
||||
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
|
||||
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama")
|
||||
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
|
||||
app.register_blueprint(recurrence_blueprint(), url_prefix="/cama")
|
||||
|
||||
if os.environ.get("WEBAPI_PRECALENTAR_MODELOS") == "1":
|
||||
_warm_in_background()
|
||||
return app
|
||||
|
||||
|
||||
def _warm_in_background() -> None:
|
||||
"""Loads the live models' members in each worker as it starts, so the first patient opened doesn't wait for them."""
|
||||
import threading
|
||||
|
||||
from webapi.model_analysis import LIVE_SCENARIOS, warm
|
||||
|
||||
def run():
|
||||
for domain in LIVE_SCENARIOS:
|
||||
try:
|
||||
warm(domain)
|
||||
except Exception: # the request that needs them will try again and say why
|
||||
logging.getLogger(__name__).exception("no se pudieron precargar los modelos de %s", domain)
|
||||
|
||||
threading.Thread(target=run, name="precarga-modelos", daemon=True).start()
|
||||
|
||||
+445
-15
@@ -1,20 +1,42 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, and the OCR extraction jobs with their manual review queue.
|
||||
their training and promotion, notebooks run on a cohort build, and the OCR
|
||||
extraction jobs with their manual review queue.
|
||||
|
||||
Versions and artifacts live in MLflow (`models.io.registry`); training runs
|
||||
elsewhere and registers its result through `POST /model-versions`, naming
|
||||
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
|
||||
Versions and artifacts live in MLflow (`models.io.registry`). Training can
|
||||
either run elsewhere and register its result through `POST /model-versions`
|
||||
(naming the indicator kit cohort build it was trained on,
|
||||
`cohorte_armado_id`), or be triggered in place through `POST
|
||||
/model-versions/<domain>/<scenario>/train`, for a deployment with no
|
||||
command-line access to run the `entrenar` compose profile by hand.
|
||||
Notebooks (`models.reports.experiment`) run in the background on the build's
|
||||
file alone and are kept as MLflow runs.
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
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
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from models.io.lineage import DOMAINS
|
||||
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from models.io.storage import build_file, cohorts_root, exported_builds
|
||||
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
|
||||
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__)
|
||||
|
||||
@@ -40,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 ----------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -72,6 +211,83 @@ def register_model_version():
|
||||
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/train")
|
||||
def train_model_version(domain: str, scenario: str):
|
||||
"""Exports the scenario's latest dbt cohort build, trains a PROD version on it unless one from the same file,
|
||||
code and environment already exists, and tries to promote it: the same one-shot pipeline the `entrenar`
|
||||
compose profile runs (`models run <domain> <scenario> --export --source dbt --environment prod --train
|
||||
--promote`), over HTTP instead of a shell. 503 with no dbt manifest configured; 404 for a domain/scenario with
|
||||
no trainer or whose cohort isn't exportable yet; 409 with the training's own version trained but not promoted
|
||||
(it's missing its validation reports: attach them, then `/promote`)."""
|
||||
from models.__main__ import main as models_main
|
||||
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
if not manifest:
|
||||
return jsonify({"error": "No hay un manifest de dbt configurado."}), 503
|
||||
argv = ["run", domain, scenario, "--export", "--source", "dbt", "--manifest", manifest, "--environment", "prod",
|
||||
"--train", "--promote"]
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
try:
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = models_main(argv)
|
||||
except SystemExit as exit:
|
||||
code = exit.code if isinstance(exit.code, int) else 1
|
||||
output, error = out.getvalue().strip(), err.getvalue().strip()
|
||||
if code == 0:
|
||||
return jsonify({"output": output})
|
||||
status = 404 if "no such model" in error else 409 if "not promoted, missing" in error else 503
|
||||
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."""
|
||||
@@ -108,19 +324,123 @@ def retire_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/artifacts/<path:path>")
|
||||
def download_artifact(domain: str, scenario: str, version: str, path: str):
|
||||
"""ML-01b: one file the version's training run stored; a folder (the saved model) as a zip."""
|
||||
name, data = registry.artifact(domain, scenario, version, path)
|
||||
return _download(name, data)
|
||||
|
||||
|
||||
# -- notebooks -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def submit(job, *args):
|
||||
"""Runs a notebook in the background, one at a time per worker by default (`WEBAPI_NOTEBOOK_WORKERS`)."""
|
||||
return _notebooks.submit(job, *args)
|
||||
|
||||
|
||||
_notebooks = ThreadPoolExecutor(max_workers=int(os.environ.get("WEBAPI_NOTEBOOK_WORKERS", "1")), thread_name_prefix="notebook")
|
||||
|
||||
|
||||
def _cohorts_root(domain: str) -> Path:
|
||||
if domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
return cohorts_root(getattr(settings, f"{domain}_database_url"))
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-files")
|
||||
def list_cohort_files():
|
||||
"""`?domain=`: the domain's cohort builds that have their file, the data a notebook can run on."""
|
||||
domain = request.args.get("domain", "")
|
||||
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."""
|
||||
return jsonify({"experiments": experiment.experiments(request.args.get("domain") or None,
|
||||
request.args.get("scenario") or None)})
|
||||
|
||||
|
||||
@governance_bp.post("/experiments")
|
||||
def run_experiment():
|
||||
"""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")
|
||||
if upload is None:
|
||||
return jsonify({"error": "falta file"}), 400
|
||||
kinds = [k.value for k in ArtifactKind]
|
||||
if request.form.get("kind") not in kinds:
|
||||
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
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 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:
|
||||
return jsonify({"error": f"la cohorte {url!r} no es del dominio {domain!r}"}), 400
|
||||
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"]))
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
@governance_bp.get("/experiments/<run_id>")
|
||||
def get_experiment(run_id: str):
|
||||
return jsonify(experiment.describe(run_id))
|
||||
|
||||
|
||||
@governance_bp.get("/experiments/<run_id>/page")
|
||||
def experiment_page(run_id: str):
|
||||
"""The notebook's rendered page. It's served sandboxed, as an origin of its own, since its scripts are the
|
||||
notebook's."""
|
||||
page = experiment.page(run_id)
|
||||
if page is None:
|
||||
return jsonify({"error": "el notebook todavía no tiene página"}), 404
|
||||
response = Response(page, mimetype="text/html")
|
||||
response.headers["Content-Security-Policy"] = "sandbox allow-scripts allow-popups"
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
return response
|
||||
|
||||
|
||||
@governance_bp.get("/experiments/<run_id>/artifacts/<path:path>")
|
||||
def download_experiment_artifact(run_id: str, path: str):
|
||||
name, data = experiment.artifact(run_id, path)
|
||||
return _download(name, data)
|
||||
|
||||
|
||||
def _download(name: str, data: bytes):
|
||||
response = Response(data, mimetype="application/octet-stream")
|
||||
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{quote(name)}"
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
return response
|
||||
|
||||
|
||||
# -- OCR ---------------------------------------------------------------------------------
|
||||
@@ -248,6 +568,72 @@ 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
|
||||
`limit` EEGs (5 by default), or every EEG with an EDF again with `all`. Larger batches are the indicator cycle's
|
||||
or `python -m models tea analyze`'s. Rows already analysed with the current plan, modules and baselines are
|
||||
skipped, so repeated calls are safe (VAR-09)."""
|
||||
from models.eeg_analysis import analyze_pending
|
||||
from webapi.orchestration.eeg import CLUSTERS, cluster as configured_cluster
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
try:
|
||||
limit = int(body.get("limit", 5))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "limit must be a whole number"}), 400
|
||||
if limit < 1:
|
||||
return jsonify({"error": "limit must be at least 1"}), 400
|
||||
cluster = body.get("cluster") or configured_cluster()
|
||||
if cluster not in CLUSTERS:
|
||||
return jsonify({"error": f"cluster must be one of {', '.join(CLUSTERS)}"}), 400
|
||||
summary = analyze_pending(everything=bool(body.get("all")), limit=limit, cluster=cluster)
|
||||
return jsonify(asdict(summary))
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/run")
|
||||
def run_ocr():
|
||||
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
|
||||
@@ -279,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())
|
||||
|
||||
@@ -4,6 +4,7 @@ import json
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
@@ -11,13 +12,19 @@ from webapi.imports import audit as import_audit
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
from webapi.orchestration.reference.catalogs import CatalogoInvalido
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
|
||||
from webapi.imports.mapping.derived import CASES, DERIVATIONS
|
||||
from webapi.imports.services.import_service import (
|
||||
DatabaseRefused,
|
||||
ImportRequestError,
|
||||
ImportSource,
|
||||
commit_sources,
|
||||
document_columns_preview,
|
||||
mapped_sample,
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
@@ -27,6 +34,7 @@ from webapi.imports.services.introspection_service import (
|
||||
document_report,
|
||||
extract_pdf_regions,
|
||||
preview_with_suggestions,
|
||||
suggest_mapping,
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
@@ -250,12 +258,17 @@ def pdf_regions_extract():
|
||||
def document_extract():
|
||||
"""Reads the documents, splits them into patient records and extracts
|
||||
the target's fields: `{files: [{name, file_base64}], target,
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?,
|
||||
include_pattern?, exclude_pattern?}`. `files` may be `sql` instead (a
|
||||
connection plus `table`/`query` and `DocumentColumns`' options), or the
|
||||
whole body may be `{source}`, an import source with `documents`.
|
||||
Each record comes back with per-field confidence and evidence, conflicts
|
||||
between sources, and the images found on its pages."""
|
||||
body = _json_body()
|
||||
if body.get("source"):
|
||||
return jsonify(document_report(body))
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
if not body.get("files") and not body.get("sql"):
|
||||
raise BadRequest("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
@@ -279,6 +292,32 @@ def document_page_image():
|
||||
# -- validate and load -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.get("/derivations")
|
||||
def derivations():
|
||||
"""The operations a source's `derived` fields may use, with their
|
||||
parameters, so a client can build the form for each."""
|
||||
return jsonify({"derivations": [cls.describe() for cls in DERIVATIONS.values()], "cases": list(CASES)})
|
||||
|
||||
|
||||
@imports_bp.post("/mapped-preview")
|
||||
def mapped_preview():
|
||||
"""`{source, limit?}`: the source's first rows as they would be
|
||||
written, with its mapping, derived fields and defaults applied."""
|
||||
body = _json_body()
|
||||
return jsonify({"rows": mapped_sample(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/columns")
|
||||
def document_columns_of_source():
|
||||
"""`{source, target?}` for a source with `documents`: its own columns
|
||||
plus every field and caption its documents print, as a preview the
|
||||
mapping screen offers like any table's, with suggestions."""
|
||||
body = _json_body()
|
||||
preview = document_columns_preview(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))
|
||||
target = body.get("target") or body["source"].get("target")
|
||||
return jsonify({**preview, "suggested_mapping": suggest_mapping([c["name"] for c in preview["columns"]], target)})
|
||||
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
source = _require(_json_body(), "source")
|
||||
@@ -302,6 +341,66 @@ def validate():
|
||||
)
|
||||
|
||||
|
||||
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
|
||||
"""For every source that asks for it (`catalog_fallback: true`) and
|
||||
reads documents, writes the captions no known field claimed but the
|
||||
project's catalog does know straight into the silver layer
|
||||
(`catalog_commit_service`). Best-effort: the structured fields already
|
||||
landed through `commit_sources`, so a failure here is reported, not
|
||||
raised."""
|
||||
reports = []
|
||||
for raw in raw_sources:
|
||||
if not isinstance(raw, dict) or raw.get("catalog_fallback") is not True:
|
||||
continue
|
||||
if raw.get("source_type") != "document" and not raw.get("documents"):
|
||||
continue
|
||||
target = raw.get("target") or ""
|
||||
domain = target.split(".", 1)[0]
|
||||
if not domain:
|
||||
continue
|
||||
payload = {**(raw.get("payload") or {}), "target": target}
|
||||
try:
|
||||
if raw.get("documents"):
|
||||
connector, _, _ = ImportSource.parse(raw).document_connector()
|
||||
if connector is None:
|
||||
continue
|
||||
else:
|
||||
connector = build_connector("document", payload)
|
||||
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
|
||||
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError, ImportRequestError) as exc:
|
||||
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
|
||||
continue
|
||||
reports.append(
|
||||
{
|
||||
"label": raw.get("label"),
|
||||
"domain": result.proyecto,
|
||||
"records_written": result.records_written,
|
||||
"records_without_patient": result.records_without_patient,
|
||||
"fields_matched": result.fields_matched,
|
||||
"fields_minted": result.fields_minted,
|
||||
"fields_unmatched": result.fields_unmatched,
|
||||
}
|
||||
)
|
||||
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}`.
|
||||
@@ -322,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
|
||||
@@ -333,6 +433,7 @@ def commit():
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": recalculating,
|
||||
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"""CaMa's descriptive analysis (`/cama/analisis`): counts and proportions of the BI-RADS cohort, never survival or risk.
|
||||
|
||||
stats.py Wilson intervals, the chi-square test of homogeneity, quantiles
|
||||
suppression.py the rule for small groups, with the complementary suppression that keeps a difference from giving them away
|
||||
calculations.py the cohort's figures, pure functions over its rows
|
||||
service.py the selection, the calculation and the common header of every answer
|
||||
routes.py the routes
|
||||
"""
|
||||
|
||||
# Compatibility for callers that explicitly mount the previous blueprints.
|
||||
# create_app registers only the L1-L3 routes.
|
||||
from webapi.cama_analysis_legacy import analysis, revision_of, SelectionError, selection_response
|
||||
@@ -0,0 +1,187 @@
|
||||
"""The descriptive analysis of the BI-RADS cohort: pure functions over the cohort's rows.
|
||||
|
||||
Every figure is a count or a proportion of patients of the selection, with the denominator it is a proportion of named in
|
||||
the answer. Nothing here is an incidence, a survival or a risk: the cohort is the patients whose latest reported
|
||||
mammogram is BI-RADS 4 to 6, not a population at risk followed over time.
|
||||
|
||||
Definitions (working conventions, for review):
|
||||
result the grade of the biopsy the list shows (the latest report at the cut-off); `SIN_BIOPSIA` when none,
|
||||
`SIN_DATO` for a report without a grade.
|
||||
known a result that is one of the catalog's grades (benign, in situ, invasive).
|
||||
malignant a grade in `cama.biopsia_cancer` (in situ or invasive); invasive is `CARCINOMA_INVASOR`.
|
||||
horizon `h` days from the mammogram's date. A mammogram counts for a horizon only when `h` days have passed by the
|
||||
cut-off, so a recent mammogram isn't read as one without a biopsy.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from webapi.cama_analysis.stats import cuantil, chi2_homogeneidad, wilson
|
||||
from webapi.cama_analysis.suppression import proporcion_publicable, suprimir_categorias, suprimir_tabla
|
||||
from webapi.cama_follow_up.cohort import SIN_BIOPSIA, SIN_DATO, Fila
|
||||
|
||||
GRADOS_CONOCIDOS = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
|
||||
INVASOR = "CARCINOMA_INVASOR"
|
||||
HORIZONTES = (30, 90, 180, 365)
|
||||
MEDIDAS = ("maligno", "invasor")
|
||||
|
||||
|
||||
def pct(x: float) -> float:
|
||||
return round(100 * x, 2)
|
||||
|
||||
|
||||
def valor_de(f: Fila, dimension: str) -> str:
|
||||
return f.resultado if dimension == "biopsia" else getattr(f, dimension)
|
||||
|
||||
|
||||
def es_conocido(f: Fila) -> bool:
|
||||
return f.biopsia in GRADOS_CONOCIDOS
|
||||
|
||||
|
||||
def es_caso(f: Fila, medida: str, malignos: set[str]) -> bool:
|
||||
return f.biopsia == INVASOR if medida == "invasor" else f.biopsia in malignos
|
||||
|
||||
|
||||
def proporcion(casos: int, total: int, umbral: int) -> dict:
|
||||
"""A proportion with its Wilson interval, or the reason it isn't published."""
|
||||
if total == 0:
|
||||
return {"estado": "sin_datos", "casos": None, "total": 0, "valor": None, "ic_bajo": None, "ic_alto": None}
|
||||
if not proporcion_publicable(casos, total, umbral):
|
||||
return {"estado": "suprimido", "casos": None, "total": None, "valor": None, "ic_bajo": None, "ic_alto": None}
|
||||
bajo, alto = wilson(casos, total)
|
||||
return {"estado": "disponible", "casos": casos, "total": total, "valor": pct(casos / total),
|
||||
"ic_bajo": pct(bajo), "ic_alto": pct(alto)}
|
||||
|
||||
|
||||
def distribucion(filas: list[Fila], por: str, categorias: list[tuple[str, str]], umbral: int) -> dict:
|
||||
"""Patients of the selection by one dimension: count, share and its Wilson interval, and the key to open them."""
|
||||
conteos = {c: 0 for c, _ in categorias}
|
||||
for f in filas:
|
||||
conteos[valor_de(f, por)] = conteos.get(valor_de(f, por), 0) + 1
|
||||
ocultas = suprimir_categorias(conteos, umbral)
|
||||
total = len(filas)
|
||||
items = []
|
||||
for codigo, etiqueta in categorias:
|
||||
n = conteos[codigo]
|
||||
item = {"codigo": codigo, "etiqueta": etiqueta, "suprimido": codigo in ocultas, "n": None, "porcentaje": None,
|
||||
"ic_bajo": None, "ic_alto": None, "seleccion": {por: codigo}}
|
||||
if codigo not in ocultas:
|
||||
item["n"] = n
|
||||
if total:
|
||||
bajo, alto = wilson(n, total)
|
||||
item.update(porcentaje=pct(n / total), ic_bajo=pct(bajo), ic_alto=pct(alto))
|
||||
items.append(item)
|
||||
return {"por": por, "total": total, "items": items}
|
||||
|
||||
|
||||
def comparacion(filas: list[Fila], por: str, categorias: list[tuple[str, str]], medida: str, malignos: set[str],
|
||||
umbral: int) -> dict:
|
||||
"""The share of cases among the patients with a known biopsy result, by group, and the test that groups differ."""
|
||||
grupos, publicados = [], []
|
||||
for codigo, etiqueta in categorias:
|
||||
del_grupo = [f for f in filas if valor_de(f, por) == codigo]
|
||||
conocidos = [f for f in del_grupo if es_conocido(f)]
|
||||
casos = sum(es_caso(f, medida, malignos) for f in conocidos)
|
||||
resultado = proporcion(casos, len(conocidos), umbral)
|
||||
resultado.update(codigo=codigo, etiqueta=etiqueta, seleccion={por: codigo})
|
||||
grupos.append(resultado)
|
||||
if resultado["estado"] == "disponible":
|
||||
publicados.append((casos, len(conocidos)))
|
||||
prueba = chi2_homogeneidad(publicados)
|
||||
prueba["nombre"] = "Chi cuadrada de homogeneidad"
|
||||
return {"por": por, "medida": medida, "denominador": "pacientes con resultado de biopsia conocido", "grupos": grupos,
|
||||
"prueba": prueba}
|
||||
|
||||
|
||||
def mapa(filas: list[Fila], por_filas: str, por_columnas: str, cats_f: list[tuple[str, str]], cats_c: list[tuple[str, str]],
|
||||
medida: str, malignos: set[str], umbral: int) -> dict:
|
||||
"""Two dimensions crossed: patients per cell and, among those with a known result, the share of cases."""
|
||||
conteos = {(f, c): 0 for f, _ in cats_f for c, _ in cats_c}
|
||||
for f in filas:
|
||||
llave = (valor_de(f, por_filas), valor_de(f, por_columnas))
|
||||
if llave in conteos:
|
||||
conteos[llave] += 1
|
||||
ocultas = suprimir_tabla(conteos, umbral)
|
||||
celdas = []
|
||||
for (fc, fe), (cc, ce) in ((f, c) for f in cats_f for c in cats_c):
|
||||
del_grupo = [f for f in filas if valor_de(f, por_filas) == fc and valor_de(f, por_columnas) == cc]
|
||||
conocidos = [f for f in del_grupo if es_conocido(f)]
|
||||
n = conteos[(fc, cc)]
|
||||
celda = {"fila": fc, "columna": cc, "suprimido": (fc, cc) in ocultas, "n": None if (fc, cc) in ocultas else n,
|
||||
"seleccion": {por_filas: fc, por_columnas: cc}}
|
||||
celda["resultado"] = (proporcion(sum(es_caso(f, medida, malignos) for f in conocidos), len(conocidos), umbral)
|
||||
if (fc, cc) not in ocultas else {"estado": "suprimido", "casos": None, "total": None, "valor": None,
|
||||
"ic_bajo": None, "ic_alto": None})
|
||||
celdas.append(celda)
|
||||
return {"filas": {"por": por_filas, "categorias": [{"codigo": c, "etiqueta": e} for c, e in cats_f]},
|
||||
"columnas": {"por": por_columnas, "categorias": [{"codigo": c, "etiqueta": e} for c, e in cats_c]},
|
||||
"medida": medida, "celdas": celdas}
|
||||
|
||||
|
||||
def resumen(filas: list[Fila], corte: date, horizonte: int, malignos: set[str], umbral: int) -> list[dict]:
|
||||
"""The indicator cards of the selection, each with its numerator, denominator, interval and state."""
|
||||
def tarjeta(clave, titulo, descripcion, unidad="%", **datos):
|
||||
return {"clave": clave, "titulo": titulo, "descripcion": descripcion, "unidad": unidad, "estado": "disponible",
|
||||
"valor": None, "ic_bajo": None, "ic_alto": None, "n": None, "denominador": None, "q1": None, "q3": None,
|
||||
"motivo": None, **datos}
|
||||
|
||||
def de_proporcion(clave, titulo, descripcion, casos, total):
|
||||
p = proporcion(casos, total, umbral)
|
||||
return tarjeta(clave, titulo, descripcion, estado=p["estado"], valor=p["valor"], ic_bajo=p["ic_bajo"],
|
||||
ic_alto=p["ic_alto"], n=p["casos"], denominador=p["total"])
|
||||
|
||||
total = len(filas)
|
||||
con_biopsia = [f for f in filas if f.primera_biopsia_fecha is not None]
|
||||
conocidos = [f for f in filas if es_conocido(f)]
|
||||
tarjetas = [
|
||||
tarjeta("cohorte", "Pacientes en la cohorte BI-RADS 4 a 6",
|
||||
"Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "pacientes",
|
||||
valor=total, n=total),
|
||||
de_proporcion("con_biopsia", "Con biopsia reportada",
|
||||
"Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.",
|
||||
len(con_biopsia), total),
|
||||
de_proporcion("maligno_conocido", "Resultado maligno entre las biopsias con resultado",
|
||||
"Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. "
|
||||
"No es incidencia: el denominador son pacientes ya biopsiadas.",
|
||||
sum(es_caso(f, "maligno", malignos) for f in conocidos), len(conocidos)),
|
||||
de_proporcion("invasor_conocido", "Carcinoma invasor entre las biopsias con resultado",
|
||||
"Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.",
|
||||
sum(es_caso(f, "invasor", malignos) for f in conocidos), len(conocidos)),
|
||||
]
|
||||
maduras = [f for f in filas if (corte - f.mastografia_fecha).days >= horizonte]
|
||||
en = lambda fecha_, f: fecha_ is not None and (fecha_ - f.mastografia_fecha).days <= horizonte # noqa: E731
|
||||
tarjetas += [
|
||||
de_proporcion(f"biopsia_{horizonte}d", f"Biopsia reportada en {horizonte} días",
|
||||
f"Pacientes cuya biopsia se reportó dentro de {horizonte} días de la mastografía, entre las que ya "
|
||||
f"cumplieron {horizonte} días al corte.", sum(en(f.primera_biopsia_fecha, f) for f in maduras), len(maduras)),
|
||||
de_proporcion(f"maligno_{horizonte}d", f"Cáncer confirmado en {horizonte} días",
|
||||
f"Pacientes con un reporte de biopsia maligna dentro de {horizonte} días de la mastografía, entre las que "
|
||||
f"ya cumplieron {horizonte} días al corte. No es incidencia acumulada: no hay seguimiento de quien no "
|
||||
"tuvo biopsia.", sum(en(f.primer_maligno_fecha, f) for f in maduras), len(maduras)),
|
||||
]
|
||||
dias = [(f.primera_biopsia_fecha - f.mastografia_fecha).days for f in con_biopsia]
|
||||
if len(dias) >= umbral:
|
||||
tarjetas.append(tarjeta("dias_a_biopsia", "Días de la mastografía al reporte de biopsia",
|
||||
"Mediana y cuartiles entre las pacientes con biopsia reportada.", "días",
|
||||
valor=cuantil(dias, .5), q1=cuantil(dias, .25), q3=cuantil(dias, .75), n=len(dias)))
|
||||
else:
|
||||
tarjetas.append(tarjeta("dias_a_biopsia", "Días de la mastografía al reporte de biopsia",
|
||||
"Mediana y cuartiles entre las pacientes con biopsia reportada.", "días",
|
||||
estado="suprimido" if dias else "sin_datos"))
|
||||
return tarjetas
|
||||
|
||||
|
||||
NO_DISPONIBLES = [
|
||||
{"clave": "supervivencia", "titulo": "Supervivencia",
|
||||
"motivo": "No hay estado vital ni fecha de defunción en las fuentes."},
|
||||
{"clave": "recaida", "titulo": "Recaída",
|
||||
"motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."},
|
||||
{"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento",
|
||||
"motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."},
|
||||
{"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia",
|
||||
"motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero "
|
||||
"común, y la muerte como riesgo competitivo no existe."},
|
||||
{"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido",
|
||||
"motivo": "Dependen de las curvas anteriores."},
|
||||
{"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral",
|
||||
"motivo": "No hay registros de estas variables en las fuentes."},
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""The routes of CaMa's descriptive analysis, under `/cama/analisis`.
|
||||
|
||||
GET /cama/analisis what the analysis offers: dimensions, measures, horizons and what isn't available
|
||||
GET /cama/analisis/resumen the indicator cards of the selection
|
||||
GET /cama/analisis/distribucion patients by BI-RADS, age group or biopsy result
|
||||
GET /cama/analisis/comparacion the share of cases among biopsied patients, by BI-RADS or age group, and its test
|
||||
GET /cama/analisis/mapa BI-RADS by age group
|
||||
GET /cama/analisis/tendencia reports of mammogram and biopsy per month or semester (activity; takes only the cut-off)
|
||||
GET /cama/analisis/indicadores patients of the cohort by BI-RADS category (the aggregate the tab has always read)
|
||||
|
||||
The selection (cut-off, window, filters) is the follow-up list's, with its suppression, its revision and its errors.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, current_app, jsonify, request
|
||||
from sqlmodel import Session
|
||||
from werkzeug.datastructures import MultiDict
|
||||
|
||||
from webapi.cama_analysis import service
|
||||
from webapi.cama_follow_up.access import configured_access
|
||||
from webapi.cama_follow_up.cohort import CohorteNoDisponible
|
||||
from webapi.cama_follow_up.listing import GrupoPequeno, PedidoInvalido, RevisionDistinta
|
||||
from webapi.cama_follow_up.routes import CONTEXTO, FILTROS, _requested
|
||||
|
||||
COMUNES = ("corte", "meses", *CONTEXTO, *FILTROS)
|
||||
ENTEROS = {"horizonte": "horizonte", "periodos": "periodos"}
|
||||
TEXTOS = {"por": "por", "medida": "medida", "tipo": "tipo", "filas": "filas_por", "columnas": "columnas_por"}
|
||||
|
||||
|
||||
def analysis_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""The blueprint of the analysis, to register with `url_prefix="/cama/analisis"`."""
|
||||
blueprint = Blueprint("cama_analisis", __name__)
|
||||
blueprint.before_request(configured_access)
|
||||
|
||||
@blueprint.after_request
|
||||
def no_store(response):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
def answer(build, propios: tuple[str, ...], comunes: tuple[str, ...]):
|
||||
reader = current_app.config.get('CAMA_COHORT_READER')
|
||||
if build is service.indicadores and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
|
||||
from webapi.cama_analysis_legacy import indicators
|
||||
return indicators()
|
||||
try:
|
||||
pedido = _pedido(request.args, propios, comunes)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = build(sesion, **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except GrupoPequeno as error:
|
||||
return jsonify({"error": str(error), "motivo": "supresion"}), 403
|
||||
except RevisionDistinta as error:
|
||||
return jsonify({"error": str(error), "motivo": "revision"}), 409
|
||||
except CohorteNoDisponible as error:
|
||||
return jsonify({"error": str(error), "motivo": "cohorte"}), 503
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
routes = {
|
||||
"": (service.catalogo, ()), "/resumen": (service.resumen, ("horizonte",)),
|
||||
"/distribucion": (service.distribucion, ("por",)), "/comparacion": (service.comparacion, ("por", "medida")),
|
||||
"/mapa": (service.mapa, ("filas", "columnas", "medida")), "/tendencia": (service.tendencia, ("tipo", "periodos"), ("corte",)),
|
||||
"/indicadores": (service.indicadores, ()),
|
||||
}
|
||||
for ruta, (construye, propios, *resto) in routes.items():
|
||||
comunes = resto[0] if resto else COMUNES
|
||||
blueprint.add_url_rule(ruta, endpoint=ruta.strip("/") or "catalogo",
|
||||
view_func=(lambda c=construye, p=propios, k=comunes: answer(c, p, k)), methods=["GET"])
|
||||
return blueprint
|
||||
|
||||
|
||||
def _pedido(args, propios: tuple[str, ...], admitidos: tuple[str, ...] = COMUNES) -> dict:
|
||||
"""The request's parameters: the selection's (typed by the follow-up's own parser) and this route's.
|
||||
|
||||
A route that isn't about the cohort (the trend) admits only the cut-off: window, filters and context are refused.
|
||||
"""
|
||||
for nombre in args:
|
||||
if nombre not in (*admitidos, *propios):
|
||||
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos + propios)}.")
|
||||
comunes = MultiDict((k, v) for k, v in args.items(multi=True) if k in admitidos)
|
||||
base = _requested(comunes, admitidos)
|
||||
if admitidos == COMUNES:
|
||||
pedido = {"corte": base.get("corte"), "meses": base.get("meses"), "filtros": base.get("filtros", {}),
|
||||
"contexto": tuple(base.get(k) for k in CONTEXTO), "hoy": None}
|
||||
else:
|
||||
pedido = {"corte": base.get("corte"), "hoy": None}
|
||||
for nombre in propios:
|
||||
if len(args.getlist(nombre)) > 1:
|
||||
raise ValueError(f"parámetro repetido {nombre!r}.")
|
||||
if nombre in args:
|
||||
valor = args[nombre]
|
||||
if nombre in ENTEROS:
|
||||
if not re.fullmatch(r"\d{1,6}", valor):
|
||||
raise ValueError(f"{nombre} debe ser un entero; llegó {valor!r}")
|
||||
pedido[ENTEROS[nombre]] = int(valor)
|
||||
else:
|
||||
if not valor:
|
||||
raise ValueError(f"{nombre} no puede ir vacío.")
|
||||
pedido[TEXTOS[nombre]] = valor
|
||||
return pedido
|
||||
@@ -0,0 +1,202 @@
|
||||
"""The answers of the descriptive analysis: the selection of L1's cohort, the calculation and the common header.
|
||||
|
||||
Every answer names the cohort, scenario, revision and cut-off of the selection it describes, so a figure can open its
|
||||
patients in the follow-up list, and applies the same window, filters and suppression as that list.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.cama_analysis import calculations as calc
|
||||
from webapi.cama_analysis.suppression import suprimir_categorias
|
||||
from webapi.cama_follow_up.cohort import CANDIDATOS, SIN_DATO, CohorteNoDisponible, disponible
|
||||
from webapi.cama_follow_up.listing import PedidoInvalido, _consulta
|
||||
from webapi.orchestration.reference.rules import valor_de
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
DIMENSIONES = ("birads", "grupo_edad", "biopsia")
|
||||
TIPOS_PERIODO = ("mes", "semestre")
|
||||
PERIODOS_MAXIMOS = 36
|
||||
HORIZONTE_POR_OMISION = 90
|
||||
|
||||
|
||||
def _seleccion(sesion: Session, *, corte, meses, filtros, contexto, hoy):
|
||||
cabecera, filas = _consulta(sesion, corte=corte, meses=0 if meses is None else meses, filtros=filtros, contexto=contexto,
|
||||
hoy=hoy, page=1, page_size=1)
|
||||
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
|
||||
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
|
||||
opciones = {f["clave"]: [(o["codigo"], o["etiqueta"]) for o in f["opciones"]] for f in cabecera["filtros_disponibles"]}
|
||||
# The columns are the list's; the analysis announces its own dimensions instead.
|
||||
encabezado = {k: v for k, v in cabecera.items() if k not in ("columnas", "filtros_disponibles", "simulado")}
|
||||
encabezado["umbral_supresion"] = umbral
|
||||
return encabezado, filas, umbral, malignos, opciones
|
||||
|
||||
|
||||
def _dimension(valor: str | None, nombre: str = "por") -> str:
|
||||
if valor not in DIMENSIONES:
|
||||
raise PedidoInvalido(f"{nombre} = {valor!r}: se admite {list(DIMENSIONES)}.")
|
||||
return valor
|
||||
|
||||
|
||||
def _medida(valor: str | None) -> str:
|
||||
valor = valor or "maligno"
|
||||
if valor not in calc.MEDIDAS:
|
||||
raise PedidoInvalido(f"medida = {valor!r}: se admite {list(calc.MEDIDAS)}.")
|
||||
return valor
|
||||
|
||||
|
||||
def catalogo(sesion: Session, **seleccion) -> dict:
|
||||
encabezado, _, umbral, _, opciones = _seleccion(sesion, **seleccion)
|
||||
return {
|
||||
**encabezado,
|
||||
"dimensiones": [{"clave": c, "etiqueta": e, "opciones": [{"codigo": k, "etiqueta": v} for k, v in opciones[c]]}
|
||||
for c, e in (("birads", "Categoría BI-RADS"), ("grupo_edad", "Grupo de edad"), ("biopsia", "Resultado de la biopsia"))],
|
||||
"medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}],
|
||||
"horizontes_dias": list(calc.HORIZONTES), "tipos_periodo": list(TIPOS_PERIODO),
|
||||
"secciones": [{"clave": c, "titulo": t, "estado": "disponible", "motivo": None} for c, t in (
|
||||
("resumen", "Indicadores de la cohorte"), ("distribucion", "Distribución de pacientes"),
|
||||
("comparacion", "Comparación entre grupos"), ("mapa", "Mapa entre variables"), ("tendencia", "Tendencia en el tiempo"))],
|
||||
"no_disponibles": calc.NO_DISPONIBLES,
|
||||
}
|
||||
|
||||
|
||||
def resumen(sesion: Session, *, horizonte: int | None = None, **seleccion) -> dict:
|
||||
horizonte = HORIZONTE_POR_OMISION if horizonte is None else horizonte
|
||||
if horizonte not in calc.HORIZONTES:
|
||||
raise PedidoInvalido(f"horizonte = {horizonte!r}: se admite {list(calc.HORIZONTES)}.")
|
||||
encabezado, filas, umbral, malignos, _ = _seleccion(sesion, **seleccion)
|
||||
corte = date.fromisoformat(encabezado["corte"])
|
||||
return {**encabezado, "horizonte_dias": horizonte, "indicadores": calc.resumen(filas, corte, horizonte, malignos, umbral),
|
||||
"no_disponibles": calc.NO_DISPONIBLES}
|
||||
|
||||
|
||||
def distribucion(sesion: Session, *, por: str | None = None, **seleccion) -> dict:
|
||||
por = _dimension(por)
|
||||
encabezado, filas, umbral, _, opciones = _seleccion(sesion, **seleccion)
|
||||
return {**encabezado, **calc.distribucion(filas, por, opciones[por], umbral)}
|
||||
|
||||
|
||||
def comparacion(sesion: Session, *, por: str | None = None, medida: str | None = None, **seleccion) -> dict:
|
||||
por, medida = _dimension(por), _medida(medida)
|
||||
if por == "biopsia":
|
||||
raise PedidoInvalido("se compara por BI-RADS o por grupo de edad: el resultado de la biopsia es lo que se mide.")
|
||||
encabezado, filas, umbral, malignos, opciones = _seleccion(sesion, **seleccion)
|
||||
return {**encabezado, **calc.comparacion(filas, por, opciones[por], medida, malignos, umbral)}
|
||||
|
||||
|
||||
def mapa(sesion: Session, *, filas_por: str | None = None, columnas_por: str | None = None, medida: str | None = None, **seleccion) -> dict:
|
||||
filas_por, columnas_por, medida = _dimension(filas_por, "filas"), _dimension(columnas_por, "columnas"), _medida(medida)
|
||||
if filas_por == columnas_por:
|
||||
raise PedidoInvalido("las filas y las columnas deben ser dimensiones distintas.")
|
||||
if "biopsia" in (filas_por, columnas_por):
|
||||
raise PedidoInvalido("el mapa cruza BI-RADS y grupo de edad: el resultado de la biopsia es lo que se mide.")
|
||||
encabezado, filas, umbral, malignos, opciones = _seleccion(sesion, **seleccion)
|
||||
return {**encabezado, **calc.mapa(filas, filas_por, columnas_por, opciones[filas_por], opciones[columnas_por], medida, malignos, umbral)}
|
||||
|
||||
|
||||
def indicadores(sesion: Session, **seleccion) -> dict:
|
||||
"""The cohort's patients by BI-RADS category: the aggregate the analysis tab has always read."""
|
||||
encabezado, filas, umbral, _, opciones = _seleccion(sesion, **seleccion)
|
||||
d = calc.distribucion(filas, "birads", opciones["birads"], umbral)
|
||||
return {"simulado": True, "cohorte": encabezado["cohorte"], "revision": encabezado["revision"], "escenario": encabezado["escenario"],
|
||||
"corte": encabezado["corte"], "umbral_supresion": umbral, "unidad": "paciente",
|
||||
"denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6",
|
||||
# This contract publishes a category only from the threshold: an empty one is not published either.
|
||||
"grupos": [{"codigo": i["codigo"], "n": None if i["suprimido"] or not i["n"] else i["n"], "suprimido": i["suprimido"] or not i["n"]}
|
||||
for i in d["items"]],
|
||||
"horizonte_dias": 0, "indicadores": []}
|
||||
|
||||
|
||||
def _periodo(fecha: date, tipo: str) -> tuple[str, date, date]:
|
||||
if tipo == "mes":
|
||||
inicio = fecha.replace(day=1)
|
||||
fin = (date(inicio.year + (inicio.month == 12), inicio.month % 12 + 1, 1))
|
||||
return f"{inicio.year}-{inicio.month:02d}", inicio, fin
|
||||
semestre = 1 if fecha.month <= 6 else 2
|
||||
inicio = date(fecha.year, 1 if semestre == 1 else 7, 1)
|
||||
fin = date(fecha.year + (semestre == 2), 7 if semestre == 1 else 1, 1)
|
||||
return f"{fecha.year}-S{semestre}", inicio, fin
|
||||
|
||||
|
||||
def _periodos_hasta(corte: date, tipo: str, cuantos: int) -> list[tuple[str, date, date]]:
|
||||
periodos = []
|
||||
ref = corte
|
||||
for _ in range(cuantos):
|
||||
periodo = _periodo(ref, tipo)
|
||||
periodos.append(periodo)
|
||||
ref = periodo[1].fromordinal(periodo[1].toordinal() - 1)
|
||||
return periodos[::-1]
|
||||
|
||||
|
||||
POBLACION_TENDENCIA = ("Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, "
|
||||
"de todas las pacientes; no la cohorte de Seguimiento")
|
||||
ALCANCE_BIOPSIAS = ("Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); "
|
||||
"una biopsia sin mastografía ligada no se cuenta")
|
||||
|
||||
|
||||
def tendencia(sesion: Session, *, tipo: str | None = None, periodos: int | None = None, corte: date | None = None,
|
||||
hoy: date | None = None) -> dict:
|
||||
"""Mammogram reports and biopsy reports per period, and the share of malignant results among the graded biopsies.
|
||||
|
||||
It is activity, not the cohort: it counts reports (a mammogram's report with a BI-RADS, a biopsy's report linked to
|
||||
one of those mammograms) by the date of the report, over every patient. It takes no window and no filter of the
|
||||
cohort, and says so; the same cut-off, period type and number of periods always give the same answer. A report is
|
||||
one count however many reports a patient has, so the shares are of reports, not of patients, and carry no test:
|
||||
repeated reports of a patient aren't independent observations. A period's total is published from the suppression
|
||||
threshold; the categories of a period hide by complement (a hidden category takes the smallest published one with
|
||||
it), so the total gives none of them away. The period the cut-off falls in is flagged.
|
||||
"""
|
||||
tipo = tipo or "mes"
|
||||
if tipo not in TIPOS_PERIODO:
|
||||
raise PedidoInvalido(f"tipo = {tipo!r}: se admite {list(TIPOS_PERIODO)}.")
|
||||
periodos = (12 if tipo == "mes" else 6) if periodos is None else periodos
|
||||
if not 1 <= periodos <= PERIODOS_MAXIMOS:
|
||||
raise PedidoInvalido(f"periodos va de 1 a {PERIODOS_MAXIMOS}.")
|
||||
if not disponible(sesion):
|
||||
raise CohorteNoDisponible("la cohorte aún no está disponible: falta correr el ciclo de indicadores de CaMa")
|
||||
hoy = hoy or date.today()
|
||||
corte = hoy if corte is None else corte
|
||||
if corte > hoy:
|
||||
raise PedidoInvalido(f"corte {corte.isoformat()} es posterior a hoy ({hoy.isoformat()}).")
|
||||
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
|
||||
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
|
||||
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
|
||||
gravedad = {c: i for i, c in enumerate(valor_de(sesion, "cama.birads_gravedad", tablas=TABLAS))}
|
||||
c = CANDIDATOS.c
|
||||
filas = sesion.execute(select(CANDIDATOS).where(c.fecha_reporte <= corte)).mappings().all()
|
||||
mastografias: dict[int, tuple] = {}
|
||||
biopsias: dict[int, tuple] = {}
|
||||
for f in filas:
|
||||
previo = mastografias.get(f["reporte_id"])
|
||||
if previo is None or gravedad.get(f["birads"], -1) > gravedad.get(previo[1], -1):
|
||||
mastografias[f["reporte_id"]] = (f["fecha_reporte"], f["birads"])
|
||||
if f["biopsia_id"] is not None and f["biopsia_fecha_reporte"] <= corte:
|
||||
previa = biopsias.get(f["biopsia_id"])
|
||||
rango = calc.GRADOS_CONOCIDOS.index(f["biopsia_grado"]) if f["biopsia_grado"] in calc.GRADOS_CONOCIDOS else -1
|
||||
if previa is None or rango > previa[2]:
|
||||
biopsias[f["biopsia_id"]] = (f["biopsia_fecha_reporte"], f["biopsia_grado"], rango)
|
||||
salida = []
|
||||
for nombre, inicio, fin in _periodos_hasta(corte, tipo, periodos):
|
||||
ultimo_dia = fin.fromordinal(fin.toordinal() - 1)
|
||||
m = [b for fecha, b in mastografias.values() if inicio <= fecha < fin]
|
||||
b = [g for fecha, g, _ in biopsias.values() if inicio <= fecha < fin]
|
||||
mm = {"4_a_6": sum(x in admitidos for x in m), "otras": sum(x not in admitidos for x in m)}
|
||||
ocultas_m = suprimir_categorias(mm, umbral)
|
||||
grados = {g: sum(x == g for x in b) for g in calc.GRADOS_CONOCIDOS}
|
||||
grados[SIN_DATO] = sum(x not in calc.GRADOS_CONOCIDOS for x in b)
|
||||
ocultas_b = suprimir_categorias(grados, umbral)
|
||||
conocidos = sum(grados[g] for g in calc.GRADOS_CONOCIDOS)
|
||||
casos = sum(grados[g] for g in calc.GRADOS_CONOCIDOS if g in malignos)
|
||||
salida.append({
|
||||
"periodo": nombre, "inicio": inicio.isoformat(), "fin": ultimo_dia.isoformat(), "incompleto": corte < ultimo_dia,
|
||||
"reportes_mastografia": {"total": None if 0 < len(m) < umbral else len(m),
|
||||
"por_categoria": {k: {"n": None if k in ocultas_m else v, "suprimido": k in ocultas_m} for k, v in mm.items()}},
|
||||
"reportes_biopsia": {"total": None if 0 < len(b) < umbral else len(b),
|
||||
"por_grado": {k: {"n": None if k in ocultas_b else v, "suprimido": k in ocultas_b} for k, v in grados.items()}},
|
||||
"maligno": calc.proporcion(casos, conocidos, umbral),
|
||||
})
|
||||
return {"corte": corte.isoformat(), "umbral_supresion": umbral, "tipo_periodo": tipo, "unidad": "reportes",
|
||||
"poblacion": POBLACION_TENDENCIA, "alcance_biopsias": ALCANCE_BIOPSIAS,
|
||||
"denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": salida}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""The statistics the descriptive analysis uses: Wilson intervals, the chi-square test of homogeneity and quantiles.
|
||||
|
||||
Plain `math`: no statistics package, so the same inputs give the same numbers on every engine and machine.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
Z95 = 1.959963984540054
|
||||
|
||||
|
||||
def wilson(k: int, n: int, z: float = Z95) -> tuple[float, float]:
|
||||
"""The Wilson score interval of `k` of `n`, as proportions in [0, 1]. Needs `n > 0` and `0 <= k <= n`."""
|
||||
if n <= 0 or not 0 <= k <= n:
|
||||
raise ValueError(f"Wilson needs 0 <= k <= n and n > 0; got k={k}, n={n}")
|
||||
p = k / n
|
||||
denominador = 1 + z * z / n
|
||||
centro = (p + z * z / (2 * n)) / denominador
|
||||
margen = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominador
|
||||
return max(0.0, round(centro - margen, 12)), min(1.0, round(centro + margen, 12))
|
||||
|
||||
|
||||
def _gamma_q(a: float, x: float) -> float:
|
||||
"""The regularized upper incomplete gamma function Q(a, x)."""
|
||||
if x <= 0:
|
||||
return 1.0
|
||||
if x < a + 1:
|
||||
# Series for P(a, x); Q = 1 - P.
|
||||
termino = suma = 1.0 / a
|
||||
n = a
|
||||
for _ in range(1000):
|
||||
n += 1
|
||||
termino *= x / n
|
||||
suma += termino
|
||||
if abs(termino) < abs(suma) * 1e-15:
|
||||
break
|
||||
return max(0.0, 1.0 - suma * math.exp(-x + a * math.log(x) - math.lgamma(a)))
|
||||
# Continued fraction for Q(a, x) (modified Lentz).
|
||||
tiny = 1e-300
|
||||
b = x + 1 - a
|
||||
c = 1 / tiny
|
||||
d = 1 / b
|
||||
h = d
|
||||
for i in range(1, 1000):
|
||||
an = -i * (i - a)
|
||||
b += 2
|
||||
d = an * d + b
|
||||
d = tiny if abs(d) < tiny else d
|
||||
c = b + an / c
|
||||
c = tiny if abs(c) < tiny else c
|
||||
d = 1 / d
|
||||
delta = d * c
|
||||
h *= delta
|
||||
if abs(delta - 1) < 1e-15:
|
||||
break
|
||||
return min(1.0, math.exp(-x + a * math.log(x) - math.lgamma(a)) * h)
|
||||
|
||||
|
||||
def chi2_sf(x: float, gl: int) -> float:
|
||||
"""The probability that a chi-square variable with `gl` degrees of freedom exceeds `x`."""
|
||||
if gl < 1:
|
||||
raise ValueError("a chi-square needs at least one degree of freedom")
|
||||
return _gamma_q(gl / 2, x / 2)
|
||||
|
||||
|
||||
def chi2_homogeneidad(grupos: list[tuple[int, int]], minimo_esperado: float = 5.0) -> dict:
|
||||
"""The chi-square test that `k` groups share one proportion, from each group's (cases, total).
|
||||
|
||||
Valid only with at least two groups and every expected count (cases and non-cases) at or above `minimo_esperado`;
|
||||
otherwise it says why it isn't. Never a p-value from a table the approximation can't be trusted on.
|
||||
"""
|
||||
if len(grupos) < 2:
|
||||
return {"valida": False, "motivo": "Hacen falta al menos dos grupos con datos publicados."}
|
||||
casos, total = sum(k for k, _ in grupos), sum(n for _, n in grupos)
|
||||
if total == 0 or casos in (0, total):
|
||||
return {"valida": False, "motivo": "Todos los pacientes tienen el mismo resultado."}
|
||||
p = casos / total
|
||||
esperados = [(n * p, n * (1 - p)) for _, n in grupos]
|
||||
if any(min(a, b) < minimo_esperado for a, b in esperados):
|
||||
return {"valida": False, "motivo": f"Algún conteo esperado es menor que {minimo_esperado:g}: la aproximación no es confiable."}
|
||||
estadistico = sum((k - n * p) ** 2 / (n * p) + ((n - k) - n * (1 - p)) ** 2 / (n * (1 - p)) for k, n in grupos)
|
||||
gl = len(grupos) - 1
|
||||
return {"valida": True, "estadistico": round(estadistico, 4), "gl": gl, "p": chi2_sf(estadistico, gl)}
|
||||
|
||||
|
||||
def cuantil(valores: list[float], q: float) -> float:
|
||||
"""The quantile `q` (0 to 1) by linear interpolation between order statistics (the common 'type 7')."""
|
||||
if not valores:
|
||||
raise ValueError("a quantile needs at least one value")
|
||||
ordenados = sorted(valores)
|
||||
posicion = (len(ordenados) - 1) * q
|
||||
abajo = math.floor(posicion)
|
||||
arriba = min(abajo + 1, len(ordenados) - 1)
|
||||
return ordenados[abajo] + (ordenados[arriba] - ordenados[abajo]) * (posicion - abajo)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Suppression of small groups in the descriptive analysis.
|
||||
|
||||
A count of 1 to `umbral - 1` patients is never published. Hiding only those would still let a difference give them away
|
||||
(a published total minus the published cells), so a hidden cell drags the smallest published cell of its line with it
|
||||
until the hidden patients are at least `umbral`. A proportion is published only when neither its group, its cases nor its
|
||||
non-cases is such a small count. Zero is published: it describes nobody.
|
||||
"""
|
||||
|
||||
PEQUENO = lambda n, umbral: 0 < n < umbral # noqa: E731
|
||||
|
||||
|
||||
def proporcion_publicable(casos: int, total: int, umbral: int) -> bool:
|
||||
"""Whether `casos` of `total` may be published: the group, the cases and the rest are each zero or at least `umbral`."""
|
||||
return total >= umbral and not PEQUENO(casos, umbral) and not PEQUENO(total - casos, umbral)
|
||||
|
||||
|
||||
def _completar(suprimidas: set, conteos: dict, linea: list, umbral: int) -> bool:
|
||||
"""Adds to `suprimidas` the smallest published cells of `linea` until the hidden ones of it total `umbral` or more."""
|
||||
cambio = False
|
||||
while True:
|
||||
ocultos = sum(conteos[c] for c in linea if c in suprimidas)
|
||||
if ocultos == 0 or ocultos >= umbral:
|
||||
return cambio
|
||||
candidatas = [c for c in linea if c not in suprimidas and conteos[c] > 0]
|
||||
if not candidatas:
|
||||
return cambio
|
||||
suprimidas.add(min(candidatas, key=lambda c: (conteos[c], str(c))))
|
||||
cambio = True
|
||||
|
||||
|
||||
def suprimir_categorias(conteos: dict[str, int], umbral: int) -> set[str]:
|
||||
"""The categories of one distribution whose count is not published."""
|
||||
suprimidas = {c for c, n in conteos.items() if PEQUENO(n, umbral)}
|
||||
_completar(suprimidas, conteos, list(conteos), umbral)
|
||||
return suprimidas
|
||||
|
||||
|
||||
def suprimir_tabla(conteos: dict[tuple[str, str], int], umbral: int) -> set[tuple[str, str]]:
|
||||
"""The cells of a two-way table whose count is not published, with the same rule applied along every row and column."""
|
||||
suprimidas = {c for c, n in conteos.items() if PEQUENO(n, umbral)}
|
||||
filas = {f for f, _ in conteos}
|
||||
columnas = {c for _, c in conteos}
|
||||
lineas = [[k for k in conteos if k[0] == f] for f in sorted(filas)] + [[k for k in conteos if k[1] == c] for c in sorted(columnas)]
|
||||
cambio = True
|
||||
while cambio:
|
||||
cambio = False
|
||||
for linea in lineas:
|
||||
cambio |= _completar(suprimidas, conteos, linea, umbral)
|
||||
return suprimidas
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Aggregate and select the breast cohort through the same configured reader."""
|
||||
|
||||
from datetime import date
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD
|
||||
|
||||
analysis = Blueprint('cama_analysis', __name__)
|
||||
BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6')
|
||||
AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO')
|
||||
|
||||
|
||||
class SelectionError(Exception):
|
||||
def __init__(self, message, status=400):
|
||||
self.message, self.status = message, status
|
||||
|
||||
|
||||
def read_cohort(cutoff):
|
||||
reader = current_app.config.get('CAMA_COHORT_READER')
|
||||
if not callable(reader):
|
||||
raise SelectionError('Cohorte no disponible', 503)
|
||||
try:
|
||||
return reader(cutoff)
|
||||
except Exception:
|
||||
current_app.logger.exception('Breast cohort provider failed')
|
||||
raise SelectionError('Cohorte no disponible', 503) from None
|
||||
|
||||
|
||||
def cutoff_arg(args):
|
||||
text = args.get('corte')
|
||||
if not text:
|
||||
raise SelectionError('Se requiere corte')
|
||||
try:
|
||||
value = date.fromisoformat(text)
|
||||
if value.isoformat() != text or value.year == 9999:
|
||||
raise ValueError()
|
||||
return value
|
||||
except ValueError:
|
||||
raise SelectionError('Corte inválido') from None
|
||||
|
||||
|
||||
def patient_access():
|
||||
check = current_app.config.get('CAMA_COHORT_ACCESS')
|
||||
if check is not None and (not callable(check) or not check(request)):
|
||||
raise SelectionError('Acceso no autorizado', 403)
|
||||
|
||||
|
||||
def revision_of(rows):
|
||||
"""Identify the materialized cohort without exposing its patient identifiers."""
|
||||
encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def cohort_request(args):
|
||||
allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'}
|
||||
if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args):
|
||||
raise SelectionError('Parámetros desconocidos o repetidos')
|
||||
if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO:
|
||||
raise SelectionError('Cohorte o escenario desconocido')
|
||||
revision = args.get('revision', '')
|
||||
if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision):
|
||||
raise SelectionError('Revisión de cohorte inválida')
|
||||
cutoff = cutoff_arg(args)
|
||||
try:
|
||||
months = int(args.get('meses', '3'))
|
||||
page = int(args.get('page', '1'))
|
||||
size = int(args.get('page_size', '50'))
|
||||
if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise SelectionError('Ventana o paginación inválida') from None
|
||||
filters = {key: args.get(key) for key in ('birads', 'grupo_edad')}
|
||||
if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES):
|
||||
raise SelectionError('Filtro inválido')
|
||||
return cutoff, months, page, size, filters, revision
|
||||
|
||||
|
||||
def selected(args):
|
||||
patient_access()
|
||||
from werkzeug.datastructures import MultiDict
|
||||
|
||||
args = MultiDict(args)
|
||||
if 'cohorte' not in args:
|
||||
if any(key in args for key in ('revision', 'escenario')):
|
||||
raise SelectionError('Contexto de cohorte incompleto')
|
||||
if 'corte' not in args:
|
||||
args['corte'] = date.today().isoformat()
|
||||
cutoff = cutoff_arg(args)
|
||||
rows = read_cohort(cutoff)
|
||||
args.update({'cohorte': COHORT, 'escenario': SCENARIO, 'revision': revision_of(rows)})
|
||||
else:
|
||||
rows = None
|
||||
cutoff, months, page, size, filters, revision = cohort_request(args)
|
||||
if rows is None:
|
||||
rows = read_cohort(cutoff)
|
||||
if not hmac.compare_digest(revision, revision_of(rows)):
|
||||
raise SelectionError('La cohorte cambió; actualiza el análisis', 409)
|
||||
selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())]
|
||||
if months:
|
||||
from webapi.seguimiento_cama import _desde
|
||||
try:
|
||||
since = _desde(cutoff, months)
|
||||
except (ValueError, OverflowError):
|
||||
raise SelectionError('Ventana inválida') from None
|
||||
else:
|
||||
since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff)
|
||||
selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff]
|
||||
# Every filtered selection is checked on the server after applying the window.
|
||||
if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())):
|
||||
raise SelectionError('Selección no disponible', 403)
|
||||
return cutoff, months, page, size, filters, since, selected_rows, revision
|
||||
|
||||
|
||||
def selection_response(args, mode, patient=None):
|
||||
cutoff, months, page, size, filters, since, rows, revision = selected(args)
|
||||
options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)]
|
||||
columns = [
|
||||
{'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'}]},
|
||||
]
|
||||
meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(),
|
||||
'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()},
|
||||
'campo_ventana': 'mastografia_fecha', 'filtros': filters,
|
||||
'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]}
|
||||
for k, label, values in options], 'columnas': columns}
|
||||
if mode == 'patient':
|
||||
found = next((row for row in rows if row['pac_id'] == patient), None)
|
||||
if found is None:
|
||||
raise SelectionError('Paciente no encontrado', 404)
|
||||
return jsonify(**meta, item=found)
|
||||
if mode == 'export':
|
||||
if len(rows) > 5000:
|
||||
raise SelectionError('La exportación supera el límite de 5000 registros', 413)
|
||||
return jsonify(**meta, total_items=len(rows), items=rows)
|
||||
return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows),
|
||||
'total_pages': (len(rows) + size - 1) // size},
|
||||
items=rows[(page - 1) * size:page * size])
|
||||
|
||||
|
||||
@analysis.get('/analisis/indicadores')
|
||||
def indicators():
|
||||
try:
|
||||
if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1:
|
||||
raise SelectionError('Se requiere únicamente corte')
|
||||
cutoff = cutoff_arg(request.args)
|
||||
rows = read_cohort(cutoff)
|
||||
groups = []
|
||||
for code in BIRADS:
|
||||
count = sum(r['birads'] == code for r in rows)
|
||||
groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD})
|
||||
return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(),
|
||||
horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente',
|
||||
denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
|
||||
indicadores=[], grupos=groups)
|
||||
except SelectionError as e:
|
||||
return jsonify(error=e.message), e.status
|
||||
|
||||
|
||||
@analysis.after_request
|
||||
def no_cache(response):
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
return response
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Read the breast screening cohort from the existing silver tables.
|
||||
|
||||
The current silver tables keep only the last version of each fact. Filtering by
|
||||
load date prevents future facts from appearing at an earlier cutoff, but cannot
|
||||
restore a previous value after an update.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import aliased
|
||||
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
|
||||
COHORT = "cama_birads_v1"
|
||||
SCENARIO = "diagnostico"
|
||||
THRESHOLD = 5
|
||||
|
||||
# `core/catalogos/cama.toml`'s `mastografia.resultados.birads`: the cohort is restricted to the codes that call
|
||||
# for a biopsy (B4 and its subcategories, B5, B6); B0 to B3 fall out by not being in this map.
|
||||
BIRADS = {"B4": "BIRADS_4", "B4A": "BIRADS_4A", "B4B": "BIRADS_4B", "B4C": "BIRADS_4C", "B5": "BIRADS_5", "B6": "BIRADS_6"}
|
||||
|
||||
|
||||
def mastografias(t):
|
||||
"""One row per mammogram taken, with the report that hangs from it (nulls when it has none): the Python
|
||||
equivalent of `Transformation/models/cama/silver/cama_mastografias.sql`, kept independent of dbt's manifest
|
||||
since this reader runs without one."""
|
||||
toma, reporte, obs_birads = aliased(t.Procedimiento), aliased(t.Procedimiento), aliased(t.Observacion)
|
||||
return (
|
||||
select(
|
||||
toma.procedimiento_id.label("procedimiento_id"),
|
||||
toma.fuente_tabla.label("fuente_tabla"),
|
||||
toma.fuente_id.label("fuente_id"),
|
||||
toma.pac_id.label("pac_id"),
|
||||
toma.fecha.label("fecha_toma"),
|
||||
reporte.procedimiento_id.label("reporte_id"),
|
||||
reporte.fecha.label("fecha_reporte"),
|
||||
func.coalesce(obs_birads.valor_id, obs_birads.valor_fuente).label("birads"),
|
||||
)
|
||||
.select_from(toma)
|
||||
.outerjoin(reporte, (reporte.padre_id == toma.procedimiento_id) & (reporte.estudio_id == "mastografia")
|
||||
& (reporte.clase == "reporte"))
|
||||
.outerjoin(obs_birads, (obs_birads.procedimiento_id == reporte.procedimiento_id)
|
||||
& (obs_birads.resultado_id == "mastografia.birads"))
|
||||
.where(toma.estudio_id == "mastografia", toma.clase == "toma")
|
||||
)
|
||||
|
||||
|
||||
def biopsias(t):
|
||||
"""One row per biopsy report with its grade, its order and the mammogram that led to it, if found: mammogram
|
||||
(toma) -> biopsy order -> biopsy report, by `padre_id`. The Python equivalent of
|
||||
`Transformation/models/cama/silver/cama_biopsias.sql`, plus the mammogram's own date and patient (`fecha_toma`,
|
||||
`toma_pac_id`), which the cohort's cross-check needs and the dbt model doesn't expose."""
|
||||
reporte, orden, toma, obs_grado = (aliased(t.Procedimiento), aliased(t.Procedimiento), aliased(t.Procedimiento),
|
||||
aliased(t.Observacion))
|
||||
return (
|
||||
select(
|
||||
reporte.procedimiento_id.label("procedimiento_id"),
|
||||
reporte.fuente_tabla.label("fuente_tabla"),
|
||||
reporte.fuente_id.label("fuente_id"),
|
||||
reporte.pac_id.label("pac_id"),
|
||||
reporte.fecha.label("fecha_reporte"),
|
||||
func.coalesce(obs_grado.valor_id, obs_grado.valor_fuente).label("grado"),
|
||||
orden.fecha.label("fecha_solicitud"),
|
||||
toma.procedimiento_id.label("toma_id"),
|
||||
toma.fecha.label("fecha_toma"),
|
||||
toma.pac_id.label("toma_pac_id"),
|
||||
)
|
||||
.select_from(reporte)
|
||||
.outerjoin(obs_grado, (obs_grado.procedimiento_id == reporte.procedimiento_id)
|
||||
& (obs_grado.resultado_id == "biopsia.grado"))
|
||||
.outerjoin(orden, (orden.procedimiento_id == reporte.padre_id) & (orden.estudio_id == "biopsia")
|
||||
& (orden.clase == "orden"))
|
||||
.outerjoin(toma, (toma.procedimiento_id == orden.padre_id) & (toma.estudio_id == "mastografia")
|
||||
& (toma.clase == "toma"))
|
||||
.where(reporte.estudio_id == "biopsia", reporte.clase == "reporte")
|
||||
)
|
||||
|
||||
|
||||
def _date(value):
|
||||
return date.fromisoformat(value) if isinstance(value, str) else value
|
||||
|
||||
|
||||
def _known(value, cutoff):
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, str):
|
||||
value = datetime.fromisoformat(value)
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc)
|
||||
|
||||
|
||||
def _age_group(birth, cutoff):
|
||||
if birth is None or birth > cutoff:
|
||||
return "SIN_DATO"
|
||||
age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day))
|
||||
if age < 40:
|
||||
return "MENOR_40"
|
||||
if age >= 70:
|
||||
return "70+"
|
||||
return f"{age // 10 * 10}-{age // 10 * 10 + 9}"
|
||||
|
||||
|
||||
class CamaCohort:
|
||||
"""Materialize one row per eligible patient, using a caller-owned session."""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
|
||||
def rows(self, cutoff: date):
|
||||
t = TABLAS
|
||||
loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()}
|
||||
procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()}
|
||||
observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()}
|
||||
people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()}
|
||||
|
||||
def procedure_known(identifier):
|
||||
p = procedures.get(identifier)
|
||||
return bool(p and _known(loads.get(p.carga_id), cutoff))
|
||||
|
||||
def observation_known(identifier, result, patient):
|
||||
o = observations.get((identifier, result))
|
||||
return bool(o and o.pac_id == patient and _known(loads.get(o.carga_id), cutoff))
|
||||
|
||||
def load_time(record):
|
||||
value = loads.get(record.carga_id) if record else None
|
||||
return value.isoformat() if value else None
|
||||
|
||||
candidates = {}
|
||||
for row in self.session.execute(mastografias(t)).mappings():
|
||||
taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte'])
|
||||
if not (taken and reported and taken <= reported <= cutoff and row['birads']
|
||||
and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id'])
|
||||
and procedures[row['reporte_id']].pac_id == row['pac_id']
|
||||
and observation_known(row['reporte_id'], 'mastografia.birads', row['pac_id'])):
|
||||
continue
|
||||
key = (taken, str(row['fuente_id']), reported, row['reporte_id'])
|
||||
prior = candidates.get(row['pac_id'])
|
||||
if prior is None or key > prior[0]:
|
||||
candidates[row['pac_id']] = (key, row)
|
||||
|
||||
reports = {}
|
||||
orders = {}
|
||||
for p in procedures.values():
|
||||
when = _date(p.fecha)
|
||||
if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when
|
||||
or when > cutoff or not procedure_known(p.procedimiento_id)):
|
||||
continue
|
||||
key = (p.pac_id, p.padre_id)
|
||||
rank = (when, str(p.fuente_id), p.procedimiento_id)
|
||||
if key not in orders or rank > orders[key][0]:
|
||||
orders[key] = (rank, p)
|
||||
for row in self.session.execute(biopsias(t)).mappings():
|
||||
reported, ordered, taken = (_date(row['fecha_reporte']), _date(row['fecha_solicitud']),
|
||||
_date(row['fecha_toma']))
|
||||
procedure = procedures.get(row['procedimiento_id'])
|
||||
order = procedures.get(procedure.padre_id) if procedure else None
|
||||
if not (taken and reported and ordered and taken <= ordered <= reported <= cutoff and row['toma_id']
|
||||
and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id'])
|
||||
and order and order.pac_id == row['pac_id'] and procedure_known(order.procedimiento_id)):
|
||||
continue
|
||||
key = (row['pac_id'], row['toma_id'])
|
||||
rank = (reported, str(row['fuente_id']), row['procedimiento_id'])
|
||||
if key not in reports or rank > reports[key][0]:
|
||||
reports[key] = (rank, row)
|
||||
|
||||
rows = []
|
||||
for patient, (_, m) in candidates.items():
|
||||
code = BIRADS.get(m['birads'])
|
||||
if not code or patient not in people:
|
||||
continue
|
||||
b = reports.get((patient, m['procedimiento_id']))
|
||||
b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None
|
||||
order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None
|
||||
if not order:
|
||||
found_order = orders.get((patient, m['procedimiento_id']))
|
||||
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
|
||||
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
|
||||
rows.append({
|
||||
'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
|
||||
'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(),
|
||||
'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff),
|
||||
'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None,
|
||||
'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None,
|
||||
'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]),
|
||||
'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]),
|
||||
'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))),
|
||||
'biopsia_solicitud_carga_inicio': load_time(order),
|
||||
'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None,
|
||||
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
|
||||
if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None,
|
||||
})
|
||||
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))
|
||||
@@ -0,0 +1,9 @@
|
||||
"""CaMa's follow-up list (`GET /cama/seguimiento`): the patients of the BI-RADS cohort at a cut-off, one row each.
|
||||
|
||||
cohort.py who is in the cohort at a cut-off and what each row shows
|
||||
listing.py the selection (window, filters, suppression), the pages, the file and the revision
|
||||
routes.py the routes: validate the request and answer
|
||||
|
||||
The cohort is read from dbt's `cama_cohorte_birads` view. Every response is marked `simulado`: the list holds
|
||||
patient-level rows, and who may read it on real data is an access rule still to be defined.
|
||||
"""
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Retain dev's optional access callback; no new authentication policy."""
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
|
||||
def configured_access():
|
||||
check = current_app.config.get('CAMA_COHORT_ACCESS')
|
||||
if check is not None and (not callable(check) or not check(request)):
|
||||
return jsonify(error='Acceso no autorizado'), 403
|
||||
@@ -0,0 +1,164 @@
|
||||
"""The BI-RADS cohort at a cut-off.
|
||||
|
||||
Each patient counts once, through her latest mammogram whose report (with a BI-RADS) is dated on or before the cut-off;
|
||||
she belongs to the cohort when that BI-RADS is one of `cama.birads_4_a_6`. The latest is the one with the latest
|
||||
date taken, then the greatest source id, then the latest report date, then the greatest report id, so the same data
|
||||
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, timedelta
|
||||
|
||||
from sqlalchemy import Date, Integer, String, column, func, inspect, select, table
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import valor_de
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
COHORTE = "cama_birads_v1"
|
||||
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")
|
||||
|
||||
CANDIDATOS = table(
|
||||
"cama_cohorte_birads",
|
||||
column("pac_id", Integer), column("procedimiento_id", Integer), column("fuente_id", String),
|
||||
column("fecha_toma", Date), column("reporte_id", Integer), column("fecha_reporte", Date), column("birads", String),
|
||||
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 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:
|
||||
inspector = inspect(sesion.get_bind())
|
||||
return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Fila:
|
||||
"""One patient of the cohort: the codes the list shows and filters by."""
|
||||
|
||||
pac_id: int
|
||||
mastografia_fecha: date
|
||||
birads: str
|
||||
grupo_edad: str
|
||||
biopsia: str | None
|
||||
biopsia_fecha: date | None
|
||||
# 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:
|
||||
"""The value the biopsy filter compares: the grade, `SIN_DATO` for a report without one, `SIN_BIOPSIA` for none."""
|
||||
if self.biopsia_fecha is None:
|
||||
return SIN_BIOPSIA
|
||||
return self.biopsia or SIN_DATO
|
||||
|
||||
|
||||
def _rango_de_grado(grado: str | None) -> int:
|
||||
return GRADOS_POR_GRAVEDAD.index(grado) if grado in GRADOS_POR_GRAVEDAD else -1
|
||||
|
||||
|
||||
def codigo_birads(fuente: str) -> str:
|
||||
"""`B4A` as the list names it: `BIRADS_4A`."""
|
||||
return "BIRADS_" + fuente[1:]
|
||||
|
||||
|
||||
def grupos_de_edad(sesion: Session) -> list[str]:
|
||||
"""The age groups of `cama.grupos_edad` in order, with the open ones at both ends (`<40`, `40-49`, ..., `70+`)."""
|
||||
cortes = valor_de(sesion, "cama.grupos_edad", tablas=TABLAS)
|
||||
return [g.etiqueta for g in sorted(grupos_de_cortes(cortes, tablas=TABLAS), key=lambda g: g.edad_min)]
|
||||
|
||||
|
||||
def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
|
||||
"""The completed age at the cut-off in its group; `SIN_DATO` without a birth date or with one after the cut-off."""
|
||||
if nacimiento is None or nacimiento > corte:
|
||||
return SIN_DATO
|
||||
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
|
||||
for grupo in grupos:
|
||||
if grupo.edad_min <= edad <= grupo.edad_max:
|
||||
return grupo.etiqueta
|
||||
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)
|
||||
c = CANDIDATOS.c
|
||||
candidatas = sesion.execute(
|
||||
select(CANDIDATOS).where(c.fecha_reporte <= corte, c.fecha_toma <= c.fecha_reporte)
|
||||
).mappings().all()
|
||||
|
||||
gravedad = {codigo: rango for rango, codigo in enumerate(valor_de(sesion, "cama.birads_gravedad", tablas=TABLAS))}
|
||||
por_mastografia: dict[tuple, dict] = {}
|
||||
for fila in candidatas:
|
||||
mastografia = por_mastografia.setdefault(
|
||||
(fila["pac_id"], fila["procedimiento_id"], fila["reporte_id"], fila["birads"]), {"fila": fila, "biopsias": []})
|
||||
# A biopsy report dated after the cut-off, or before the mammogram, doesn't exist for this list.
|
||||
if fila["biopsia_id"] is not None and fila["fecha_toma"] <= fila["biopsia_fecha_reporte"] <= corte:
|
||||
mastografia["biopsias"].append(fila)
|
||||
mastografias: dict[int, tuple] = {}
|
||||
for mastografia in por_mastografia.values():
|
||||
fila = mastografia["fila"]
|
||||
llave = (fila["fecha_toma"], str(fila["fuente_id"]), fila["fecha_reporte"], fila["reporte_id"],
|
||||
gravedad.get(fila["birads"], -1))
|
||||
if fila["pac_id"] not in mastografias or llave > mastografias[fila["pac_id"]][0]:
|
||||
mastografias[fila["pac_id"]] = (llave, mastografia)
|
||||
|
||||
cohorte = []
|
||||
for pac_id, (_, elegida) in mastografias.items():
|
||||
fila = elegida["fila"]
|
||||
if fila["birads"] not in admitidos:
|
||||
continue
|
||||
biopsia = max(elegida["biopsias"], key=lambda b: (b["biopsia_fecha_reporte"], str(b["biopsia_fuente_id"]), b["biopsia_id"],
|
||||
_rango_de_grado(b["biopsia_grado"])), default=None)
|
||||
cohorte.append(Fila(
|
||||
pac_id=pac_id, mastografia_fecha=fila["fecha_toma"], birads=codigo_birads(fila["birads"]),
|
||||
grupo_edad=grupo_de_edad(fila["fecha_nacimiento"], corte, grupos),
|
||||
biopsia=biopsia["biopsia_grado"] if biopsia else None,
|
||||
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))
|
||||
|
||||
|
||||
def construccion(sesion: Session) -> str:
|
||||
"""The data the cohort stands on: the last load that added or changed rows (`carga-<id>`, `carga-0` without any)."""
|
||||
carga = TABLAS.Carga
|
||||
ultima = sesion.execute(
|
||||
select(func.max(carga.carga_id)).where((carga.filas_nuevas > 0) | (carga.filas_cambiadas > 0))
|
||||
).scalar()
|
||||
return f"carga-{ultima or 0}"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user