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.
This commit is contained in:
Angel Capetillo Zavala
2026-11-17 10:44:07 -06:00
parent 0571b5e6af
commit b1bbbc25b4
27 changed files with 2729 additions and 12 deletions
+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.