Compare commits

..

26 Commits

Author SHA1 Message Date
ulises 9a62ddcdaf CaMa recurrence: import schemas for the follow-up and the new patient variables, silver mappings and /cama/recurrencia
The patient takes the menopausal state, molecular and clinical subtype, integrative cluster, cellularity, mutation load,
Ki-67 category and source of the record; a new import entity carries the recurrence and the last contact; hormone and
anti-HER2 therapy are treatments. The route serves each cohort's scenarios, a scenario's figure and a patient's scenarios
over the live cohort build, computing the models and the bootstrap in the background and caching them per build. Includes
the survival import work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:42 -06:00
edgar 26f2b35338 Retire GET /cacu/pacientes/<id>/riesgo: the record reads the FHIR RiskAssessment
The WebApp patient record now reads GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (WebApp
feature/cohorts-dbt-canonical), so the custom route, its blueprint and its tests go; the risk batches and the
follow-up list point to the FHIR search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:15:55 -06:00
edgar 0c1b383da2 CaCu's individual risk as a FHIR RiskAssessment, and each risk's index date
GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (DEV only, tagged simulado, a searchset validated with R4B, as
TEA's patient resources): the patient's current batch, one prediction per horizon with its outcome, probability and
whenPeriod from the risk's index date, the confidence interval in an extension; declared in the CapabilityStatement.
GET /cacu/pacientes/<id>/riesgo adds riesgo.fecha_indice. Tests and the risk-band fixture carry the index date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:46 -06:00
edgar 7d06f9db9d The cycle builds the cohorts dbt defines; models' moved modules
The `cohorts` and `estimate` steps take the project's cohorts from dbt's manifest (`cohort_urls`) and build each one
with models' `build_of` over dbt's queries, instead of the Python-frame TOMLs in models/cohorts, which are gone; without
a manifest a project has no cohort steps. The recruitment window and cut-off are dbt's vars. The live estimator reads
cin2_logistic through `Scenario` and `KitBuild`, and governance imports `models.reports.experiment`, where models now
keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:18:00 -06:00
Angel Capetillo Zavala c86c530703 Declare the tea library as a direct dependency 2026-11-20 16:56:05 -06:00
Angel Capetillo Zavala 553d25fa54 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:44:47 -06:00
AlbertoPMDM 6b8af821a3 Lock the tea library at 0.2.0 2026-11-19 20:34:09 -06:00
AlbertoPMDM d35e8bbae9 feat(tea): EEG analysis before the silver load, and its verdict, quality checks and baselines through silver and FHIR 2026-11-19 15:43:27 -06:00
Erick ivan 7101913fff revert(auth): remove the session login from the API
The API no longer authenticates: no /auth routes, no session cookie and no before_request lock. An external service that reads and writes data was hitting the 401, so the endpoint is open again.

The interface keeps its login and the per-account domains, now resolved in the browser. WEBAPI_USUARIO(S) and WEBAPI_SECRET_KEY are gone from the Dockerfile and .env.example.
2026-11-19 10:32:22 -06:00
Erick ivan 084fe2e8d3 feat(auth): session login with per-domain scope
Cookie session with /auth/login, /auth/logout and /auth/me. Four accounts come from WEBAPI_USUARIOS (admin plus one per domain) and a second before_request answers 403 when an account asks for another domain.

The data suites run with WEBAPI_AUTH_REQUIRED=0; test_auth.py turns the lock back on and covers both hooks. The Dockerfile normalises the entrypoint so a Windows checkout still starts the container.
2026-11-19 09:35:25 -06:00
Angel Capetillo Zavala b1bbbc25b4 Integrate CaMa follow-up, descriptive analysis and L3 with dev
Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
2026-11-17 10:44:07 -06:00
Roberto Treviño Cervantes 0571b5e6af wording fixes 2026-11-17 02:17:31 -06:00
roberto 0a7234f5ef Merge pull request 'Kit exit: FHIR MeasureReports, live estimators, entrenar profile' (#12) from feature/kit-exit-integration into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/12
2026-11-16 21:09:28 -06:00
Roberto Treviño Cervantes 9737b5a67f The follow-up list identifies each patient by the platform's pac_id, the key the risk route takes; TEA keeps its salted pseudonym 2026-11-15 05:40:08 -06:00
Roberto Treviño Cervantes 854a2e9c55 The recomputation worker estimates with the models in production and wakes on the marker directory; the scanned test form carries a birth date 2026-11-15 05:37:50 -06:00
Roberto Treviño Cervantes b8045e7481 dbt's manifest compiled at start-up for the deployment's engine; the image carries the dbt environments 2026-11-15 00:47:38 -06:00
Roberto Treviño Cervantes 6dce665d93 Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration
# Conflicts:
#	Dockerfile
#	README.md
#	tests/staging/cama.py
#	tests/test_fhir_measures.py
#	tests/test_fhir_tea.py
#	tests/test_orquestacion_oro.py
#	tests/test_orquestacion_plata.py
#	uv.lock
#	webapi/__init__.py
#	webapi/fhir/__init__.py
#	webapi/fhir/measures.py
#	webapi/follow_up/routes.py
#	webapi/imports/schemas/tea/ordenes_estudio.py
#	webapi/metrics.py
#	webapi/orchestration/cycle.py
#	webapi/orchestration/reference/catalogs.py
#	webapi/orchestration/repositories.py
#	webapi/orchestration/silver/cama.py
#	webapi/orchestration/silver/orders_and_notes.py
2026-11-15 00:44:31 -06:00
rockdrigo 461d651805 TEA FHIR: an episode's _include brings its ADOS-2 observation 2026-11-13 17:03:23 -06:00
alberto 790879513b The image compiles dbt's manifest and sets DBT_MANIFEST, so the measure and FHIR routes are served 2026-11-13 15:31:29 -06:00
alberto e19121bc42 TEA: an order carries its study's report as a PDF through the import 2026-11-13 15:03:02 -06:00
alberto 0f9433949f TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too 2026-11-12 19:47:19 -06:00
edgar a0407e41d6 TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary 2026-11-12 15:21:25 -06:00
edgar c430a5bd11 Every stratum value an answer writes is in the stratum-value catalog 2026-11-08 17:28:24 -06:00
edgar 270e229a51 The kit's silver load, reference tables, table maps and follow-up list move into the WebApi; the kit is no longer a dependency 2026-11-08 17:28:24 -06:00
edgar 82504bd0bf English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports 2026-11-08 17:28:24 -06:00
edgar 2296598896 CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is /<domain>/indicadores 2026-11-08 17:28:24 -06:00
99 changed files with 6757 additions and 572 deletions
+23 -1
View File
@@ -1,6 +1,22 @@
# Build context is the repo root (see docker-compose.yml) so the sibling
# packages Core/, Persistance/, Extraction/ and models/
# can be copied.
# can be copied, and Transformation/ compiled.
# 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. 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 --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.
@@ -34,6 +50,12 @@ ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
ENV WEBAPI_REPORT_DIR=/data/reportes
ENV INDICADORES_DIR=/data/indicadores
ENV MLFLOW_DISABLE_AGENT_HINT=1
# Without it the measure routes (/<domain>/indicadores, /<domain>/fhir) aren't
# registered. The entrypoint replaces it with one compiled against the
# 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
+1
View File
@@ -70,6 +70,7 @@ 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) |
+25 -3
View File
@@ -2,7 +2,7 @@
set -e
# The notebook runner shares the image but runs with no network, a read-only
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
# 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
@@ -16,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
+74
View File
@@ -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.
+94
View File
@@ -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.
+59
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
2026-11-22T10:18:21+00:00
+7 -2
View File
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
dependencies = [
"flask>=3.0",
"persistance",
"models[notebooks]",
"models[notebooks,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
+18 -8
View File
@@ -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 }
+47 -26
View File
@@ -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)
+258
View File
@@ -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()
+226
View File
@@ -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])
+193
View File
@@ -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
+52
View File
@@ -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
+370
View File
@@ -0,0 +1,370 @@
"""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.
"""
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: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data
doesn't support is added, or the hospital's identifier leaks."""
respuesta = get(app, page_size=200)
cuerpo = respuesta.get_json()
assert cuerpo["simulado"] is True
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"])
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"]
assert 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")]
+310
View File
@@ -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
+58
View File
@@ -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'
+94
View File
@@ -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]) == {}
+25
View File
@@ -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'}
+53
View File
@@ -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"
+118
View File
@@ -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.
Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up
only on the next cycle), or the analysis starts waiting for steps it doesn't need.
"""
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
assert "analyze_eeg" in deps["load"]
assert deps["analyze_eeg"] == {"migrate"}
order = steps_of(proyecto)
assert order.index("analyze_eeg") < order.index("load")
def test_without_an_analysis_the_step_does_nothing():
"""Pins down: a context without `eeg_analysis` (CaCu, CaMa, the tests' cycles) makes the step a no-op.
Fails if the step starts running an analysis nobody configured.
"""
pasos = run(Context("cacu", 2025, 2025), only=["analyze_eeg"])
assert [(p.name, p.summary) for p in pasos] == [("analyze_eeg", {})]
def test_what_the_analysis_writes_is_loaded_by_the_same_cycle(tea_base, fake_analysis):
"""Pins down: the cycle runs the analysis once, before any silver load, and `load` then carries what it wrote
into the EEG's silver observations.
Fails if the analysis runs after `load` or more than once, or its summary stops being the step's.
"""
from core.tea.indicadores.models import Observacion, Procedimiento
pasos = tea_base.run("analyze_eeg", "catalogs", "load", eeg_analysis=fake_analysis)
assert pasos["analyze_eeg"] == {"pending": 1, "valid": 1, "not_valid": 0, "failed": 0}
assert fake_analysis.calls == [0]
with Session(tea_base.motor) as sesion:
toma = sesion.exec(select(Procedimiento).where(Procedimiento.estudio_id == "eeg",
Procedimiento.clase == "toma")).one()
valores = {o.resultado_id: o.valor_numerico for o in sesion.exec(
select(Observacion).where(Observacion.procedimiento_id == toma.procedimiento_id))}
assert valores["eeg.canales"] == 21
def test_only_tea_has_an_analysis_and_it_can_be_turned_off(monkeypatch):
"""Pins down: TEA's cycle gets the analysis, with the cluster `EEG_ANALYSIS_CLUSTER` names; the other domains
get none, `off` leaves it out, and an unknown value is refused.
Fails if another domain starts analysing EEGs, `off` stops leaving the analysis out, or a mistyped cluster is
silently taken as the default.
"""
monkeypatch.delenv(CLUSTER_ENV, raising=False)
assert live_eeg_analysis("tea").keywords == {"cluster": "auto"}
assert live_eeg_analysis("cacu") is None
monkeypatch.setenv(CLUSTER_ENV, "sync")
assert live_eeg_analysis("tea").keywords == {"cluster": "sync"}
monkeypatch.setenv(CLUSTER_ENV, "off")
assert live_eeg_analysis("tea") is None
monkeypatch.setenv(CLUSTER_ENV, "everywhere")
with pytest.raises(ValueError, match=CLUSTER_ENV):
live_eeg_analysis("tea")
+109
View File
@@ -0,0 +1,109 @@
"""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"]
+1 -1
View File
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
domain, client = domain_client
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
assert measures["total"] == {"cacu": 7, "cama": 8}[domain]
assert measures["total"] == {"cacu": 7, "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()
+103 -6
View File
@@ -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
@@ -167,8 +168,10 @@ 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,
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."""
ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality
observations, one per check of its analysis (clean windows, usable scalp, triage level, line noise) as the
analysis's own report writes them; no metric observation while the alterations are hidden. Fails if an included
resource drops out, a check stops reaching the report or changes shape, or the alterations leak."""
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}
@@ -176,7 +179,47 @@ 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, "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):
@@ -204,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"
@@ -222,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):
+87
View File
@@ -173,6 +173,64 @@ 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
@@ -203,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"]}
+9 -5
View File
@@ -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",
+58
View File
@@ -0,0 +1,58 @@
"""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_only_cacu_has_a_live_estimator():
"""CaMa and TEA have no registered model, so their cycles estimate nothing. Fails if a domain without a model
gets an estimator that would then fail resolving a version."""
assert estimators.live_estimators("cama") == {}
assert estimators.live_estimators("tea") == {}
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
Fails if `live_estimators` stops catching the registry's `LookupError`."""
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
assert estimators.live_estimators("cacu") == {}
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
live = estimators.live_estimators("cacu")
assert list(live) == [URL]
estimator = live[URL]
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
with pytest.raises(RuntimeError):
estimator.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
+38
View File
@@ -348,3 +348,41 @@ def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
assert "nódulo circunscrito" in row.mast_interpretacion
assert row.mast_dicom_blob.startswith(b"\x89PNG")
def test_a_tea_order_keeps_the_pdf_its_sql_source_carries(client, tmp_path):
"""Pins down: `ord_pdf_blob` travels with the order from a SQL source into `ordenes_estudio`, byte for
byte, and an order without a file stays without one. The source is a SQLite file in `tmp_path` holding a
two-row `ordenes_estudio`. Fails if the import schema drops the field or the commit rewrites the bytes."""
report = text_pdf([["EVALUACION PSICOLOGICA", "ADOS-2 Modulo 2"]])
url = f"sqlite:///{tmp_path / 'hospital.db'}"
table = sa.Table(
"ordenes_estudio", sa.MetaData(),
sa.Column("ord_id", sa.String(36), primary_key=True),
sa.Column("ord_id_hospital", sa.String(64)),
sa.Column("ord_tipo_estudio", sa.Text),
sa.Column("ord_pdf_blob", sa.LargeBinary),
)
engine = sa.create_engine(url)
table.create(engine)
with engine.begin() as connection:
connection.execute(sa.insert(table), [
{"ord_id": "ord-pdf-1", "ord_id_hospital": "ORD-PDF-1", "ord_tipo_estudio": "ADOS2", "ord_pdf_blob": report},
{"ord_id": "ord-pdf-2", "ord_id_hospital": "ORD-PDF-2", "ord_tipo_estudio": "EEG", "ord_pdf_blob": None},
])
engine.dispose()
source = {
"source_type": "sql",
"target": "tea.OrdenesEstudio",
"column_mapping": {column.name: column.name for column in table.columns},
"payload": {"connection_string": url, "table": "ordenes_estudio"},
}
result = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}).get_json()["results"][0]
assert (result["created"], result["rejected"]) == (2, 0), result
from persistance.tea import ordenes_estudio_repository
assert ordenes_estudio_repository.get("ord-pdf-1").ord_pdf_blob == report
assert ordenes_estudio_repository.get("ord-pdf-2").ord_pdf_blob is None
+13 -6
View File
@@ -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,22 @@ 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_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases):
"""Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores
as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from
anywhere else than dbt, or a build's count and members disagree."""
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
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) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in 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()
+3 -3
View File
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers and its eight measures;
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
# TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 13, "tea": 11}[base.proyecto]
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "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": 8, "tea": 10}[base.proyecto]
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
+14 -4
View File
@@ -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"))
+1 -1
View File
@@ -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
-87
View File
@@ -1,87 +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`, the app without `DEV_REVISION` 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.
"""
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):
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
with pytest.MonkeyPatch.context() as mp:
mp.delenv("DEV_REVISION", raising=False)
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
def test_a_scored_member_has_the_contracts_shape(client, seeded):
"""Pins down: without `DEV_REVISION` the route exists, and 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 the route depends on an environment variable again, or 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
+102
View File
@@ -0,0 +1,102 @@
"""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
+4 -2
View File
@@ -9,7 +9,7 @@ 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",
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
"dias_toma_diagnostico", "prioridad"} # fmt: skip
@@ -31,7 +31,9 @@ def test_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):
+72
View File
@@ -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'}
+5 -10
View File
@@ -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):
+143
View File
@@ -0,0 +1,143 @@
"""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 and p5/median/p95 5/6/7, 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),
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 and the baseline's p5/median/p95 at the age are results of the recording.
Fails if the silver mapping or the catalog drops one of the deviation's results.
"""
toma = _observations(loaded, "toma")
assert [toma[None, f"eeg.ritmo_posterior{s}"] for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95")] == \
[6.8, 1.2, 0, 5.0, 6.0, 7.0]
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 and the baseline's
p5/median/p95 as the reference; a metric without a z (no baseline in production) can't be evaluated. And the
electrodes view carries each electrode's z next to its value.
Fails if dbt goes back to scoring metrics against fixed ranges of its own, or drops the electrode z.
"""
with loaded.motor.connect() as connection:
metrics = {r.metrica: r for r in connection.execute(text(
"select metrica, valor, ref_min, ref_mediana, ref_max, valor_z, estado from tea_paciente_eeg_metricas"))}
(electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all()
rhythm = metrics["ritmo_posterior"]
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.valor_z, rhythm.estado) == \
(6.8, 5.0, 6.0, 7.0, 1.2, "normal")
assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
assert tuple(electrode) == (1.4, -0.4)
+3 -4
View File
@@ -19,7 +19,7 @@ from sqlmodel import select
import staging.tea as fixture
from conftest import base_de
from core.tea.models import Ados2, Eeg, 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)
Generated
+1021 -134
View File
File diff suppressed because it is too large Load Diff
+16 -5
View File
@@ -10,6 +10,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.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
from webapi.cama_recurrence.routes import cama_recurrence_bp
from webapi.cama_survival.routes import cama_survival_bp
from webapi.follow_up.routes import follow_up_blueprint
@@ -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
@@ -87,14 +94,18 @@ def create_app() -> Flask:
# 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, marked `simulado` in every response. Who may see them is
# an access rule still to be defined, not an environment variable.
# 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.db import get_cacu_session
from persistance.db import get_cacu_session, get_cama_session
from webapi.patient_risk import patient_risk_blueprint
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(cama_survival_bp, url_prefix="/cama/supervivencia")
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
return app
+63 -7
View File
@@ -1,13 +1,18 @@
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
their promotion, notebooks run on a cohort build, 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`).
Notebooks (`models.pipelines.experiment`) run in the background on the build's
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
@@ -23,7 +28,7 @@ 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.pipelines import experiment
from models.reports import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
from persistance.settings import settings
@@ -84,6 +89,34 @@ 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.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."""
@@ -342,6 +375,29 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
return jsonify(updated)
@governance_bp.post("/eeg/run")
def run_eeg_analysis():
"""Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most
`limit` EEGs (5 by default), or every EEG with an EDF again with `all`. Larger batches are the indicator cycle's
or `python -m models tea analyze`'s. Rows already analysed with the current plan, modules and baselines are
skipped, so repeated calls are safe (VAR-09)."""
from models.eeg_analysis import analyze_pending
from webapi.orchestration.eeg import CLUSTERS, cluster as configured_cluster
body = request.get_json(silent=True) or {}
try:
limit = int(body.get("limit", 5))
except (TypeError, ValueError):
return jsonify({"error": "limit must be a whole number"}), 400
if limit < 1:
return jsonify({"error": "limit must be at least 1"}), 400
cluster = body.get("cluster") or configured_cluster()
if cluster not in CLUSTERS:
return jsonify({"error": f"cluster must be one of {', '.join(CLUSTERS)}"}), 400
summary = analyze_pending(everything=bool(body.get("all")), limit=limit, cluster=cluster)
return jsonify(asdict(summary))
@governance_bp.post("/ocr/run")
def run_ocr():
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
+12
View File
@@ -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
+187
View File
@@ -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."},
]
+108
View File
@@ -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
+202
View File
@@ -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}
+93
View File
@@ -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)
+49
View File
@@ -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
+168
View File
@@ -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
+195
View File
@@ -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'])))
+9
View File
@@ -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.
"""
+8
View File
@@ -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
+146
View File
@@ -0,0 +1,146 @@
"""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.
Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off.
"""
from dataclasses import dataclass
from datetime import date
from 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"
# 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),
)
class CohorteNoDisponible(RuntimeError):
"""The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503)."""
def disponible(sesion: Session) -> bool:
return inspect(sesion.get_bind()).has_table(CANDIDATOS.name)
@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
@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 cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
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),
))
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}"
+190
View File
@@ -0,0 +1,190 @@
"""The follow-up list and its file: the cohort at a cut-off, narrowed by a window and filters, in pages.
A selection of fewer patients than `comun.umbral_supresion` is never served: not as a page, not as a file, and not
through any combination of window and filters, which is what lets a small group be isolated. The whole cohort, with no
window and no filter, is the one selection that can be empty. The revision names the cohort, its version, the data it
stands on and the cut-off; a client that quotes another one is refused, so a page or a file always comes from the
cohort that was counted.
"""
import calendar
import hashlib
from datetime import date, timedelta
from sqlmodel import Session
from webapi.cama_follow_up.cohort import (
COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
disponible, grupos_de_edad,
)
from webapi.orchestration.reference.rules import valor_de
from webapi.orchestration.tables.cama import TABLAS
VENTANAS = (0, 1, 3, 6, 12)
VENTANA_POR_OMISION = 3
PAGINA_MAXIMA = 200
EXPORTACION_MAXIMA = 5000
GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"}
COLUMNAS = [
{"clave": "pac_id", "etiqueta": "Identificador de paciente"},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad"},
{"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]},
{"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]},
]
class PedidoInvalido(ValueError):
"""A parameter outside what the contract admits (400)."""
class RevisionDistinta(ValueError):
"""The cohort, scenario or revision quoted is not the one the server holds (409)."""
class GrupoPequeno(ValueError):
"""The selection has too few patients to be published (403)."""
class PaginaFuera(LookupError):
"""A page past the last one, with patients (404)."""
class ExportacionGrande(ValueError):
"""More patients than a file may hold (413)."""
def _desde(corte: date, meses: int) -> date:
indice = corte.year * 12 + corte.month - 1 - meses
anio, mes = divmod(indice, 12)
if anio < 1:
raise PedidoInvalido("la ventana excede el rango de fechas admitido")
anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1]))
return anterior + timedelta(days=1)
def revision_de(construido: str, corte: date) -> str:
"""The digest of the cohort, its version, its data and the cut-off."""
return hashlib.sha256(f"{COHORTE}|{VERSION}|{construido}|{corte.isoformat()}".encode()).hexdigest()
def filtros_disponibles(sesion: Session) -> list[dict]:
"""The filters the list offers, with every value it accepts."""
edades = [*grupos_de_edad(sesion), SIN_DATO]
return [
{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [
{"codigo": codigo_birads(b), "etiqueta": "BI-RADS " + b[1:]}
for b in valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS)]},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [
{"codigo": e, "etiqueta": "Sin dato" if e == SIN_DATO else e} for e in edades]},
{"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [
*({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()),
{"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"},
{"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]},
]
def _validar(sesion: Session, *, corte: date | None, meses: int | None, filtros: dict, hoy: date, page: int,
page_size: int) -> tuple[date, int, dict, list[dict]]:
meses = VENTANA_POR_OMISION if meses is None else meses
if meses not in VENTANAS:
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
corte = hoy if corte is None else corte
if corte > hoy:
raise PedidoInvalido(f"corte {corte.isoformat()} es posterior a hoy ({hoy.isoformat()}).")
disponibles = filtros_disponibles(sesion)
permitidos = {f["clave"]: {o["codigo"] for o in f["opciones"]} for f in disponibles}
for clave, valor in filtros.items():
if clave not in permitidos:
raise PedidoInvalido(f"filtro desconocido {clave!r}; hay {sorted(permitidos)}.")
if valor not in permitidos[clave]:
raise PedidoInvalido(f"{clave} desconocido: {valor!r}.")
return corte, meses, {c: filtros.get(c) for c in permitidos}, disponibles
def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict) -> tuple[list[Fila], date]:
desde = min((f.mastografia_fecha for f in cohorte), default=corte) if meses == 0 else _desde(corte, meses)
elegidas = [f for f in cohorte if desde <= f.mastografia_fecha <= corte
and all(valor is None or getattr(f, "resultado" if clave == "biopsia" else clave) == valor
for clave, valor in filtros.items())]
return elegidas, desde
def _item(f: Fila) -> dict:
return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads,
"mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia,
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None}
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
if not disponible(sesion):
raise CohorteNoDisponible("la cohorte aún no está disponible: falta correr el ciclo de indicadores de CaMa")
corte, meses, filtros, disponibles = _validar(sesion, corte=corte, meses=meses, filtros=filtros,
hoy=hoy or date.today(), page=page, page_size=page_size)
actual = revision_de(construccion(sesion), corte)
if any(contexto) and not all(contexto):
raise PedidoInvalido("el contexto de la cohorte lleva cohorte, escenario y revisión juntos.")
if any(contexto) and contexto != (COHORTE, ESCENARIO, actual):
raise RevisionDistinta("la cohorte, el escenario o la revisión no son los que sirve el servidor para este corte")
elegidas, desde = _selecciona(cohorte_al(sesion, corte), corte=corte, meses=meses, filtros=filtros)
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
acotada = meses != 0 or any(v is not None for v in filtros.values())
if (elegidas and len(elegidas) < umbral) or (acotada and not elegidas):
raise GrupoPequeno(f"la selección tiene menos de {umbral} pacientes: su lista no se publica.")
cabecera = {
"simulado": True, "cohorte": COHORTE, "escenario": ESCENARIO, "revision": actual, "corte": corte.isoformat(),
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
"filtros": filtros, "filtros_disponibles": disponibles, "columnas": COLUMNAS,
}
return cabecera, elegidas
def seguimiento_de(sesion: Session, *, corte: date | None = None, meses: int | None = None, filtros: dict | None = None,
cohorte: str | None = None, escenario: str | None = None, revision: str | None = None,
page: int = 1, page_size: int = 50, hoy: date | None = None) -> dict:
"""A page of the list, ready for `json.dumps`.
Raises:
PedidoInvalido: a parameter out of range or unknown.
RevisionDistinta: the context quoted is not the server's.
GrupoPequeno: the selection has fewer patients than the suppression threshold.
PaginaFuera: `page` past the last page, with patients.
"""
cabecera, elegidas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {}, hoy=hoy, page=page,
page_size=page_size, contexto=(cohorte, escenario, revision))
total = len(elegidas)
paginas = -(-total // page_size)
if total and page > paginas:
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
cabecera["paginacion"] = {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas}
cabecera["items"] = [_item(f) for f in elegidas[(page - 1) * page_size: page * page_size]]
return cabecera
def paciente_de(sesion: Session, pac_id: str, *, corte=None, meses=None, filtros=None,
cohorte=None, escenario=None, revision=None, page=1, page_size=50) -> dict:
"""dev's individual route, after the same full-selection suppression and revision checks."""
cabecera, filas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {},
contexto=(cohorte, escenario, revision), hoy=None, page=page, page_size=page_size)
fila = next((f for f in filas if str(f.pac_id) == pac_id), None)
if fila is None:
raise PaginaFuera('Paciente no encontrado en la selección')
return {**cabecera, 'item': _item(fila)}
def exportacion_de(sesion: Session, *, corte: date | None = None, meses: int | None = None, filtros: dict | None = None,
cohorte: str | None = None, escenario: str | None = None, revision: str | None = None,
hoy: date | None = None) -> dict:
"""Every row of the selection, with the same header, selection rules and context as the list.
Raises:
ExportacionGrande: more than `EXPORTACION_MAXIMA` patients.
"""
cabecera, elegidas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {}, hoy=hoy, page=1,
page_size=1, contexto=(cohorte, escenario, revision))
if len(elegidas) > EXPORTACION_MAXIMA:
raise ExportacionGrande(f"la exportación admite hasta {EXPORTACION_MAXIMA} pacientes; la selección tiene {len(elegidas)}.")
cabecera["total_items"] = len(elegidas)
cabecera["items"] = [_item(f) for f in elegidas]
return cabecera
+113
View File
@@ -0,0 +1,113 @@
"""The routes of CaMa's follow-up list: `GET /cama/seguimiento` and `GET /cama/seguimiento/exportacion`."""
import json
import re
from collections.abc import Callable
from datetime import date
from flask import Blueprint, Response, current_app, jsonify, request
from sqlmodel import Session
from webapi.cama_follow_up.cohort import CohorteNoDisponible
from webapi.cama_follow_up.access import configured_access
from webapi.cama_follow_up.listing import (
ExportacionGrande, GrupoPequeno, PaginaFuera, PedidoInvalido, RevisionDistinta, exportacion_de, seguimiento_de, paciente_de,
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
"""The blueprint of the list and its file, to register with `url_prefix="/cama"`."""
blueprint = Blueprint("cama_seguimiento", __name__)
blueprint.before_request(configured_access)
@blueprint.after_request
def no_store(response):
response.headers["Cache-Control"] = "no-store"
return response
def answer(build, admitidos: tuple[str, ...], legacy_mode=None, patient=None):
reader = current_app.config.get('CAMA_COHORT_READER')
if legacy_mode and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
from webapi.cama_analysis_legacy import SelectionError, selection_response
try:
return selection_response(request.args, legacy_mode, patient)
except SelectionError as error:
return jsonify(error=error.message), error.status
try:
pedido = _requested(request.args, admitidos)
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 PaginaFuera as error:
return jsonify({"error": str(error)}), 404
except RevisionDistinta as error:
return jsonify({"error": str(error), "motivo": "revision"}), 409
except ExportacionGrande as error:
return jsonify({"error": str(error)}), 413
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")
@blueprint.get("/seguimiento")
def get_seguimiento():
"""The BI-RADS cohort's follow-up list at a cut-off, one page."""
return answer(seguimiento_de, ("corte", *ENTEROS, *CONTEXTO, *FILTROS), 'list')
@blueprint.get("/seguimiento/exportacion")
def get_exportacion():
"""Every row of the same selection, for a file."""
return answer(exportacion_de, ("corte", "meses", *CONTEXTO, *FILTROS), 'export')
@blueprint.get('/pacientes/<pac_id>')
def paciente(pac_id):
return answer(lambda session, **pedido: paciente_de(session, pac_id, **pedido),
('corte', *ENTEROS, *CONTEXTO, *FILTROS), 'patient', pac_id)
return blueprint
def _requested(args, admitidos: tuple[str, ...]) -> dict:
"""The query's parameters, typed. `ValueError` for an unknown, repeated or badly written one."""
for nombre in args:
if nombre not in admitidos:
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos)}.")
if len(args.getlist(nombre)) > 1:
raise ValueError(f"parámetro repetido {nombre!r}.")
pedido: dict = {}
if (corte := args.get("corte")) is not None:
if not FECHA.fullmatch(corte):
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
try:
pedido["corte"] = date.fromisoformat(corte)
except ValueError:
raise ValueError(f"corte {corte!r} no es una fecha") from None
for nombre in ENTEROS:
if nombre in args:
if not re.fullmatch(r"\d{1,6}", args[nombre]):
raise ValueError(f"{nombre} debe ser un entero; llegó {args[nombre]!r}")
pedido[nombre] = int(args[nombre])
contexto = {n: args[n] for n in CONTEXTO if n in args}
if contexto and len(contexto) != len(CONTEXTO):
raise ValueError(f"el contexto de la cohorte lleva {list(CONTEXTO)} juntos.")
if any(not v for v in contexto.values()):
raise ValueError("el contexto de la cohorte no puede ir vacío.")
pedido.update(contexto)
filtros = {n: args[n] for n in FILTROS if n in args}
if any(not v for v in filtros.values()):
raise ValueError("un filtro no puede ir vacío.")
if filtros:
pedido["filtros"] = filtros
return pedido
View File
+42
View File
@@ -0,0 +1,42 @@
"""`/cama/recurrencia`: the scenarios of each cohort, the figure of one and the scenarios a patient meets."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_recurrence import service
cama_recurrence_bp = Blueprint("cama_recurrence", __name__)
@cama_recurrence_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_recurrence_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_recurrence_bp.get("/figura")
def figure():
cohort = request.args.get("cohorte", "").strip()
scenario = request.args.get("escenario", "").strip()
if not cohort or not scenario:
raise BadRequest("faltan los parámetros «cohorte» y «escenario»")
try:
return jsonify(service.figure(cohort, scenario))
except service.Calculating:
return jsonify({"estado": "calculando"}), 202
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}» en la cohorte «{cohort}»")
except LookupError:
raise NotFound(f"el escenario «{scenario}» no tiene recaídas suficientes para dibujarse")
@cama_recurrence_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+183
View File
@@ -0,0 +1,183 @@
"""CaMa's recurrence analysis over the live cohort build.
Each cohort (METABRIC, SCAN-B) is recoded from the latest build of `cama/cohorte_total` by the dictionary of
`models.cama.recurrence`. Its covariates, the terms of each horizon and the bootstrap of the combined estimate are
computed once per build, in the background, and kept on disk; a scenario's figure is computed when it is asked for and kept
in memory. A new build computes them again.
"""
import hashlib
import pickle
import tempfile
import threading
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.recurrence import analysis, cohort as recurrence_cohort
from models.io.storage import KitBuild
DOMAIN, COHORT = "cama", "cama/cohorte_total"
CACHE_DIR = Path(tempfile.gettempdir()) / "cama_recurrence"
class NotAvailable(LookupError):
"""There is no cohort build to draw on."""
class Calculating(RuntimeError):
"""The cohort's models and bootstrap are still being computed."""
@dataclass
class CohortState:
name: str
frame: pd.DataFrame
scenarios: list[dict]
masks: dict
status: str = "calculando"
error: str | None = None
covariates: list[str] = field(default_factory=list)
dropped: list[str] = field(default_factory=list)
models: dict = field(default_factory=dict)
point: dict = field(default_factory=dict)
draws: dict = field(default_factory=dict)
figures: dict = field(default_factory=dict)
@dataclass
class Live:
build_id: int
model: dict
events: pd.DataFrame
cohorts: dict[str, CohortState]
_lock = threading.RLock()
_live: Live | None = None
def _cache_file(build_id: int, name: str, model_text: str, members: int) -> Path:
key = hashlib.sha256(f"{build_id}|{name}|{members}|{model_text}".encode()).hexdigest()[:20]
return CACHE_DIR / f"{name}-{key}.pkl"
def _compute(state: CohortState, model: dict, cache: Path) -> None:
try:
if cache.is_file():
with cache.open("rb") as handle:
saved = pickle.load(handle)
else:
settings, calculator = model["modeling"], model["calculator"]
horizons = model["config"]["horizons_months"]
cfg = model["cohorts"][state.name]
covariates, dropped = analysis.prune_covariates(state.frame, cfg["covariates"], cfg["treatment"], settings)
models = analysis.select_models(state.frame, covariates, horizons, settings)
calc = analysis.Calculator(state.frame, covariates, models, horizons, settings["bdeu_ess"])
point = calc.risk(np.arange(calc.n), state.masks)
draws = calc.bootstrap(state.masks, calculator["bootstrap_replicas"], settings["seed"])
saved = {"covariates": covariates, "dropped": dropped, "models": models, "point": point, "draws": draws}
CACHE_DIR.mkdir(parents=True, exist_ok=True)
with cache.open("wb") as handle:
pickle.dump(saved, handle)
with _lock:
state.covariates, state.dropped, state.models = saved["covariates"], saved["dropped"], saved["models"]
state.point, state.draws, state.status = saved["point"], saved["draws"], "listo"
except Exception as error: # the cohort reports its failure; the others keep working
with _lock:
state.status, state.error = "error", f"{type(error).__name__}: {error}"
def live() -> Live:
"""The latest build's cohorts; recoded again only when the build changed."""
global _live
repositories = import_module(f"persistance.{DOMAIN}")
build_id = repositories.cohort_repository.latest_build(COHORT)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el análisis de recurrencia")
with _lock:
if _live is not None and _live.build_id == int(build_id):
return _live
model = recurrence_cohort.load()
model_text = recurrence_cohort.TOML.read_text(encoding="utf-8")
events = KitBuild(DOMAIN, int(build_id)).frame()
cohorts = {}
for name, cfg in model["cohorts"].items():
frame = recurrence_cohort.recode(events, model, name)
if frame.empty:
continue
scenarios = cfg["scenarios"]
state = CohortState(name, frame, scenarios, analysis.scenario_masks(frame, scenarios))
cohorts[name] = state
cache = _cache_file(int(build_id), name, model_text, len(frame))
threading.Thread(target=_compute, args=(state, model, cache), daemon=True).start()
_live = Live(int(build_id), model, events, cohorts)
return _live
def _cohort(current: Live, name: str) -> CohortState:
if name not in current.cohorts:
raise KeyError(name)
return current.cohorts[name]
def scenarios() -> dict:
current = live()
minimum = current.model["calculator"]["min_events"]
cohorts = []
for name, state in current.cohorts.items():
rows = []
for scenario in state.scenarios:
mask = state.masks[scenario["name"]]
events = int(state.frame.loc[mask, "evento"].sum())
rows.append({"nombre": scenario["name"], "condiciones": scenario["when"], "n": int(mask.sum()),
"recaidas": events, "dibujable": events >= minimum})
cohorts.append({"id": name, "nombre": current.model["cohorts"][name]["name"], "estado": state.status,
"error": state.error, "escenarios": rows})
return {"build": current.build_id, "horizontes": current.model["config"]["horizons_months"], "cohortes": cohorts}
def figure(cohort: str, scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for an unknown cohort or scenario, `Calculating` while the cohort
is being computed, `LookupError` when the scenario has too few recurrences to be drawn."""
current = live()
state = _cohort(current, cohort)
if scenario not in state.masks:
raise KeyError(scenario)
with _lock:
if state.status == "calculando":
raise Calculating(cohort)
if state.status == "error":
raise RuntimeError(state.error)
if scenario not in state.figures:
figure_record = analysis.scenario_figure(
state.frame, scenario, state.masks[scenario], state.point[scenario], state.draws[scenario],
current.model["config"]["horizons_months"], current.model["calculator"])
if figure_record is None:
raise LookupError(scenario)
state.figures[scenario] = {"cohorte": cohort, "cohorte_nombre": current.model["cohorts"][cohort]["name"],
"condiciones": next(s["when"] for s in state.scenarios if s["name"] == scenario),
"build": current.build_id, **figure_record}
return state.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient's covariates meet in each cohort; one that needs a covariate she lacks does not include her."""
current = live()
events = current.events[current.events["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
found = []
# The analysis is for patients after treatment: those whose timeline holds the post-treatment scenario.
if not (events["tipo"] == "escenario_postratamiento").any():
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": False, "escenarios": found}
for name, state in current.cohorts.items():
recoded = recurrence_cohort.recode(events, current.model, name, of_source=False, follow_up=False)
if recoded.empty:
continue
masks = analysis.scenario_masks(recoded, state.scenarios)
found += [{"cohorte": name, "escenario": n} for n, mask in masks.items() if bool(mask[0])]
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": True, "escenarios": found}
+16
View File
@@ -0,0 +1,16 @@
"""Configure the breast cohort using the shared persistence settings."""
from persistance.db import get_cama_session
from webapi.cama_cohort import CamaCohort
def configure_cama_cohort(app):
def read(cutoff):
with get_cama_session() as session:
return CamaCohort(session).rows(cutoff)
read._cama_default_reader = True
# Distinguish the historical default from an explicit integration override.
# Normal create_app uses L1-L3; consumers that replace the callback keep dev's contract.
read._cama_default_reader = True
app.config['CAMA_COHORT_READER'] = read
+5
View File
@@ -0,0 +1,5 @@
"""CaMa's survival figures over the model in production.
service.py the production model and the live cohort, a scenario's figure and a patient's scenarios, cached
routes.py the routes: `/cama/supervivencia/...`
"""
+37
View File
@@ -0,0 +1,37 @@
"""`/cama/supervivencia`: the survival figure of a clinical scenario and the scenarios of a patient."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_survival import service
cama_survival_bp = Blueprint("cama_survival", __name__)
@cama_survival_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_survival_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_survival_bp.get("/figura")
def figure():
scenario = request.args.get("escenario", "").strip()
if not scenario:
raise BadRequest("falta el parámetro «escenario»")
try:
return jsonify(service.figure(scenario))
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}»")
@cama_survival_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+124
View File
@@ -0,0 +1,124 @@
"""The production CaMa survival model over the live cohort build.
A scenario's figure is computed on request from the production version of `cama/seer_survival` and the latest build of its
cohort, and kept per (model version, cohort build, scenario): a new version or a new build computes it again. The saved model
is rehydrated with the current class before it scores (`SeerSurvivalModel.rehydrate`).
"""
import os
import pickle
import threading
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
import mlflow.sklearn
import pandas as pd
from models.cama.seer_survival import seer_model
from models.dags.training import Scenario
from models.io.registry import registry
from models.io.storage import KitBuild
DOMAIN, SCENARIO = "cama", "seer_survival"
class NotAvailable(LookupError):
"""There is no production version, or no cohort build to draw on."""
class SavedFile:
"""The model saved as a file (`CAMA_SURVIVAL_MODEL`), versioned by its modification time."""
def __init__(self, path: str):
self.path = Path(path)
self.version = f"archivo-{int(self.path.stat().st_mtime)}"
def load(self):
with self.path.open("rb") as handle:
return pickle.load(handle)
@dataclass
class Live:
"""The model of the production version and the live build's members, recoded once for both."""
version: str
build_id: int
model: seer_model.SeerSurvivalModel
cohort: pd.DataFrame
frame: object
figures: dict
_lock = threading.RLock()
_live: Live | None = None
def _resolve() -> tuple[str, int, object]:
scenario = Scenario.load(DOMAIN, SCENARIO)
repositories = import_module(f"persistance.{DOMAIN}")
file = os.environ.get("CAMA_SURVIVAL_MODEL")
if file:
if not Path(file).is_file():
raise NotAvailable("no hay un modelo de supervivencia guardado")
resolved = SavedFile(file)
else:
try:
resolved = registry.resolve(DOMAIN, SCENARIO)
except LookupError as error:
raise NotAvailable("no hay una versión del modelo de supervivencia en producción") from error
build_id = repositories.cohort_repository.latest_build(scenario.cohort)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el modelo de supervivencia")
return resolved.version, int(build_id), resolved
def live() -> Live:
"""The production version over the latest build; loaded again only when either changed."""
global _live
version, build_id, resolved = _resolve()
with _lock:
if _live is None or (_live.version, _live.build_id) != (version, build_id):
saved = resolved.load() if isinstance(resolved, SavedFile) else mlflow.sklearn.load_model(resolved.model_uri)
model = seer_model.SeerSurvivalModel.rehydrate(saved)
cohort = KitBuild(DOMAIN, build_id).frame()
recoded = model.recode(cohort)
_live = Live(version, build_id, model, cohort, model.frame(recoded), {})
return _live
def scenarios() -> dict:
current = live()
return {"model_version": current.version, "build": current.build_id, "scenarios": current.model.scenario_names()}
def figure(scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for a scenario the model doesn't define."""
current = live()
if scenario not in current.model.scenario_names():
raise KeyError(scenario)
with _lock:
if scenario not in current.figures:
settings = seer_model.figure_settings()
current.figures[scenario] = {
"model_version": current.version, "build": current.build_id,
**current.model.figure_record(
current.frame, scenario, ks_max_seconds=settings["ks_max_seconds"], n_boot=settings["n_boot"],
min_members=settings["min_members"], min_deaths=settings["min_deaths"])}
return current.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient belongs to, from her variables over the timeline (age, stage, subtype, surgery)."""
current = live()
events = current.cohort[current.cohort["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
model = current.model
recoded = model.recode(events)
names = []
if len(recoded):
masks = model.scenario_masks(model.frame(recoded))
names = [name for name, mask in masks.items() if bool(mask[0])]
return {"model_version": current.version, "build": current.build_id, "pac_id": pac_id, "scenarios": names}
+83
View File
@@ -0,0 +1,83 @@
"""dbt's manifest for the deployment's engine.
The measures are served from `manifest.json` (`DBT_MANIFEST`), whose compiled SQL is the dialect of the dbt target it
was compiled with. The image ships SQLite's; on another engine the entrypoint runs this module, which compiles the
project in `TRANSFORMATION_DIR` against the configured databases (the adapters for MySQL, PostgreSQL and SQL Server
open a connection to compile) and prints the path of the manifest to serve. On SQLite it prints nothing: the image's
manifest is the right one.
The three domains must share one engine: one manifest covers every domain's models.
"""
import os
import subprocess
import sys
from pathlib import Path
from sqlalchemy.engine import make_url
DOMAINS = ("cacu", "cama", "tea")
TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
def target_of(urls: dict[str, str]) -> str:
"""The dbt target the domains' database URLs share. `ValueError` for an engine dbt has no target for, or when
the domains don't share one engine."""
targets = {domain: TARGETS.get(make_url(url).get_backend_name()) for domain, url in urls.items()}
if unknown := [domain for domain, target in targets.items() if target is None]:
raise ValueError(f"no dbt target for the engine of {', '.join(unknown)}")
if len(set(targets.values())) != 1:
raise ValueError("the domains' databases must be on one engine: one manifest serves the three domains")
return next(iter(targets.values()))
def environment(urls: dict[str, str], target: str) -> dict[str, str]:
"""What `Transformation/profiles.yml` reads: the server and credentials from CaCu's URL (one server for the three
domains), each domain's database name, and on SQLite each domain's file."""
env: dict[str, str] = {}
for domain, url in urls.items():
parsed = make_url(url)
if target == "sqlite":
env[f"{domain.upper()}_DB_PATH"] = parsed.database or f"{domain}.db"
else:
env[f"{domain.upper()}_DBT_DATABASE"] = parsed.database or domain
first = make_url(urls["cacu"])
if target != "sqlite":
env["DBT_HOST"] = first.host or "localhost"
if first.port:
env["DBT_PORT"] = str(first.port)
env["DBT_USER"] = first.username or ""
env["DBT_PASSWORD"] = first.password or ""
return env
def dbt_executable(root: Path, target: str) -> Path:
"""dbt-mysql runs on an older dbt-core, so it lives in its own environment next to the main one."""
return root / (".venv-mysql" if target == "mysql" else ".venv") / "bin" / "dbt"
def compile_manifest(root: Path, target: str, env: dict[str, str], out_dir: Path) -> Path:
"""Compiles every model with placeholders for the question's parameters (`--no-introspect`: the target's
tables needn't exist yet) and returns the manifest's path."""
out_dir.mkdir(parents=True, exist_ok=True)
command = [str(dbt_executable(root, target)), "compile", "--project-dir", str(root), "--profiles-dir", str(root),
"--profile", "cacu", "--target", target, "--no-introspect", "--target-path", str(out_dir)]
subprocess.run(command, check=True, env={**os.environ, **env}, stdout=sys.stderr)
return out_dir / "manifest.json"
def main() -> int:
from persistance.settings import settings
urls = {domain: getattr(settings, f"{domain}_database_url") for domain in DOMAINS}
target = target_of(urls)
if target == "sqlite":
return 0
root = Path(os.environ.get("TRANSFORMATION_DIR") or Path(__file__).resolve().parents[2] / "Transformation")
out_dir = Path(os.environ.get("DBT_MANIFEST_DIR", "/data/dbt"))
print(compile_manifest(root, target, environment(urls, target), out_dir))
return 0
if __name__ == "__main__":
sys.exit(main())
+38 -6
View File
@@ -1,4 +1,5 @@
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA and CaCu, its patients' screening and
individual risk.
GET metadata CapabilityStatement
GET Measure, Measure/<id> the measures (dbt's definitions)
@@ -8,6 +9,7 @@
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's individual risk, the current batch (DEV only)
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
@@ -36,6 +38,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
blueprint = Blueprint(f"{project}_fhir", __name__)
titles = labels(manifest)
patients = with_patients and project == "tea"
risks = with_patients and project == "cacu"
def definitions() -> dict:
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
@@ -80,6 +83,9 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
"definition": canonical("OperationDefinition/resumen-tea")}]},
{"type": "ValueSet", "interaction": [{"code": "read"}]},
]
if risks:
resources += [{"type": "RiskAssessment", "interaction": [{"code": "search-type"}],
"searchParam": [{"name": "subject", "type": "reference"}]}]
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
@@ -169,9 +175,31 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
if patients:
_patient_routes(blueprint, repositories, now)
if risks:
_risk_routes(blueprint, repositories)
return blueprint
def _risk_routes(blueprint: Blueprint, repositories) -> None:
"""CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from webapi.fhir import cacu
@blueprint.get("/RiskAssessment")
def risk_assessments():
subject = request.args.get("subject", "")
reference = subject.removeprefix("Patient/")
if not reference.isdigit():
return outcome(400, "invalid", "falta `subject=Patient/<pac_id>`: el riesgo se busca por paciente")
try:
count, offset = page()
except ValueError as error:
return outcome(400, "invalid", str(error))
pac_id = int(reference)
risk = repositories.cohort_repository.current_risk(pac_id)
found = [] if risk is None else [cacu.risk_assessment(pac_id, risk, simulated_data())]
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
def _period_asked(repositories):
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
if periodo := request.args.get("periodo"):
@@ -342,13 +370,17 @@ def tea_outcome(status: int, code: str, error: Exception):
def _included(tea, queries, e, simulated: bool) -> list[dict]:
"""What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG."""
"""What an episode's search includes: its patient, its steps, its M-CHAT, its ADOS-2, its diagnosis and its study
EEG."""
from sqlalchemy import select
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"]))
resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated),
pac_id = e.child["pac_id"]
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == pac_id))
ados2 = tea.ados2_observation(tea._rows(queries, select(tea.ADOS2).where(tea.ADOS2.c.pac_id == pac_id)),
e.pseudonym, simulated)
resources = [tea.patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated),
tea.care_plan(e, simulated)]
resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r]
resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r]
if (eeg := e.study_eeg()) is not None:
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks)
return resources
+62
View File
@@ -0,0 +1,62 @@
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data).
The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed
evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient:
id `<lote_id>-<pac_id>`
status the batch's state (`final`)
subject `Patient/<pac_id>`: CaCu's follow-up list uses the platform's `pac_id` (TEA keeps a
pseudonym until its patients get their own identity)
occurrenceDateTime when the batch was evaluated
method the registered model and its version (MLflow)
prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod`
from the risk's index date (the model's decision point) to that date plus the horizon;
the immediate risk (horizon 0) is a period of one day. A confidence interval, when the
model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a
decimal or a range, not both).
Not yet: `basis` (CaCu doesn't publish its cytology and HPV `Observation`s) and `mitigation` (ASCCP's clinical
action thresholds are for CIN3+; the outcome here is CIN2+).
"""
from datetime import date, datetime, timedelta, timezone
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
OUTCOME = f"{CODE_SYSTEM}/desenlace"
MODEL = f"{CODE_SYSTEM}/modelo"
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"}
DAYS_PER_YEAR = 365.25
def _utc(moment: datetime) -> str:
moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _until(start: date, years: float) -> date:
return start + timedelta(days=round(years * DAYS_PER_YEAR))
def _prediction(horizon, outcome: dict, start: date | None) -> dict:
item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad}
if start is not None:
item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()}
if horizon.ic_bajo is not None and horizon.ic_alto is not None:
item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo},
"high": {"value": horizon.ic_alto}}}]
return item
def risk_assessment(pac_id: int, risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`."""
desenlace = risk.desenlace or "cin2_mas"
outcome = concept(OUTCOME, desenlace, OUTCOMES.get(desenlace))
resource = {
"resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote,
"subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en),
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
}
return tagged(resource, simulated)
+27 -3
View File
@@ -1,7 +1,9 @@
"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with
their paging links, the simulated-data tag and the project's canonical URLs."""
their paging links, the simulated-data tag and the project's canonical URLs. Every answer is validated against FHIR's
R4B models (`fhir.resources`, the models the EEG analysis validates its own report with) before it leaves."""
import json
import logging
import os
from urllib.parse import urlencode
@@ -17,10 +19,32 @@ SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display":
MAX_COUNT = 200
DEFAULT_COUNT = 50
log = logging.getLogger(__name__)
def validated(resource: dict) -> dict:
"""The resource as FHIR's R4B models read it and write it back (R4B keeps R4's shape for these resources).
`ValueError` if it doesn't conform."""
from fhir.resources.R4B import get_fhir_model_class
try:
model = get_fhir_model_class(resource["resourceType"])
except KeyError as exc:
raise ValueError(f"no FHIR resource type {resource.get('resourceType')!r}") from exc
return model.model_validate(resource).model_dump(mode="json", exclude_none=True)
def fhir(resource: dict, status: int = 200) -> Response:
"""A resource as the answer, in FHIR's JSON media type."""
return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
"""A resource as the answer, in FHIR's JSON media type. One that doesn't conform to FHIR never leaves: the answer
is then a 500 `OperationOutcome`, and the reason goes to the log."""
try:
body = validated(resource)
except ValueError:
if resource.get("resourceType") == "OperationOutcome":
raise
log.exception("a %s answer doesn't conform to FHIR R4B", resource.get("resourceType"))
return outcome(500, "exception", "la respuesta no es un recurso FHIR válido")
return Response(json.dumps(body, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
+88 -45
View File
@@ -6,27 +6,22 @@ stage the furthest step reached by the cut-off (`type`, with its date as an exte
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`):
Until the domain expert validates the age baselines, every alteration stays hidden (`alterations_validated`):
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
"""
import hashlib
import os
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
from webapi.follow_up.listing import seudonimo
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
("EEG", "fecha_eeg", "EEG de buena calidad"))
CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"),
("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"),
("calidad_correlacion", "Baja correlación entre canales", "canales"),
("calidad_sin_senal", "Canales planos o sin señal", "canales"),
("calidad_linea", "Ruido de la línea eléctrica", "dB"))
ALTERED = ("aumentado", "disminuido")
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
@@ -40,12 +35,16 @@ FOLLOW_UP = table("tea_seguimiento", *map(column, (
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
EEGS = table("tea_paciente_eegs", *map(column, (
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido",
*(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno")))))
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "nivel", "fraccion_limpia",
"canales_malos", "ruido_linea_db", "calidad", "valido")))
CHECKS = table("tea_paciente_eeg_criterios", *map(column, (
"procedimiento_id", "pac_id", "criterio", "electrodo", "valor", "valor_texto", "bajo", "alto", "anormal",
"decisivo", "etiqueta", "unidad")))
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "valor_z",
"estado")))
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
"valor")))
"valor", "valor_z")))
ADOS2 = table("tea_paciente_ados2", *map(column, (
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
"etiqueta", "puntaje", "puntaje_algoritmo")))
@@ -53,7 +52,7 @@ PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
def alterations_validated() -> bool:
"""Whether the domain expert validated the reference ranges, effect texts and quality thresholds
"""Whether the domain expert validated the EEG analysis's age baselines and the effect texts
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
@@ -62,6 +61,12 @@ def salt() -> str:
return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT)
def seudonimo(pac_id: int, sal: str) -> str:
"""TEA's patient and episode ids: stable for a salt, without saying the `pac_id`. CaCu's follow-up list moved
to the platform's `pac_id`; TEA keeps the pseudonym until its patient resources get their own identity."""
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
def _date(value) -> date | None:
if value is None or isinstance(value, date):
return value
@@ -81,6 +86,7 @@ class Episode:
cutoff: date
eegs: list[dict]
metrics: list[dict]
checks: list[dict] = field(default_factory=list)
@property
def pseudonym(self) -> str:
@@ -142,17 +148,16 @@ class Episode:
def episodes(queries, cutoff: date) -> list[Episode]:
"""Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics."""
eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS))
eegs, metrics, checks = (_rows(queries, select(EEGS)), _rows(queries, select(METRICS)),
_rows(queries, select(CHECKS)))
by_child = {}
for child in _rows(queries, select(FOLLOW_UP)):
if (_date(child["fecha_mchat"]) or date.max) <= cutoff:
by_child[child["pac_id"]] = Episode(child, cutoff, [], [])
for eeg in eegs:
if eeg["pac_id"] in by_child:
by_child[eeg["pac_id"]].eegs.append(eeg)
for metric in metrics:
if metric["pac_id"] in by_child:
by_child[metric["pac_id"]].metrics.append(metric)
for rows, kind in ((eegs, "eegs"), (metrics, "metrics"), (checks, "checks")):
for row in rows:
if row["pac_id"] in by_child:
getattr(by_child[row["pac_id"]], kind).append(row)
return list(by_child.values())
@@ -223,26 +228,47 @@ def condition(e: Episode, simulated: bool) -> dict | None:
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]:
def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulated: bool) -> list[dict]:
"""One `Observation` per quality check the EEG analysis evaluated, as the analysis's own validation report writes
it (`tea.validation.fhir`): its code in the analysis's code system, its value (a quantity or a text), whether it
was abnormal (A/N), its limit as the reference range, and as components the bad channel's electrode and whether
the check alone can make the EEG not valid. Study-wide checks first, then the bad channels by electrode."""
from tea.validation.fhir import INTERP, SYSTEM
observations = []
for name, label, unit in CRITERIA:
if eeg[name] is None:
continue
value = ({"valueInteger": int(eeg[name])} if unit == "canales"
else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}})
observations.append(tagged({
"resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": concept(CATALOG, f"eeg.{name}", label),
mine = [c for c in checks if c["procedimiento_id"] == eeg["procedimiento_id"]]
for c in sorted(mine, key=lambda c: (c["electrodo"] is not None, c["electrodo"] or "", c["criterio"])):
code, unit = c["criterio"].replace("_", "-"), c["unidad"]
quantity = (lambda v: {"value": float(v), **({"unit": unit} if unit else {})})
resource = {
"resourceType": "Observation",
"id": "-".join(p for p in ("calidad", code, c["electrodo"], str(eeg["procedimiento_id"])) if p),
"status": "final", "code": {"coding": [coding(SYSTEM, code, c["etiqueta"] or code)],
"text": c["etiqueta"] or code},
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
**value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")],
}, simulated))
"interpretation": [concept(INTERP, "A" if c["anormal"] else "N")],
}
if c["valor"] is not None:
resource["valueQuantity"] = quantity(c["valor"])
elif c["valor_texto"] is not None:
resource["valueString"] = c["valor_texto"]
limits = {k: quantity(c[v]) for k, v in (("low", "bajo"), ("high", "alto")) if c[v] is not None}
if limits:
resource["referenceRange"] = [limits]
resource["component"] = [
*([{"code": {"text": "electrode"}, "valueString": c["electrodo"]}] if c["electrodo"] else []),
{"code": {"text": "decisive"}, "valueBoolean": bool(c["decisivo"])},
]
observations.append(tagged(resource, simulated))
return observations
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
simulated: bool) -> list[dict]:
"""One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or
why it couldn't be evaluated) and one per metric with a component per electrode."""
"""One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's
observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG
as the reference, H/L/N, and the z and the baseline's median as components. A value without a z is a metric the
baseline couldn't score (none in production, or an age it doesn't cover): no interpretation."""
from webapi.fhir.terminology import TEA_EEG
observations = []
@@ -252,35 +278,42 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()}
if m["valor"] is None or m["valor_z"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown")
if m["valor"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed")
else:
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
if m["valor"] is not None and m["valor_z"] is not None:
resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get(
m["estado"], "N"))]
resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"),
"valueQuantity": {"value": round(float(m["valor_z"]), 2)}}]
if m["ref_mediana"] is not None:
resource["component"].append({
"code": concept(f"{CODE_SYSTEM}/puntaje", "mediana", "Mediana de la referencia a la edad"),
"valueQuantity": {"value": float(m["ref_mediana"]), "unit": spec["unidad"]}})
if m["ref_min"] is not None:
resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]},
"high": {"value": float(m["ref_max"]), "unit": spec["unidad"]},
"text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}]
observations.append(tagged(resource, simulated))
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]]
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]
and x["valor_z"] is not None]
if at:
observations.append(tagged({
"resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]),
"valueQuantity": {"value": float(x["valor"])}}
"valueQuantity": {"value": round(float(x["valor_z"]), 2)}}
for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated))
return observations
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]:
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
checks: list[dict] = ()) -> list[dict]:
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
no result beyond its quality, and the alterations stay out until validated."""
quality = quality_observations(eeg, pseudonym, simulated)
quality = quality_observations(eeg, list(checks), pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
if eeg["valido"] == 1 and alterations_validated() else [])
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
@@ -292,14 +325,21 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered],
"conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]}
if eeg["calidad"] != "SIN_ANALIZAR":
from tea.validation.fhir import SYSTEM
report["conclusionCode"].append(concept(SYSTEM, "valid" if eeg["valido"] == 1 else "not-valid"))
if eeg["duracion_min"] is not None or eeg["canales"] is not None:
report["extension"] = [e for e in (
{"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])}
if eeg["duracion_min"] is not None else None,
{"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
) if e]
if eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio."
if eeg["calidad"] == "SIN_ANALIZAR":
report["conclusion"] = "EEG sin analizar todavía: no es válido para el estudio."
elif eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio" + (
f" (nivel de triaje: {eeg['nivel']})." if eeg["nivel"] else ".")
return [procedure, tagged(report, simulated), *quality, *altered]
@@ -335,7 +375,8 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
"""The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today."""
"""The `$resumen-tea` collection: the patient, its screening episode (with its age group), its first ADOS-2 and
the EEG the study uses, as of today."""
pseudonym = seudonimo(pac_id, salt())
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
@@ -344,9 +385,11 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
if child is not None:
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)))
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)),
_rows(queries, select(CHECKS).where(CHECKS.c.pac_id == pac_id)))
resources.append(episode_of_care(e, simulated))
eeg = e.study_eeg()
if eeg is not None:
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated)
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks)
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
+9 -4
View File
@@ -1,33 +1,38 @@
# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where
# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`.
# TEA's EEG vocabulary for the FHIR answers: what each metric's state may mean (`efectos`, by state), and where each
# 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
# The effect texts are placeholders pending the domain expert's review, like the age baselines they go with.
[metricas.ritmo_posterior]
etiqueta = "Ritmo posterior"
unidad = "Hz"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."]
[metricas.husos_sueno_n2]
etiqueta = "Husos de sueño N2"
unidad = "husos/min"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
[metricas.husos_sueno_n3]
etiqueta = "Husos de sueño N3"
unidad = "husos/min"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
[metricas.picos_paroxisticos]
etiqueta = "Picos paroxísticos"
unidad = "picos/min"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."]
[metricas.gradiente_anteroposterior]
etiqueta = "Gradiente anteroposterior"
unidad = "razón posterior/anterior"
unidad = "pendiente"
efectos.normal = ["Dentro de lo esperado para la edad."]
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."]
+17 -3
View File
@@ -1,6 +1,7 @@
"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's
catalog (`core/catalogos/<domain>.toml`: studies, results and their values), TEA's screening stages and diagnostic
results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`)."""
results, TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under
the analysis's own code system with the catalog's labels."""
import tomllib
from pathlib import Path
@@ -38,6 +39,18 @@ def catalog(domain: str) -> dict:
return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True)
def eeg_checks() -> dict:
"""The EEG analysis's quality checks (`CriterioEeg`), under the code system its validation report uses, each with
the catalog's label of its `eeg.calidad_<check>` result."""
from core.tea.enums import CriterioEeg
from tea.validation.fhir import SYSTEM
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["eeg"]["resultados"]
concepts = [{"code": c.value, "display": results[f"calidad_{c.value.replace('-', '_')}"]["etiqueta"]}
for c in CriterioEeg]
return {**_code_system("tea-eeg-criterio", "Reglas de calidad del EEG", concepts), "url": SYSTEM}
def tea_code_systems() -> dict[str, dict]:
metrics = [{"code": code, "display": spec["etiqueta"], "property": [
{"code": "unidad", "valueString": spec["unidad"]},
@@ -48,8 +61,9 @@ def tea_code_systems() -> dict[str, dict]:
_code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]),
_code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]),
{**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics),
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"},
{"code": "efecto-disminuido", "type": "string"}]},
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-normal", "type": "string"},
{"code": "efecto-aumentado", "type": "string"}, {"code": "efecto-disminuido", "type": "string"}]},
eeg_checks(),
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
+12 -11
View File
@@ -7,15 +7,16 @@ grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la m
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta
lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal.
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
misma que usan los lotes de riesgo y `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`; `id_seudonimo` repite ese valor
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna.
"""
import calendar
import hashlib
import json
import tomllib
from datetime import date, timedelta
@@ -85,7 +86,6 @@ class PaginaFuera(LookupError):
def seguimiento_de(
sesion: Session,
*,
sal: str,
corte: date | None = None,
meses: int | None = None,
estatus: str | None = None,
@@ -119,7 +119,7 @@ def seguimiento_de(
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
desde = _meses_antes(corte, meses) + timedelta(days=1)
estatus_de = _estatus_al_corte(sesion, corte, valores_estatus)
items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas)
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
if estatus is not None:
items = [i for i in items if i["estatus"]["codigo"] == estatus]
@@ -140,9 +140,9 @@ def seguimiento_de(
}
def seudonimo(pac_id: int, sal: str) -> str:
"""El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`."""
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
def identificador(pac_id: int) -> str:
"""El identificador que sale en la lista: el `pac_id` de la plataforma, como texto decimal."""
return str(pac_id)
def _validar_reglas(lista: dict) -> None:
@@ -164,7 +164,7 @@ def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int,
return {pac_id: estatus for pac_id, estatus in filas}
def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
"""Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua."""
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
en_ventana: dict[int, dict[str, list]] = {}
@@ -187,7 +187,8 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]])
estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE")
items.append({
"id_seudonimo": seudonimo(pac_id, sal),
"pac_id": identificador(pac_id),
"id_seudonimo": identificador(pac_id),
"grupo_edad": edades.get(pac_id, SIN_DATO),
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
"ultima_citologia": None if cito is None else {
@@ -201,7 +202,7 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
"prioridad": None,
"_orden": mas_reciente,
})
items.sort(key=lambda i: i["id_seudonimo"])
items.sort(key=lambda i: int(i["pac_id"]))
items.sort(key=lambda i: i.pop("_orden"), reverse=True)
return items
+4 -4
View File
@@ -3,8 +3,9 @@
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
Es dato por paciente, sobre datos simulados: toda respuesta lleva `simulado: true`. La ruta se registra
siempre; quién puede verla lo decidirá una regla de acceso. La lista la arma `webapi.follow_up.listing`; aquí solo se valida,
se abre la sesión y se traducen los errores.
siempre; quién puede verla lo decidirá una regla de acceso. Cada fila trae el `pac_id` de la plataforma, el que
usa la ruta de riesgo individual. La lista la arma `webapi.follow_up.listing`; aquí solo se valida, se abre la
sesión y se traducen los errores.
"""
import json
@@ -19,7 +20,6 @@ from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
from sqlmodel import Session
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
def in_dev() -> bool:
@@ -40,7 +40,7 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
return jsonify({"error": str(error)}), 400
sesion = get_session()
try:
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido)
cuerpo = seguimiento_de(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except PaginaFuera as error:
@@ -19,3 +19,21 @@ class BiopsiaMamaImportSchema(ImportSchema):
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
bx_pdf_blob: Optional[bytes] = None
bx_ocr_confianza: Optional[float] = None
bx_tipo_histologico: Optional[str] = None
bx_grado_nottingham: Optional[str] = None
bx_receptor_estrogeno: Optional[str] = None
bx_receptor_estrogeno_pct: Optional[float] = None
bx_receptor_progesterona: Optional[str] = None
bx_receptor_progesterona_pct: Optional[float] = None
bx_her2: Optional[str] = None
bx_her2_fish: Optional[str] = None
bx_ki67_pct: Optional[float] = None
bx_tamano_tumor_mm: Optional[float] = None
bx_ganglios_positivos: Optional[float] = None
bx_invasion_linfovascular: Optional[str] = None
bx_multifocalidad: Optional[str] = None
bx_margenes: Optional[str] = None
bx_pt: Optional[str] = None
bx_pn: Optional[str] = None
bx_lateralidad: Optional[str] = None
bx_localizacion: Optional[str] = None
@@ -22,3 +22,6 @@ class MastografiaImportSchema(ImportSchema):
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
mast_dicom_blob: Optional[bytes] = None
mast_interpretacion: Optional[str] = None
mast_densidad: Optional[str] = None
mast_margen_masa: Optional[str] = None
mast_tipo_hallazgo: Optional[str] = None
@@ -36,3 +36,5 @@ class NotaMedicaImportSchema(ImportSchema):
nm_presion_arterial_sistolica: Optional[int] = None
nm_presion_arterial_diastolica: Optional[int] = None
nm_temperatura: Optional[float] = None
nm_estadio_clinico: Optional[str] = None
nm_metastasis: Optional[str] = None
+14
View File
@@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import (
Catalog,
CatalogValue,
FlexDate,
PostalCode,
RequiredDate,
RequiredHospitalId,
@@ -25,6 +26,19 @@ class PacienteImportSchema(ImportSchema):
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
# IND-01: required, since age at each event of interest is derived from it.
pac_fecha_nacimiento: RequiredDate
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
pac_estado_civil: Optional[str] = None
pac_raza: Optional[str] = None
pac_brca1: Optional[str] = None
pac_brca2: Optional[str] = None
pac_estado_menopausico: Optional[str] = None
pac_pam50: Optional[str] = None
pac_subtipo_clinico: Optional[str] = None
pac_cluster_integrativo: Optional[str] = None
pac_celularidad: Optional[str] = None
pac_carga_mutacional: Optional[float] = None
pac_ki67_categoria: Optional[str] = None
pac_fuente: Optional[str] = None
@@ -0,0 +1,13 @@
"""Import schema for `core.cama.models.SeguimientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class SeguimientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
seg_tipo: RequiredStr
seg_fecha: FlexDate = None
seg_detalle: Optional[str] = None
@@ -0,0 +1,14 @@
"""Import schema for `core.cama.models.TratamientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class TratamientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
trat_tipo: RequiredStr
trat_fecha: FlexDate = None
trat_detalle: Optional[str] = None
trat_lateralidad: Optional[str] = None
+14 -14
View File
@@ -18,6 +18,8 @@ from persistance.cacu import paciente_repository as cacu_paciente_repository
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
from persistance.cama import tratamiento_mama_repository as cama_tratamiento_mama_repository
from persistance.cama import seguimiento_mama_repository as cama_seguimiento_mama_repository
from persistance.cama import mastografia_repository as cama_mastografia_repository
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
@@ -25,8 +27,6 @@ from persistance.cama import paciente_repository as cama_paciente_repository
from persistance.repository import Repository
from webapi.imports.schemas.base import ImportSchema
from persistance.tea import ados2_repository as tea_ados2_repository
from persistance.tea import eeg_metrica_electrodo_repository as tea_eeg_metrica_electrodo_repository
from persistance.tea import eeg_metrica_repository as tea_eeg_metrica_repository
from persistance.tea import eeg_repository as tea_eeg_repository
from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluacion_neuropediatrica_repository
from persistance.tea import mchat_repository as tea_mchat_repository
@@ -53,6 +53,8 @@ from webapi.imports.schemas.cama.episodio_clinico import (
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
)
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
from webapi.imports.schemas.cama.tratamiento_mama import TratamientoMamaImportSchema
from webapi.imports.schemas.cama.seguimiento_mama import SeguimientoMamaImportSchema
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
from webapi.imports.schemas.cama.ordenes_estudio import (
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
@@ -60,8 +62,6 @@ from webapi.imports.schemas.cama.ordenes_estudio import (
from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
from webapi.imports.schemas.tea.eeg import EegImportSchema
from webapi.imports.schemas.tea.eeg_metrica import EegMetricaImportSchema
from webapi.imports.schemas.tea.eeg_metrica_electrodo import EegMetricaElectrodoImportSchema
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema
from webapi.imports.schemas.tea.mchat import MchatImportSchema
from webapi.imports.schemas.tea.ordenes_estudio import (
@@ -154,6 +154,16 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
repository=cama_biometria_hematica_repository,
conflict_fields=None,
),
"cama.TratamientoMama": EntitySpec(
schema=TratamientoMamaImportSchema,
repository=cama_tratamiento_mama_repository,
conflict_fields=None,
),
"cama.SeguimientoMama": EntitySpec(
schema=SeguimientoMamaImportSchema,
repository=cama_seguimiento_mama_repository,
conflict_fields=None,
),
"cama.EpisodioClinico": EntitySpec(
schema=CamaEpisodioClinicoImportSchema,
repository=cama_episodio_clinico_repository,
@@ -187,14 +197,4 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
# one row.
conflict_fields=("eeg_id_registro_laboratorio",),
),
"tea.EegMetrica": EntitySpec(
schema=EegMetricaImportSchema,
repository=tea_eeg_metrica_repository,
conflict_fields=("met_id",),
),
"tea.EegMetricaElectrodo": EntitySpec(
schema=EegMetricaElectrodoImportSchema,
repository=tea_eeg_metrica_electrodo_repository,
conflict_fields=("mel_id",),
),
}
+4 -9
View File
@@ -1,15 +1,14 @@
"""Import schema for `core.tea.models.Eeg`: the study, its EDF and what the EEG analysis writes back (sleep,
channels, duration and the five quality criteria)."""
"""Import schema for `core.tea.models.Eeg`: the study and its EDF, and the sleep, channels, duration and line noise
a report may state. The verdict, quality checks and metrics are the EEG analysis's, written from the EDF, never
imported."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Bounded, EdfFile, FlexDate, OptionalStr, SourceId
_CHANNELS = Bounded(int, 0, None)
class EegImportSchema(ImportSchema):
# The source's own id, kept so the metrics that reference it still point at this record.
# The source's own id, kept so the analysis rows that reference it still point at this record.
eeg_id: SourceId = None
eeg_pac_id: Optional[int] = None
eeg_ord_id: OptionalStr = None
@@ -18,9 +17,5 @@ class EegImportSchema(ImportSchema):
eeg_con_sueno: Bounded(int, 0, 1) = None
eeg_canales: Bounded(int, 1, 256) = None
eeg_duracion_min: Bounded(float, 0, None) = None
eeg_canales_amplitud: _CHANNELS = None
eeg_canales_alta_frecuencia: _CHANNELS = None
eeg_canales_correlacion: _CHANNELS = None
eeg_canales_sin_senal: _CHANNELS = None
eeg_ruido_linea_db: Bounded(float, 0, None) = None
eeg_estudio: EdfFile = None
-16
View File
@@ -1,16 +0,0 @@
"""Import schema for `core.tea.models.EegMetrica`: a metric the EEG analysis measured. A blank value is a metric
that can't be evaluated."""
from typing import Optional
from core.tea.enums import MetricaEeg
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr, SourceId
_METRICA_CATALOG = Catalog(MetricaEeg)
class EegMetricaImportSchema(ImportSchema):
met_id: SourceId = None
met_eeg_id: OptionalStr = None
met_codigo: CatalogValue(_METRICA_CATALOG) = None
met_valor: Optional[float] = None
@@ -1,12 +0,0 @@
"""Import schema for `core.tea.models.EegMetricaElectrodo`: a metric's z-score at one 10-20 electrode."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import OptionalStr, SourceId
class EegMetricaElectrodoImportSchema(ImportSchema):
mel_id: SourceId = None
mel_met_id: OptionalStr = None
mel_electrodo: OptionalStr = None
mel_valor: Optional[float] = None
@@ -15,3 +15,4 @@ class OrdenesEstudioImportSchema(ImportSchema):
ord_id_hospital: OptionalStr = None
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
ord_fecha: FlexDate = None
ord_pdf_blob: Optional[bytes] = None
+4
View File
@@ -284,6 +284,10 @@ class MeasureQueries:
for a in p.at_end if a.known_at}
for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)):
known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())}
# The follow-up fact of a composition (the biopsy of the chosen sample) is compared with the knowledge cut-off too:
# its column has to be read as a datetime, or a text compare against the cut-off would be wrong.
follow_up = getattr(getattr(definition, "category", None), "follow_up", None)
known |= {definition.dimensions[n] for n in (follow_up.known_at if follow_up else ())}
self.status = getattr(definition, "population", None)
if self.status is not None:
names |= {definition.dimensions[n] for n in self.status.columns()}
+4 -1
View File
@@ -13,6 +13,8 @@ from datetime import date
from pathlib import Path
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
from webapi.orchestration.runner import run
PROJECTS = ("cacu", "cama", "tea")
@@ -42,7 +44,8 @@ def main(argv: list[str] | None = None) -> None:
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}")
return
logging.basicConfig(level=logging.INFO, format="%(message)s")
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters)
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project))
for paso in run(ctx, only=args.only):
print(f"{paso.name:20} {paso.seconds:6.1f} s")
+4 -1
View File
@@ -1,7 +1,7 @@
"""Lo que recibe cada paso del ciclo."""
import os
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import date
from pathlib import Path
@@ -39,5 +39,8 @@ class Context:
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()`
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada.
estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
# The domain's EEG analysis (`webapi.orchestration.eeg.live_eeg_analysis`): run by the `analyze_eeg` step before
# the silver load, it writes the analysis of each stored EDF to bronze. Without it, that step does nothing.
eeg_analysis: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
repos: Any = field(default=None, compare=False, repr=False)
+29 -35
View File
@@ -11,6 +11,7 @@ Bronce lo escribe la ingesta, fuera del ciclo.
"""
import logging
from dataclasses import asdict
from datetime import date, datetime
from functools import partial
from importlib import import_module
@@ -36,13 +37,13 @@ from webapi.orchestration.reference.rules import (
from webapi.orchestration.reference.periods import periodos_de_tipos
from webapi.orchestration.tables import tablas_de
from persistance.edges.silver import save_load_in
from sqlmodel import SQLModel, func, select
from sqlmodel import SQLModel, select
from webapi.orchestration.context import Context
from webapi.orchestration.semantic_layer import catalog_layers, event_views
from models.cohorts.build import build_of, latest_build, read_frame
from models.cohorts.definition import read_definition
from webapi.orchestration.project import cohort_definitions, period_types
from models.io.storage import read_queries
from webapi.orchestration.project import cohort_urls, period_types
log = logging.getLogger(__name__)
@@ -81,8 +82,17 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
return counts
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]:
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo`.
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
if ctx.eeg_analysis is None:
return {}
return asdict(ctx.eeg_analysis())
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis.
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
"""
@@ -178,23 +188,17 @@ def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict
@config.when(with_cohorts=True)
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
"""Arma cada cohorte del proyecto con las reglas de dbt, su única definición: la población, la fecha índice, las
exclusiones y las variables son consultas del manifest (`read_queries`), con su ventana de reclutamiento y su
corte (las variables de dbt), y corren en la base después de `event_models`.
"""
tablas = tablas_de(ctx.project)
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
def armado(definicion, sesion):
corte = ctx.cutoff or _last_load_date(sesion, tablas)
return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
linea=ctx.repos.silver.timeline.query)
manifest = _manifest(ctx)
armados = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
for url in cohort_urls(ctx.project, manifest):
consultas = read_queries(manifest, url)
armados[url] = ctx.repos.gold.cohorts.assemble(
lambda sesion, consultas=consultas: build_of(sesion, consultas, cohortes=tablas_cohorte))
return armados
@@ -210,30 +214,20 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
estimador = ctx.estimators.get(definicion.url)
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
continue
def frame(sesion, definicion=definicion):
armado_id = latest_build(sesion, definicion.url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, definicion,
cohortes=tablas_cohorte)
def frame(sesion, url=url):
armado_id = latest_build(sesion, url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, cohortes=tablas_cohorte)
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
if armado_id is None:
continue
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch(
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
return lotes
def _last_load_date(sesion, tablas) -> date | None:
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
if ultima is None or isinstance(ultima, date):
return ultima.date() if isinstance(ultima, datetime) else ultima
return date.fromisoformat(str(ultima)[:10])
+29
View File
@@ -0,0 +1,29 @@
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load.
`EEG_ANALYSIS_CLUSTER` says where the batch runs: `auto` (the default: the scheduler in `DASK_SCHEDULER_ADDRESS` if
set, otherwise a local cluster), `local`, `remote`, `sync` (in the cycle's own process), or `off`, which leaves the
analysis out of the cycle (`python -m models tea analyze` and `POST /governance/eeg/run` still run it).
"""
import os
from collections.abc import Callable
from functools import partial
from typing import Any
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
CLUSTERS = ("auto", "local", "remote", "sync")
def cluster() -> str:
value = os.environ.get(CLUSTER_ENV, "auto")
if value not in (*CLUSTERS, "off"):
raise ValueError(f"{CLUSTER_ENV} must be one of {', '.join((*CLUSTERS, 'off'))}, not {value!r}")
return value
def live_eeg_analysis(domain: str) -> Callable[[], Any] | None:
"""The domain's EEG analysis for the cycle, or none: only TEA has one, and `off` leaves it out."""
if domain != "tea" or cluster() == "off":
return None
from models.eeg_analysis import analyze_pending
return partial(analyze_pending, cluster=cluster())
+83
View File
@@ -0,0 +1,83 @@
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
its domain has in production.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
set, so an estimator here ignores the wide frame and rebuilds the model's own input (`models.io.storage.KitBuild`):
the cycle's latest build for membership, the domain's timeline for the events, then the production version in
MLflow to score it at the horizons its run recorded (`horizons_years`). `estimar`'s arguments go
unused by design.
"""
from dataclasses import dataclass
from importlib import import_module
from typing import Any
@dataclass(frozen=True)
class Provenance:
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str | None
def como_dict(self) -> dict[str, str]:
return {key: value for key, value in self.__dict__.items() if value}
class Cin2LogisticEstimator:
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to
test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has
something to report when `estimate` calls it."""
def __init__(self, domain: str = "cacu", version: str | None = None):
self.domain = domain
self.version = version
self.desenlace = "cin2_mas"
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import json
import mlflow.pyfunc
import numpy as np
from models.dags.estimation import estimate_frame
from models.dags.training import Scenario
from models.io.registry import registered_name, registry
from models.io.storage import KitBuild
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
scenario = Scenario.load(self.domain, "cin2_logistic")
build_id = repos.cohort_repository.latest_build(scenario.cohort)
resolved = registry.resolve(self.domain, scenario.scenario, self.version)
frame = KitBuild(self.domain, build_id).frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame))
self.desenlace = scenario.outcome
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))]
def procedencia(self) -> Provenance:
if self._provenance is None:
raise RuntimeError("estimar() runs before procedencia()")
return self._provenance
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
from models.dags.training import Scenario
from models.io.registry import registry
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {scenario.cohort: Cin2LogisticEstimator(domain)}
+6 -6
View File
@@ -1,9 +1,9 @@
"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`)."""
"""What the cycle needs to know of a project's definitions, all from dbt's manifest: its period types and its cohorts."""
import json
from pathlib import Path
from models.cohorts.definition import ROOT
from models.io.storage import cohort_urls as _cohort_urls
def period_types(proyecto: str, manifest: Path) -> list[str]:
@@ -13,7 +13,7 @@ def period_types(proyecto: str, manifest: Path) -> list[str]:
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
def cohort_definitions(proyecto: str) -> list[Path]:
"""The cohort TOMLs the cycle builds (`models/cohorts/<project>/*.toml`): today only CaCu's surveillance cohort.
Those in `<project>/proposals/` aren't built."""
return sorted((ROOT / proyecto).glob("*.toml"))
def cohort_urls(proyecto: str, manifest: Path | None) -> list[str]:
"""The cohorts the cycle builds: those of the project in dbt's manifest (`Transformation/models/<project>/cohorts/`,
`meta.cohort` of their population query). dbt is their only definition. None without a manifest."""
return _cohort_urls(manifest, proyecto) if manifest else []
+7 -6
View File
@@ -18,7 +18,8 @@ from hamilton.lifecycle import NodeExecutionHook
from webapi.orchestration import cycle
from webapi.orchestration.context import Context
from webapi.orchestration.project import cohort_definitions
from webapi.orchestration.context import dbt_manifest_path
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.repositories import repositories_of
log = logging.getLogger(__name__)
@@ -49,10 +50,10 @@ class _Logbook(NodeExecutionHook):
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
def _driver(proyecto: str, manifest, *adaptadores) -> driver.Driver:
return (driver.Builder()
.with_modules(cycle)
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
.with_config({"with_cohorts": bool(cohort_urls(proyecto, manifest))})
.with_adapters(*adaptadores)
.build())
@@ -61,9 +62,9 @@ def _in_order(dr: driver.Driver) -> list[str]:
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
def steps_of(proyecto: str) -> list[str]:
def steps_of(proyecto: str, manifest=None) -> list[str]:
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
return _in_order(_driver(proyecto))
return _in_order(_driver(proyecto, manifest or dbt_manifest_path()))
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
@@ -75,7 +76,7 @@ def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
if ctx.repos is None:
ctx = replace(ctx, repos=repositories_of(ctx.project))
bitacora = _Logbook()
dr = _driver(ctx.project, bitacora)
dr = _driver(ctx.project, ctx.dbt_manifest, bitacora)
todos = _in_order(dr)
pedidos = [p for p in todos if only is None or p in only]
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
+81 -8
View File
@@ -4,10 +4,10 @@
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
"""
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente, SeguimientoMama, TratamientoMama
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.extracted import ConEstructurado, DesdeTexto
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
@@ -36,11 +36,39 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"biopsia.her2", "biopsia.ki67_pct"),
texto=lambda f: f.bx_pdf_blob,
)
DE_LA_MASTOGRAFIA = ConEstructurado(DE_LA_INTERPRETACION, {"mastografia.densidad": "mast_densidad"})
# A mammogram's findings, each a part of its report.
LOS_HALLAZGOS = (
Hija("mastografia", "parte", solo_si=("mast_margen_masa",), fecha="mast_fecha_reporte",
resultados={"mast_margen_masa": "mastografia.margen_masa"}),
Hija("mastografia", "parte", solo_si=("mast_tipo_hallazgo",), fecha="mast_fecha_reporte",
resultados={"mast_tipo_hallazgo": "mastografia.tipo_hallazgo"}),
)
DE_LA_NOTA = DesdeTexto(
"cama", ("nota_medica.estadio_clinico",),
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
)
# What a biopsy report and a note carry structured wins over the text's reading; the rest is read from the text.
DE_LA_PATOLOGIA = ConEstructurado(DEL_REPORTE_DE_PATOLOGIA, {
"biopsia.tipo_histologico": "bx_tipo_histologico", "biopsia.grado_nottingham": "bx_grado_nottingham",
"biopsia.receptor_estrogeno": "bx_receptor_estrogeno", "biopsia.receptor_estrogeno_pct": "bx_receptor_estrogeno_pct",
"biopsia.receptor_progesterona": "bx_receptor_progesterona",
"biopsia.receptor_progesterona_pct": "bx_receptor_progesterona_pct", "biopsia.her2": "bx_her2",
"biopsia.ki67_pct": "bx_ki67_pct", "biopsia.her2_fish": "bx_her2_fish",
"biopsia.tamano_tumor_mm": "bx_tamano_tumor_mm", "biopsia.ganglios_positivos": "bx_ganglios_positivos",
"biopsia.invasion_linfovascular": "bx_invasion_linfovascular", "biopsia.multifocalidad": "bx_multifocalidad",
"biopsia.margenes": "bx_margenes", "biopsia.pt": "bx_pt", "biopsia.pn": "bx_pn",
})
DE_LA_NOTA_ESTRUCTURADA = ConEstructurado(DE_LA_NOTA, {
"nota_medica.estadio_clinico": "nm_estadio_clinico", "nota_medica.m": "nm_metastasis",
})
# The biopsy's sample: the breast and the site it was taken from, dated by its request or, without one, its report.
LA_TOMA_DE_LA_BIOPSIA = Hija(
"biopsia", "toma", solo_si=("bx_lateralidad", "bx_localizacion"), fecha="bx_fecha_toma",
resultados={"bx_lateralidad": "biopsia.lateralidad", "bx_localizacion": "biopsia.localizacion"},
)
DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
@@ -51,17 +79,62 @@ DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
derivadas=DE_LA_INTERPRETACION.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
fuentes=DE_LA_INTERPRETACION.fuentes,
derivadas=DE_LA_MASTOGRAFIA.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_MASTOGRAFIA.resultados},
fuentes=DE_LA_MASTOGRAFIA.fuentes, hijas=LOS_HALLAZGOS,
),
DeStaging(
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
derivadas={**DE_LA_PATOLOGIA.derivadas,
"bx_fecha_toma": lambda f: f.bx_fecha_solicitud or f.bx_fecha_reporte},
fuentes=DE_LA_PATOLOGIA.fuentes,
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
resultados={"bx_grado_histologico": "biopsia.grado", **DE_LA_PATOLOGIA.resultados}),
LA_TOMA_DE_LA_BIOPSIA),
),
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA_ESTRUCTURADA),
# Facts of the patient with no date of their own: dated at her birth, known as of the load.
DeStaging(
Paciente, "pac_id", "parte", estudio_id="sociodemografico", fecha="pac_fecha_nacimiento",
resultados={"pac_estado_civil": "sociodemografico.estado_civil", "pac_raza": "sociodemografico.raza",
"pac_estado_menopausico": "sociodemografico.estado_menopausico",
"pac_fuente": "sociodemografico.fuente"},
),
DeStaging(
Paciente, "pac_id", "reporte", estudio_id="prueba_genetica", fecha="pac_fecha_nacimiento",
solo_si=lambda f: f.pac_brca1 is not None or f.pac_brca2 is not None,
resultados={"pac_brca1": "prueba_genetica.brca1", "pac_brca2": "prueba_genetica.brca2"},
),
*(
DeStaging(
TratamientoMama, "trat_id", "encuentro", estudio_id=estudio, fecha="trat_fecha",
solo_si=lambda f, e=estudio: f.trat_tipo == e,
resultados={"trat_detalle": resultado, **({"trat_lateralidad": "cirugia.lateralidad"} if estudio == "cirugia" else {})},
)
for estudio, resultado in (
("cirugia", "cirugia.tipo_cirugia"), ("radioterapia", "radioterapia.intencion"),
("quimioterapia", "quimioterapia.intencion"), ("hormonoterapia", "hormonoterapia.intencion"),
("anti_her2", "anti_her2.intencion"),
)
),
*(
DeStaging(
SeguimientoMama, "seg_id", "encuentro", estudio_id=estudio, fecha="seg_fecha",
solo_si=lambda f, e=estudio: f.seg_tipo == e, resultados={"seg_detalle": resultado},
)
for estudio, resultado in (("recurrencia", "recurrencia.sitio"), ("ultimo_contacto", "ultimo_contacto.estado"))
),
DeStaging(
Paciente, "pac_id", "parte", estudio_id="perfil_molecular", fecha="pac_fecha_nacimiento",
solo_si=lambda f: any(getattr(f, c) is not None for c in (
"pac_pam50", "pac_subtipo_clinico", "pac_cluster_integrativo", "pac_celularidad", "pac_carga_mutacional",
"pac_ki67_categoria")),
resultados={"pac_pam50": "perfil_molecular.pam50", "pac_subtipo_clinico": "perfil_molecular.subtipo_clinico",
"pac_cluster_integrativo": "perfil_molecular.cluster_integrativo",
"pac_celularidad": "perfil_molecular.celularidad",
"pac_carga_mutacional": "perfil_molecular.carga_mutacional",
"pac_ki67_categoria": "perfil_molecular.ki67_categoria"},
),
)
+39
View File
@@ -117,3 +117,42 @@ def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
if texto is not None and str(texto.value).strip():
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
return None, None
@dataclass(frozen=True)
class ConEstructurado:
"""`DesdeTexto` whose results the row may carry already structured: a structured column wins over what the text
gives, and a column with no text twin is a result of its own. `estructurados`: result -> staging column;
each result keeps the text reading as its fallback when `lector` has it."""
lector: DesdeTexto | None
estructurados: dict[str, str]
@property
def derivadas(self) -> dict[str, Callable]:
columnas = dict(self.lector.derivadas) if self.lector else {}
leidos = set(self.lector.resultado_ids) if self.lector else set()
for resultado_id, columna in self.estructurados.items():
clave = _columna(resultado_id)
texto = self.lector.derivadas[clave] if resultado_id in leidos else (lambda f: None)
fuente = self.lector.derivadas[clave + "_fuente"] if resultado_id in leidos else (lambda f: None)
columnas[clave] = lambda f, c=columna, t=texto: _con_valor(getattr(f, c, None), t(f))
columnas[clave + "_fuente"] = lambda f, c=columna, t=fuente: (
None if _vacio(getattr(f, c, None)) else t(f))
return columnas
@property
def resultados(self) -> dict[str, str]:
return {_columna(r): r for r in {*(self.lector.resultado_ids if self.lector else ()), *self.estructurados}}
@property
def fuentes(self) -> dict[str, str]:
return {columna: columna + "_fuente" for columna in self.resultados}
def _vacio(valor) -> bool:
return valor is None or (isinstance(valor, str) and not valor.strip())
def _con_valor(estructurado, leido):
return leido if _vacio(estructurado) else estructurado
+1
View File
@@ -22,6 +22,7 @@ def de_derechohabiente(paciente) -> dict:
"dependencia": texto_limpio(paciente.pac_dependencia),
"parentesco": texto_limpio(paciente.pac_parentesco),
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
"fecha_defuncion": paciente.pac_fecha_defuncion,
}
+41 -9
View File
@@ -3,8 +3,10 @@
- an order is an `orden` of the study it asks for (`ord_tipo_estudio`, in Core's code or one of its aliases);
- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each
hangs from its order when it has one;
- an EEG metric is a result of its EEG's recording, not a procedure; a metric's electrode value is a `parte` of the
EEG (`codigo_fuente` the electrode) with the metric's result. Both find their EEG through the metric's row.
- what the EEG analysis writes: the EEG's verdict and study-wide quality checks (`eeg_criterio` without an
electrode) and each metric with its deviation from the age baseline are results of the EEG's recording, not
procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an electrode are `parte`s of
the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric.
"""
from core.tea.enums import (
@@ -18,6 +20,7 @@ from core.tea.models import (
ADOS2_ITEMS,
Ados2,
Eeg,
EegCriterio,
EegMetrica,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
@@ -50,7 +53,20 @@ def _metrica(f) -> str | None:
return None if codigo is None else codigo.lower()
def _criterio(f) -> str | None:
"""A quality check's results in the catalog: `calidad_` and its code in snake case (`clean-windows` ->
`calidad_clean_windows`)."""
codigo = texto_limpio(f.cri_codigo)
return None if codigo is None else "calidad_" + codigo.lower().replace("-", "_")
def _valor_de_criterio(f):
return f.cri_valor if f.cri_valor is not None else texto_limpio(f.cri_valor_texto)
SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG)
EEG_DEL_CRITERIO = Padre(estudio_id="eeg", clase="toma", fuente_id="cri_eeg_id", tabla=EEG)
DEVIATION = ("z", "fuera", "p5", "mediana", "p95")
DESDE_STAGING = (
@@ -95,26 +111,42 @@ DESDE_STAGING = (
Eeg, "eeg_id", "toma", estudio_id="eeg", fecha="eeg_fecha_estudio", paciente="eeg_pac_id",
padres=(_su_orden("eeg", "eeg_ord_id"),), columnas={"id_hospital": "eeg_id_registro_laboratorio"},
resultados={
"eeg_valido": "eeg.valido",
"eeg_nivel": "eeg.nivel",
"eeg_fraccion_limpia": "eeg.fraccion_limpia",
"eeg_canales_malos": "eeg.canales_malos",
"eeg_edad_meses": "eeg.edad_meses",
"eeg_con_sueno": "eeg.con_sueno",
"eeg_canales": "eeg.canales",
"eeg_duracion_min": "eeg.duracion_min",
"eeg_canales_amplitud": "eeg.calidad_amplitud",
"eeg_canales_alta_frecuencia": "eeg.calidad_alta_frecuencia",
"eeg_canales_correlacion": "eeg.calidad_correlacion",
"eeg_canales_sin_senal": "eeg.calidad_sin_senal",
"eeg_ruido_linea_db": "eeg.calidad_linea",
"eeg_ruido_linea_db": "eeg.ruido_linea",
},
),
DeStaging(
EegCriterio, "cri_id", "toma", estudio_id="eeg", paciente=None, observa_en=EEG_DEL_CRITERIO,
solo_si=lambda f: f.cri_electrodo is None,
derivadas={"criterio": _criterio, "valor": _valor_de_criterio},
resultados={"valor": "eeg.{criterio}", "cri_anormal": "eeg.{criterio}_anormal",
"cri_decisivo": "eeg.{criterio}_decisivo", "cri_bajo": "eeg.{criterio}_bajo",
"cri_alto": "eeg.{criterio}_alto"},
),
DeStaging(
EegCriterio, "cri_id", "parte", estudio_id="eeg", paciente=None, padres=(EEG_DEL_CRITERIO,),
solo_si=lambda f: f.cri_electrodo is not None,
derivadas={"criterio": _criterio, "valor": _valor_de_criterio},
columnas={"codigo_fuente": "cri_electrodo"},
resultados={"valor": "eeg.{criterio}"},
),
DeStaging(
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
derivadas={"metrica": _metrica},
resultados={"met_valor": "eeg.{metrica}"},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION}},
),
DeStaging(
EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,
juntas=(Junta(EegMetrica, "met_id", "mel_met_id"),), padres=(SU_EEG,),
derivadas={"metrica": _metrica},
columnas={"codigo_fuente": "mel_electrodo"},
resultados={"mel_valor": "eeg.{metrica}"},
resultados={"mel_valor": "eeg.{metrica}", "mel_z": "eeg.{metrica}_z"},
),
)
-49
View File
@@ -1,49 +0,0 @@
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
removed or renamed, only added.
"""
from datetime import timezone
from flask import Blueprint, jsonify
COHORT_URL = "cacu/cohorte_vigilancia"
COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
def patient_risk_blueprint(repositories) -> Blueprint:
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("cacu_patient_risk", __name__)
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
def get_patient_risk(pac_id: int):
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
if repositories.persona_repository.get(pac_id) is None:
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
membership = repositories.cohort_repository.membership(pac_id, COHORT_URL)
risk = repositories.cohort_repository.current_risk(pac_id)
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
return blueprint
def _cohort(membership) -> dict | None:
if membership is None:
return None
return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(),
**{name: membership.variables.get(name) for name in COHORT_VARIABLES}}
def _risk(risk) -> dict | None:
if risk is None:
return None
evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc)
return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version,
"evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"estado_lote": risk.estado_lote,
"horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
"ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}
+54 -15
View File
@@ -1,11 +1,15 @@
"""Recomputes a domain's indicators after its staging tables change.
A successful import asks for a recomputation (`RecomputationQueue.solicitar`),
A successful import asks for a recomputation (`RecomputationQueue.request_run`),
which only drops a marker file. A separate process (`python -m
webapi.recomputation`, the `indicadores` compose service) picks the
markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs ->
staging to facts -> views -> registry -> definitions -> reports.
Requests that arrive while a domain is running are folded into one more run.
webapi.recomputation`, the `indicadores` compose service) watches the markers'
directory and, on any change there, runs every pending domain's cycle
(`webapi.orchestration.run`): catalogs -> staging to facts -> views -> registry
-> definitions -> event models -> cohorts -> estimates, with the live estimators
of the models in production (`webapi.orchestration.estimators`). A periodic
check (`INDICADORES_INTERVALO_S`) stays as a fallback for a missed or coalesced
filesystem event; it no longer sets the normal reaction time. Requests that
arrive while a domain is running are folded into one more run.
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
and `estado.json`; each run is also appended, as counts only, to
@@ -24,6 +28,9 @@ from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes
@@ -99,6 +106,8 @@ class RecomputationQueue:
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
from webapi.orchestration import Context, run, steps_of
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
@@ -107,7 +116,8 @@ class RecomputationQueue:
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
try:
ctx = Context(dominio, desde, hasta, allow_undecided=True)
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",
@@ -134,22 +144,51 @@ class RecomputationQueue:
return ran
class _Waker(FileSystemEventHandler):
"""Wakes the main loop on any change in the pending-markers directory."""
def __init__(self, wake: threading.Event):
self._wake = wake
def on_any_event(self, event) -> None:
self._wake.set()
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
cola = RecomputationQueue()
interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
cola._pending.mkdir(parents=True, exist_ok=True)
fallback_s = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
for dominio in DOMAINS:
cola.request_run(dominio)
stop = threading.Event()
signal.signal(signal.SIGTERM, lambda *_: stop.set())
signal.signal(signal.SIGINT, lambda *_: stop.set())
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
while True:
for dominio in cola.serve():
log.info("%s: %s", dominio, cola.status()[dominio].get("estado"))
if stop.wait(interval):
break
wake = threading.Event()
def _stop(*_):
stop.set()
wake.set()
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
observer = Observer()
observer.schedule(_Waker(wake), str(cola._pending), recursive=False)
observer.start()
log.info("indicadores en vivo: observando %s (respaldo cada %.0f s)", cola._pending, fallback_s)
try:
while True:
for dominio in cola.serve():
log.info("%s: %s", dominio, cola.status()[dominio].get("estado"))
if stop.is_set():
break
wake.wait(fallback_s)
wake.clear()
if stop.is_set():
break
finally:
observer.stop()
observer.join()
if __name__ == "__main__":
+46
View File
@@ -0,0 +1,46 @@
"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`,
`/cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`) or void it (`entered-in-error`).
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
to be defined.
"""
from flask import Blueprint, jsonify, request
from persistance.edges.gold import ERROR, FINAL
def risk_batches_blueprint(repositories) -> Blueprint:
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("risk_batches", __name__)
@blueprint.get("/riesgos/lotes")
def list_pending_batches():
"""Pending batches, newest first."""
return jsonify([_batch(b) for b in repositories.cohort_repository.pending_batches()])
@blueprint.post("/riesgos/lotes/<int:lote_id>/confirmar")
def confirm_batch(lote_id: int):
"""Moves every current evaluation of the batch to `final` (ADR-MD-008): a clinical decision, with its
reason. 404 if the batch doesn't exist or has no evaluation left to decide."""
return _decide(lote_id, FINAL)
@blueprint.post("/riesgos/lotes/<int:lote_id>/anular")
def void_batch(lote_id: int):
"""Moves every current evaluation of the batch to `entered-in-error`."""
return _decide(lote_id, ERROR)
def _decide(lote_id: int, estado: str):
reason = (request.get_json(silent=True) or {}).get("reason", "").strip()
if not reason:
return jsonify({"error": "se requiere un motivo"}), 400
changed = repositories.cohort_repository.change_state(lote_id, estado, reason)
if not changed:
return jsonify({"error": f"el lote {lote_id} no existe o ya no tiene evaluaciones vigentes"}), 404
return jsonify({"lote_id": lote_id, "evaluaciones_cambiadas": changed})
return blueprint
def _batch(batch) -> dict:
return {"lote_id": batch.lote_id, "modelo_nombre": batch.modelo_nombre, "modelo_version": batch.modelo_version,
"evaluado_en": batch.evaluado_en.isoformat(), "n_evaluaciones": batch.n_evaluaciones}
+46
View File
@@ -0,0 +1,46 @@
"""Patient follow-up for the configured breast cohort."""
import calendar
from datetime import date, timedelta
from flask import Blueprint, jsonify, request
from webapi.cama_analysis import SelectionError, selection_response
def _desde(corte, meses):
indice = corte.year * 12 + corte.month - 1 - meses
anio, mes = divmod(indice, 12)
if anio < 1:
raise ValueError("la ventana excede el rango de fechas admitido")
anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1]))
return anterior + timedelta(days=1)
def blueprint_seguimiento_cama():
blueprint = Blueprint("cama_seguimiento", __name__)
@blueprint.after_request
def no_cache(response):
response.headers["Cache-Control"] = "no-store"
return response
def respond(mode, patient=None):
try:
return selection_response(request.args, mode, patient)
except SelectionError as error:
return jsonify(error=error.message), error.status
@blueprint.get("/seguimiento")
def seguimiento():
return respond('list')
@blueprint.get("/seguimiento/exportacion")
def exportacion():
return respond('export')
@blueprint.get("/pacientes/<pac_id>")
def paciente(pac_id):
return respond('patient', pac_id)
return blueprint