From 5a4baeb33edef322a71b2a8e68bbef10aee904fe Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:56:07 -0600 Subject: [PATCH 1/7] Tests: CaMa's stage and size measures of invasive cancers, and the measure counts --- tests/test_cama_measure_metadata.py | 3 +- tests/test_cama_stratifiers.py | 89 +++++++++++------------------ tests/test_fhir_measures.py | 2 +- tests/test_orquestacion_oro.py | 8 +-- 4 files changed, 41 insertions(+), 61 deletions(-) diff --git a/tests/test_cama_measure_metadata.py b/tests/test_cama_measure_metadata.py index d8bee9c..14c84d0 100644 --- a/tests/test_cama_measure_metadata.py +++ b/tests/test_cama_measure_metadata.py @@ -68,7 +68,8 @@ def test_each_contract_publishes_the_figures_the_page_can_draw(measures): "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": []} + "CAMA-HISTOPATOLOGIA-BIRADS": [], "CAMA-ESTADIO-CANCER-INVASOR": ["fig_c2_donas", "fig_c2_barras"], + "CAMA-TAMANO-CANCER-INVASOR": ["fig_c2_donas", "fig_c2_barras"]} assert {i: figures(m) for i, m in measures.items()} == expected diff --git a/tests/test_cama_stratifiers.py b/tests/test_cama_stratifiers.py index 219a318..7f6de6b 100644 --- a/tests/test_cama_stratifiers.py +++ b/tests/test_cama_stratifiers.py @@ -1,11 +1,12 @@ -"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata. -dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as -timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the -labels a timeline stratum's values carry into FHIR. +"""What this module covers: CaMa's tumour characteristics, from the results read from reports to the measures of the +invasive cancers. dbt's `cama_estratificadores` (stage group, early or advanced stage, T by size) as timeline facts; +`CAMA_ESTADIO_CANCER_INVASOR` and `CAMA_TAMANO_CANCER_INVASOR`, whose category is that characteristic as known by the +cut-offs; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into +FHIR. Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database (`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on -2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA. +2025-07-28 from her BI-RADS 4A mammogram (14 mm), and a note of 2025-08-04 with stage IIA. """ import os @@ -20,7 +21,7 @@ from webapi.compositions import answer_composition, composition_definitions from webapi.fhir.measures import _label from webapi.metrics import Question -URL = "cama/CAMA_BIRADS_CANCER_INVASOR" +BIRADS, ESTADIO, TAMANO = (f"cama/CAMA_{n}_CANCER_INVASOR" for n in ("BIRADS", "ESTADIO", "TAMANO")) UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @@ -40,10 +41,10 @@ def base(tmp_path, sin_supresion, manifest): base.motor.dispose() -def answered(base, manifest, period: str, event_cutoff: date | None = None): +def answered(base, manifest, url: str, period: str, event_cutoff: date | None = None): d = base.dominio - definition = composition_definitions(manifest)[URL] - return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff), + definition = composition_definitions(manifest)[url] + return answer_composition("cama", definition, Question(url, period, event_cutoff=event_cutoff), parameters=d.def_parametro_repository, periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True) @@ -54,58 +55,36 @@ def stratifiers(base) -> set[str]: def test_the_stratifiers_come_from_h003_s_reports(base): - """Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology - report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in - `vars.cama.estratos` or a timeline `tipo` it reads changes.""" - assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"} + """Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and + nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads + changes, or a subtype comes back.""" + assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "tamano_t1"} -def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest): - """Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to - it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the - category or a stratum's values drift.""" - assert answered(base, manifest, "2025-S1").categories == {} - result = answered(base, manifest, "2025-S2") - assert result.categories == {"B4A": 1} - assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}}, - "etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}}, - "tamano": {"T1": {"B4A": 1}}} +def test_the_invasive_cancers_split_by_stage_and_by_size(base, manifest): + """Pins down: H-003 counts in S2, the period of her biopsy report, under her stage (II, from the note) and her T + (T1, from the mammogram), each broken down by age; S1 has no invasive cancer. Fails if the characteristics model, + a category rule or the age stratum drifts.""" + assert answered(base, manifest, ESTADIO, "2025-S1").categories == {} + estadio = answered(base, manifest, ESTADIO, "2025-S2") + assert (estadio.categories, estadio.strata) == ({"II": 1}, {"grupo_edad": {"50-59": {"II": 1}}}) + tamano = answered(base, manifest, TAMANO, "2025-S2") + assert (tamano.categories, tamano.strata) == ({"T1": 1}, {"grupo_edad": {"50-59": {"T1": 1}}}) -def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest): - """Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype - (report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's - start (H-003 would have nothing) or ignores the cut-off (she'd have her stage).""" - strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata - assert strata["clasificacion"] == {"HER2": {"B4A": 1}} - assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}} +def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest): + """Pins down: the BI-RADS of the mammogram before an invasive cancer isn't broken down by the tumour's + characteristics, which describe the cancer and not that mammogram. Fails if tumour strata come back.""" + result = answered(base, manifest, BIRADS, "2025-S2") + assert (result.categories, result.strata) == ({"B4A": 1}, {}) -SUBTIPOS = [ - ({"her2": "H3"}, "subtipo_her2"), - ({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"), - ({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"), - ({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"), - ({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"), - ({"her2": "H0", "ki67_pct": None}, None), - ({"her2": "H2"}, None), -] - - -@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS) -def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo): - """Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both - receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and - progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's - report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise. - Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes.""" - valores = {"receptor_progesterona": "POSITIVO", **cambios} - with base.motor.begin() as con: - for nombre, valor in valores.items(): - columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id" - con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"), - {"v": valor, "r": f"biopsia.{nombre}"}) - assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set()) +def test_a_characteristic_is_read_as_known_by_the_cut_off(base, manifest): + """Pins down: a characteristic counts only if it was dated by the event cut-off: on 2025-08-01 the size (from the + mammogram before the biopsy) is known and the stage (note of 08-04) isn't, so H-003 still counts, without data. + Fails if a fact after the cut-off is read, or a patient without a fact by then drops out.""" + assert answered(base, manifest, TAMANO, "2025-S2", event_cutoff=date(2025, 8, 1)).categories == {"T1": 1} + assert answered(base, manifest, ESTADIO, "2025-S2", event_cutoff=date(2025, 8, 1)).categories == {"SIN_DATO": 1} def test_a_timeline_stratum_s_values_carry_their_labels(): diff --git a/tests/test_fhir_measures.py b/tests/test_fhir_measures.py index 21f3542..904fbdb 100644 --- a/tests/test_fhir_measures.py +++ b/tests/test_fhir_measures.py @@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client): with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape.""" domain, client = domain_client measures = valid(client.get(f"/{domain}/fhir/Measure").get_json()) - assert measures["total"] == {"cacu": 7, "cama": 11}[domain] + assert measures["total"] == {"cacu": 7, "cama": 13}[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() diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 8a1bd5c..413b319 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.run("definitions")["definitions"] - # CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures; - # TEA: the age group and its ten measures. - assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto] + # CaCu: three strata and its seven measures; CaMa: the age group of its invasive cancers, the BI-RADS stratum of + # the histopathological result and its thirteen measures; TEA: the age group and its ten measures. + assert resumen["definitions"] == {"cacu": 10, "cama": 15, "tea": 11}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto] + assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 13, "tea": 10}[base.proyecto] assert base.run("definitions")["definitions"]["borradas"] == 0 From 7a84cb19c937c907fbc24c96df1119b566ba6d33 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:56:07 -0600 Subject: [PATCH 2/7] Tests: each CaMa patient's scenario and the evidence that starts it --- tests/test_cama_scenarios.py | 88 ++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 tests/test_cama_scenarios.py diff --git a/tests/test_cama_scenarios.py b/tests/test_cama_scenarios.py new file mode 100644 index 0000000..c774512 --- /dev/null +++ b/tests/test_cama_scenarios.py @@ -0,0 +1,88 @@ +"""What this module covers: the group each CaMa patient's predicted risks are read in, inferred by dbt +(`cama_procedimientos_inferidos`, rules in `cama.escenarios`) and carried by her timeline with the kind of evidence +that started it: follow-up from a benign biopsy with no malignant diagnosis before, post-diagnosis from a note with a +malignant breast tumour ICD-10 or an invasive biopsy, post-treatment from a later such note by a treating specialty. + +Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database +(`staging/cama.py`) loaded, with dbt's views. Its records: H-003 an invasive biopsy (2025-07-28) and a C50.4 note by +oncological surgery (08-04); H-103 (C50.9, 07-20) and H-102 (C50.9, 09-30) one such note each; H-001 an in situ +carcinoma note (D05.1, by family medicine, 03-01) and a benign biopsy (04-05); H-104 a C50 note without a date. +""" + +import os +from datetime import date +from pathlib import Path + +import pytest +from conftest import base_de +from sqlalchemy import text + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +@pytest.fixture +def base(tmp_path, manifest): + base = base_de("cama", tmp_path) + base.run("catalogs", "load", "views", "event_models") + yield base + base.motor.dispose() + + +def scenarios(base) -> dict[str, set[tuple[str, date, str]]]: + """Patient (hospital id) -> the group facts of her timeline, (tipo, fecha, evidence).""" + with base.motor.connect() as con: + rows = con.execute(text( + "select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l " + "join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all() + found: dict[str, set[tuple[str, date, str]]] = {} + for r in rows: + found.setdefault(r.pac_id_hospital, set()).add( + (r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo)) + return found + + +def test_each_patient_s_group_starts_at_its_first_evidence(base): + """Pins down: an invasive biopsy or a dated C50 note, whoever wrote it, starts post-diagnosis; a C50 note by oncological + surgery after that diagnosis starts post-treatment, one on the diagnosis' own day doesn't (H-103, H-102); an in + situ carcinoma (D05) is no diagnosis, so H-001's benign biopsy starts her follow-up; a note without a date starts + nothing. Fails if `cama.escenarios` changes an evidence list, a grade or a code, or treatment stops requiring a + later date than the diagnosis.""" + assert scenarios(base) == { + "H-003": {("escenario_postdiagnostico", date(2025, 7, 28), "biopsia"), + ("escenario_postratamiento", date(2025, 8, 4), "nota")}, + "H-103": {("escenario_postdiagnostico", date(2025, 7, 20), "cie")}, + "H-102": {("escenario_postdiagnostico", date(2025, 9, 30), "cie")}, + "H-001": {("escenario_seguimiento", date(2025, 4, 5), "biopsia")}, + } + + +def test_a_benign_biopsy_after_a_malignant_diagnosis_starts_no_follow_up(base): + """Pins down: a benign biopsy reported after a malignant diagnosis doesn't start a follow-up, and a C50 note by a + specialty that doesn't treat (family medicine) is a diagnosis, not a treatment. Fails if the follow-up rule stops + looking at earlier diagnoses or `tratamiento_especialidades` stops filtering.""" + with base.motor.begin() as con: + con.execute(text( + "update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and " + "pac_id = (select pac_id from paciente where pac_id_hospital = 'H-001')")) + assert scenarios(base)["H-001"] == {("escenario_postdiagnostico", date(2025, 3, 1), "cie")} + + +def test_a_diagnosis_after_a_follow_up_keeps_both_groups(base): + """Pins down: a patient in follow-up whose malignant diagnosis comes later keeps both facts, so her timeline reads + the progression: follow-up from the benign biopsy, post-diagnosis from the later note. Fails if a later diagnosis + erases the follow-up that preceded it.""" + with base.motor.begin() as con: + con.execute(text( + "update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and " + "pac_id = (select pac_id from paciente where pac_id_hospital = 'H-001')")) + con.execute(text( + "update procedimiento set fecha = '2025-06-01' where estudio_id = 'nota_medica' and pac_id = " + "(select pac_id from paciente where pac_id_hospital = 'H-001')")) + assert scenarios(base)["H-001"] == {("escenario_seguimiento", date(2025, 4, 5), "biopsia"), + ("escenario_postdiagnostico", date(2025, 6, 1), "cie")} From ca0f02aa0ce691e70df554cee7784d2a0150cd5f Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:56:07 -0600 Subject: [PATCH 3/7] A coded catalog result may name the code system of its values; the histological type comes out as its ICD-O-3 code --- tests/test_extracted_results.py | 2 +- webapi/orchestration/reference/catalogs.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_extracted_results.py b/tests/test_extracted_results.py index 8dd938e..440f42e 100644 --- a/tests/test_extracted_results.py +++ b/tests/test_extracted_results.py @@ -125,7 +125,7 @@ def test_a_pathology_pdf_s_text_layer_gives_its_results(): going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor.""" leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1]))) assert {r: v for r, (v, _) in leido.items()} == { - "biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2", + "biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2", "biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0, "biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0, "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py index 2691940..a4a8bd8 100644 --- a/webapi/orchestration/reference/catalogs.py +++ b/webapi/orchestration/reference/catalogs.py @@ -204,8 +204,8 @@ def _tipo_de_valor(resultado: dict, resultado_id: str) -> str: raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.") if tipo_valor != "codigo" and "valores" in resultado: raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.") - if tipo_valor != "externo" and "sistema" in resultado: - raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.") + if tipo_valor not in ("codigo", "externo") and "sistema" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo o externo lleva sistema, no uno de tipo {tipo_valor}.") if tipo_valor != "numero" and "unidad" in resultado: raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.") return tipo_valor From 028f774400fbb597abf1698c5533019f7e495263 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 20:46:09 -0600 Subject: [PATCH 4/7] Tests: CaMa's clinical scenarios as a hierarchy, with discharge notes starting post-treatment --- tests/test_cama_scenarios.py | 96 ++++++++++++++++++++++-------------- 1 file changed, 58 insertions(+), 38 deletions(-) diff --git a/tests/test_cama_scenarios.py b/tests/test_cama_scenarios.py index c774512..fa66e3d 100644 --- a/tests/test_cama_scenarios.py +++ b/tests/test_cama_scenarios.py @@ -1,12 +1,13 @@ -"""What this module covers: the group each CaMa patient's predicted risks are read in, inferred by dbt -(`cama_procedimientos_inferidos`, rules in `cama.escenarios`) and carried by her timeline with the kind of evidence -that started it: follow-up from a benign biopsy with no malignant diagnosis before, post-diagnosis from a note with a -malignant breast tumour ICD-10 or an invasive biopsy, post-treatment from a later such note by a treating specialty. +"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`, +rules in `cama.escenarios`) and carried by her timeline with the evidence that started it and its level: screening from +her first mammogram before a diagnosis, control from a note with a malignant breast tumour ICD-10, post-treatment from +a discharge note after that diagnosis. Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database -(`staging/cama.py`) loaded, with dbt's views. Its records: H-003 an invasive biopsy (2025-07-28) and a C50.4 note by -oncological surgery (08-04); H-103 (C50.9, 07-20) and H-102 (C50.9, 09-30) one such note each; H-001 an in situ -carcinoma note (D05.1, by family medicine, 03-01) and a benign biopsy (04-05); H-104 a C50 note without a date. +(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30, +H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30), +H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a +type: the tests that need a discharge write `nota_medica.tipo_nota` themselves. """ import os @@ -34,49 +35,68 @@ def base(tmp_path, manifest): base.motor.dispose() -def scenarios(base) -> dict[str, set[tuple[str, date, str]]]: - """Patient (hospital id) -> the group facts of her timeline, (tipo, fecha, evidence).""" +def scenarios(base) -> dict[str, set[tuple[str, date, str, int]]]: + """Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence, level).""" with base.motor.connect() as con: rows = con.execute(text( - "select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l " + "select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo, l.valor_numerico from cama_linea_de_tiempo l " "join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all() - found: dict[str, set[tuple[str, date, str]]] = {} + found: dict[str, set[tuple[str, date, str, int]]] = {} for r in rows: found.setdefault(r.pac_id_hospital, set()).add( - (r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo)) + (r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo, int(r.valor_numerico))) return found -def test_each_patient_s_group_starts_at_its_first_evidence(base): - """Pins down: an invasive biopsy or a dated C50 note, whoever wrote it, starts post-diagnosis; a C50 note by oncological - surgery after that diagnosis starts post-treatment, one on the diagnosis' own day doesn't (H-103, H-102); an in - situ carcinoma (D05) is no diagnosis, so H-001's benign biopsy starts her follow-up; a note without a date starts - nothing. Fails if `cama.escenarios` changes an evidence list, a grade or a code, or treatment stops requiring a - later date than the diagnosis.""" +def discharge(base, hospital_id: str) -> None: + """Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would.""" + with base.motor.begin() as con: + con.execute(text( + "insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) " + "select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' " + "from procedimiento p join paciente x on x.pac_id = p.pac_id " + "where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id}) + + +def test_each_patient_s_scenario_follows_the_hierarchy(base): + """Pins down: a first mammogram starts screening only before a diagnosis; a dated C50 note, whoever wrote it, starts + control; an invasive biopsy alone doesn't (control asks for the ICD-10); an in situ carcinoma (D05) and a note + without a date start nothing; with no discharge note nobody is in post-treatment. Fails if `cama.escenarios` + changes an evidence list or a code, or screening stops ending at the diagnosis.""" assert scenarios(base) == { - "H-003": {("escenario_postdiagnostico", date(2025, 7, 28), "biopsia"), - ("escenario_postratamiento", date(2025, 8, 4), "nota")}, - "H-103": {("escenario_postdiagnostico", date(2025, 7, 20), "cie")}, - "H-102": {("escenario_postdiagnostico", date(2025, 9, 30), "cie")}, - "H-001": {("escenario_seguimiento", date(2025, 4, 5), "biopsia")}, + "H-001": {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1)}, + "H-003": {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1), + ("escenario_control", date(2025, 8, 4), "cie", 2)}, + "H-101": {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)}, + "H-102": {("escenario_tamizaje", date(2025, 2, 20), "mastografia", 1), + ("escenario_control", date(2025, 9, 30), "cie", 2)}, + "H-103": {("escenario_tamizaje", date(2025, 7, 1), "mastografia", 1), + ("escenario_control", date(2025, 7, 20), "cie", 2)}, + "H-104": {("escenario_tamizaje", date(2025, 11, 11), "mastografia", 1)}, } -def test_a_benign_biopsy_after_a_malignant_diagnosis_starts_no_follow_up(base): - """Pins down: a benign biopsy reported after a malignant diagnosis doesn't start a follow-up, and a C50 note by a - specialty that doesn't treat (family medicine) is a diagnosis, not a treatment. Fails if the follow-up rule stops - looking at earlier diagnoses or `tratamiento_especialidades` stops filtering.""" - with base.motor.begin() as con: - con.execute(text( - "update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and " - "pac_id = (select pac_id from paciente where pac_id_hospital = 'H-001')")) - assert scenarios(base)["H-001"] == {("escenario_postdiagnostico", date(2025, 3, 1), "cie")} +def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base): + """Pins down: a discharge note that carries a malignant tumour's ICD-10 starts post-treatment at its date, at level 3, + above the control the same note starts. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops + reading the note's type.""" + discharge(base, "H-003") + assert scenarios(base)["H-003"] == {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1), + ("escenario_control", date(2025, 8, 4), "cie", 2), + ("escenario_postratamiento", date(2025, 8, 4), "egreso", 3)} -def test_a_diagnosis_after_a_follow_up_keeps_both_groups(base): - """Pins down: a patient in follow-up whose malignant diagnosis comes later keeps both facts, so her timeline reads - the progression: follow-up from the benign biopsy, post-diagnosis from the later note. Fails if a later diagnosis - erases the follow-up that preceded it.""" +def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base): + """Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her in + screening: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it.""" + discharge(base, "H-101") + assert scenarios(base)["H-101"] == {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)} + + +def test_a_diagnosis_after_screening_keeps_both_levels(base): + """Pins down: a patient in screening whose malignant diagnosis comes later keeps both facts, so her timeline reads the + step from screening to control, the event that validates the screening models. Fails if a later diagnosis erases + the screening that preceded it.""" with base.motor.begin() as con: con.execute(text( "update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and " @@ -84,5 +104,5 @@ def test_a_diagnosis_after_a_follow_up_keeps_both_groups(base): con.execute(text( "update procedimiento set fecha = '2025-06-01' where estudio_id = 'nota_medica' and pac_id = " "(select pac_id from paciente where pac_id_hospital = 'H-001')")) - assert scenarios(base)["H-001"] == {("escenario_seguimiento", date(2025, 4, 5), "biopsia"), - ("escenario_postdiagnostico", date(2025, 6, 1), "cie")} + assert scenarios(base)["H-001"] == {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1), + ("escenario_control", date(2025, 6, 1), "cie", 2)} From 8130f86f3aca93a4daab650ce987c58bce45a17f Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 20 Nov 2026 18:46:40 -0600 Subject: [PATCH 5/7] Silver persona carries the date of death in CaCu and CaMa; tests for it and for CaMa's birth and death on the timeline --- tests/test_date_of_death.py | 62 ++++++++++++++++++++++++++ webapi/orchestration/silver/persons.py | 1 + 2 files changed, 63 insertions(+) create mode 100644 tests/test_date_of_death.py diff --git a/tests/test_date_of_death.py b/tests/test_date_of_death.py new file mode 100644 index 0000000..48e8f6a --- /dev/null +++ b/tests/test_date_of_death.py @@ -0,0 +1,62 @@ +"""What this module covers: a patient's date of death, from staging (`paciente.pac_fecha_defuncion`) to silver's +`persona.fecha_defuncion` in CaCu and CaMa, and in CaMa onto her timeline as a `defuncion` fact next to her birth. + +Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base_con_defuncion`, the domain's +fixture database (`staging/.py`) with one patient given a date of death before it's loaded. +""" + +import os +from datetime import date +from pathlib import Path + +import pytest +from conftest import base_de +from sqlalchemy import text + +DEATH = date(2026, 2, 1) + + +@pytest.fixture +def manifest(): + path = os.environ.get("DBT_MANIFEST") + if not path: + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + return Path(path) + + +def with_death(domain: str, tmp_path): + """The domain's fixture database with its first patient (lowest `pac_id`) dead on `DEATH`, loaded to silver.""" + base = base_de(domain, tmp_path) + with base.motor.begin() as con: + con.execute(text("update paciente set pac_fecha_defuncion = :d where pac_id = (select min(pac_id) from paciente)"), + {"d": DEATH}) + return base + + +@pytest.mark.parametrize("domain", ["cacu", "cama"]) +def test_silver_persona_carries_the_date_of_death(domain, tmp_path, manifest): + """Pins down: the dead patient's `persona` has her date of death and everyone else's is null. Fails if the + staging-to-silver copy (`persons.de_derechohabiente`) stops carrying `pac_fecha_defuncion`.""" + base = with_death(domain, tmp_path) + base.run("catalogs", "load") + with base.motor.connect() as con: + rows = con.execute(text("select pac_id, fecha_defuncion from persona order by pac_id")).all() + base.motor.dispose() + assert [date.fromisoformat(str(rows[0].fecha_defuncion)[:10])] + [r.fecha_defuncion for r in rows[1:]] \ + == [DEATH] + [None] * (len(rows) - 1) + + +def test_cama_timeline_has_birth_for_everyone_and_death_for_the_dead(tmp_path, manifest): + """Pins down: every CaMa patient has a `nacimiento` fact and only the dead one a `defuncion` fact, on her date of + death, with class `persona`. Fails if the timeline stops reading `persona` or reads a null date as a death.""" + base = with_death("cama", tmp_path) + base.run("catalogs", "load", "views", "event_models") + with base.motor.connect() as con: + people = con.execute(text("select count(*) from persona")).scalar_one() + facts = con.execute(text( + "select tipo, pac_id, fecha, clase from cama_linea_de_tiempo where tipo in ('nacimiento', 'defuncion')")).all() + first = con.execute(text("select min(pac_id) from persona")).scalar_one() + base.motor.dispose() + assert sum(f.tipo == "nacimiento" for f in facts) == people + assert [(f.pac_id, date.fromisoformat(str(f.fecha)[:10]), f.clase) for f in facts if f.tipo == "defuncion"] \ + == [(first, DEATH, "persona")] diff --git a/webapi/orchestration/silver/persons.py b/webapi/orchestration/silver/persons.py index 613c760..5047d57 100644 --- a/webapi/orchestration/silver/persons.py +++ b/webapi/orchestration/silver/persons.py @@ -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, } From d1e06798c9548d8ccec2fbf81a0572bfd678aaf0 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 20 Nov 2026 23:28:33 -0600 Subject: [PATCH 6/7] Tests: no CaMa measure is served by clinical stage or tumour size; the stratifiers view is built in its own test --- tests/test_cama_measure_metadata.py | 3 +- tests/test_cama_stratifiers.py | 46 ++++++++++++----------------- tests/test_fhir_measures.py | 2 +- tests/test_orquestacion_oro.py | 8 ++--- 4 files changed, 25 insertions(+), 34 deletions(-) diff --git a/tests/test_cama_measure_metadata.py b/tests/test_cama_measure_metadata.py index 14c84d0..d8bee9c 100644 --- a/tests/test_cama_measure_metadata.py +++ b/tests/test_cama_measure_metadata.py @@ -68,8 +68,7 @@ def test_each_contract_publishes_the_figures_the_page_can_draw(measures): "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": [], "CAMA-ESTADIO-CANCER-INVASOR": ["fig_c2_donas", "fig_c2_barras"], - "CAMA-TAMANO-CANCER-INVASOR": ["fig_c2_donas", "fig_c2_barras"]} + "CAMA-HISTOPATOLOGIA-BIRADS": []} assert {i: figures(m) for i, m in measures.items()} == expected diff --git a/tests/test_cama_stratifiers.py b/tests/test_cama_stratifiers.py index 7f6de6b..8d5361b 100644 --- a/tests/test_cama_stratifiers.py +++ b/tests/test_cama_stratifiers.py @@ -1,14 +1,13 @@ -"""What this module covers: CaMa's tumour characteristics, from the results read from reports to the measures of the -invasive cancers. dbt's `cama_estratificadores` (stage group, early or advanced stage, T by size) as timeline facts; -`CAMA_ESTADIO_CANCER_INVASOR` and `CAMA_TAMANO_CANCER_INVASOR`, whose category is that characteristic as known by the -cut-offs; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into -FHIR. +"""What this module covers: CaMa's tumour characteristics read from reports. dbt's `cama_estratificadores` (stage +group, early or advanced stage, T by size) as timeline facts; that no measure is served by clinical stage or tumour +size; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into FHIR. Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database (`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on 2025-07-28 from her BI-RADS 4A mammogram (14 mm), and a note of 2025-08-04 with stage IIA. """ +import json import os from dataclasses import replace from datetime import date @@ -21,7 +20,7 @@ from webapi.compositions import answer_composition, composition_definitions from webapi.fhir.measures import _label from webapi.metrics import Question -BIRADS, ESTADIO, TAMANO = (f"cama/CAMA_{n}_CANCER_INVASOR" for n in ("BIRADS", "ESTADIO", "TAMANO")) +BIRADS = "cama/CAMA_BIRADS_CANCER_INVASOR" UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @@ -49,27 +48,28 @@ def answered(base, manifest, url: str, period: str, event_cutoff: date | None = history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True) -def stratifiers(base) -> set[str]: +def stratifiers(base, manifest) -> set[str]: + """The stratifiers' `tipo`s, from the view built here: no served measure reads it, so the cycle doesn't.""" + node = next(n for n in json.loads(manifest.read_text(encoding="utf-8"))["nodes"].values() + if n["resource_type"] == "model" and n["name"] == "cama_estratificadores") with base.motor.connect() as con: - return set(con.execute(text("select tipo from cama_estratificadores")).scalars()) + return set(con.execute(text(f"select tipo from ({node['compiled_code']}) e")).scalars()) -def test_the_stratifiers_come_from_h003_s_reports(base): +def test_the_stratifiers_come_from_h003_s_reports(base, manifest): """Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads changes, or a subtype comes back.""" - assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "tamano_t1"} + assert stratifiers(base, manifest) == {"estadio_ii", "etapa_temprana", "tamano_t1"} -def test_the_invasive_cancers_split_by_stage_and_by_size(base, manifest): - """Pins down: H-003 counts in S2, the period of her biopsy report, under her stage (II, from the note) and her T - (T1, from the mammogram), each broken down by age; S1 has no invasive cancer. Fails if the characteristics model, - a category rule or the age stratum drifts.""" - assert answered(base, manifest, ESTADIO, "2025-S1").categories == {} - estadio = answered(base, manifest, ESTADIO, "2025-S2") - assert (estadio.categories, estadio.strata) == ({"II": 1}, {"grupo_edad": {"50-59": {"II": 1}}}) - tamano = answered(base, manifest, TAMANO, "2025-S2") - assert (tamano.categories, tamano.strata) == ({"T1": 1}, {"grupo_edad": {"50-59": {"T1": 1}}}) +def test_no_measure_is_served_by_stage_or_tumour_size(manifest): + """Pins down: clinical stage and tumour size aren't served as measures; they come from reports read by text, not + yet validated. Fails if a measure on them is published again.""" + metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() + urls = {m["config"].get("meta", {}).get("measure_url") for m in metrics} - {None} + assert BIRADS in urls and BIRADS in composition_definitions(manifest) + assert not {u for u in urls if "ESTADIO" in u or "TAMANO" in u} def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest): @@ -79,14 +79,6 @@ def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest) assert (result.categories, result.strata) == ({"B4A": 1}, {}) -def test_a_characteristic_is_read_as_known_by_the_cut_off(base, manifest): - """Pins down: a characteristic counts only if it was dated by the event cut-off: on 2025-08-01 the size (from the - mammogram before the biopsy) is known and the stage (note of 08-04) isn't, so H-003 still counts, without data. - Fails if a fact after the cut-off is read, or a patient without a fact by then drops out.""" - assert answered(base, manifest, TAMANO, "2025-S2", event_cutoff=date(2025, 8, 1)).categories == {"T1": 1} - assert answered(base, manifest, ESTADIO, "2025-S2", event_cutoff=date(2025, 8, 1)).categories == {"SIN_DATO": 1} - - def test_a_timeline_stratum_s_values_carry_their_labels(): """Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from `resto_etiqueta`. Fails if `_label` reads labels only from a map.""" diff --git a/tests/test_fhir_measures.py b/tests/test_fhir_measures.py index 904fbdb..21f3542 100644 --- a/tests/test_fhir_measures.py +++ b/tests/test_fhir_measures.py @@ -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": 13}[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() diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 413b319..eb2f598 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -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 age group of its invasive cancers, the BI-RADS stratum of - # the histopathological result and its thirteen measures; TEA: the age group and its ten measures. - assert resumen["definitions"] == {"cacu": 10, "cama": 15, "tea": 11}[base.proyecto] + # CaCu: three strata and its seven measures; CaMa: the BI-RADS stratum of the histopathological result and its + # eleven measures; TEA: the age group and its ten measures. + assert resumen["definitions"] == {"cacu": 10, "cama": 12, "tea": 11}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. - assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 13, "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 From 9b617db9d022dfa168ded37af535c8c9920f3a26 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 01:55:04 -0600 Subject: [PATCH 7/7] CaMa: two clinical scenarios, post-treatment and under observation, with the follow-up list's scenario column and filter --- tests/test_cama_follow_up.py | 59 +++++++++++++++++++++++++-- tests/test_cama_scenarios.py | 68 +++++++++----------------------- webapi/cama_follow_up/cohort.py | 24 +++++++++-- webapi/cama_follow_up/listing.py | 9 ++++- webapi/cama_follow_up/routes.py | 2 +- 5 files changed, 103 insertions(+), 59 deletions(-) diff --git a/tests/test_cama_follow_up.py b/tests/test_cama_follow_up.py index 31655a0..a2a6c0a 100644 --- a/tests/test_cama_follow_up.py +++ b/tests/test_cama_follow_up.py @@ -8,6 +8,7 @@ invented patients with the cases below; their names (`P01`...) are the source id Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6): BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day. P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it. +No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some. """ import json @@ -151,14 +152,16 @@ def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app): def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app): """Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its - date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data - doesn't support is added, or the hospital's identifier leaks.""" + date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body. + Fails if a column the data doesn't support is added, or the hospital's identifier leaks.""" respuesta = get(app, page_size=200) cuerpo = respuesta.get_json() assert cuerpo["simulado"] is True - assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"]) + assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha", + "escenario_clinico"} for i in cuerpo["items"]) + assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"} assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"]) - assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"] + assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"] assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES) assert respuesta.headers["Cache-Control"] == "no-store" @@ -368,3 +371,51 @@ def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_ with Session(base.motor) as sesion: cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31)) assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")] + + +@pytest.fixture +def con_postratamiento(tmp_path): + """The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on + 2025-11-01 and P06 on 2026-01-15, after the cut-off.""" + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it") + from sqlalchemy import text + + base = base_de("cama", tmp_path, datos=insertar) + base.run(*UNTIL_MODELS, allow_undecided=True) + hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"} + with base.motor.begin() as c: + for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"): + try: + with c.begin_nested(): + c.execute(text(drop)) + except Exception: + pass + c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)")) + for hospital, fecha in hechos.items(): + c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente " + "where pac_id_hospital = :h"), {"f": fecha, "h": hospital}) + flask = Flask(__name__) + flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama") + yield base, flask.test_client() + base.motor.dispose() + + +def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento): + """Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the + cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it + and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from + something other than the timeline, or if the filter stops being offered.""" + base, app = con_postratamiento + nombres = hospital_de(base) + escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"] + for i in get(app, corte=corte, page_size=200).get_json()["items"]} + al_corte = escenario(CORTE) + assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"} + assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"} + assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO" + filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200) + assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"} + filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico") + assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"}, + {"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}] diff --git a/tests/test_cama_scenarios.py b/tests/test_cama_scenarios.py index fa66e3d..d893976 100644 --- a/tests/test_cama_scenarios.py +++ b/tests/test_cama_scenarios.py @@ -1,7 +1,7 @@ """What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`, -rules in `cama.escenarios`) and carried by her timeline with the evidence that started it and its level: screening from -her first mammogram before a diagnosis, control from a note with a malignant breast tumour ICD-10, post-treatment from -a discharge note after that diagnosis. +rules in `cama.escenarios`): post-treatment from a discharge note after a malignant breast tumour's diagnosis, carried by +her timeline as an `escenario_postratamiento` fact with the evidence that started it; every other patient is under +observation ("en observación"), which has no fact. Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database (`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30, @@ -35,16 +35,15 @@ def base(tmp_path, manifest): base.motor.dispose() -def scenarios(base) -> dict[str, set[tuple[str, date, str, int]]]: - """Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence, level).""" +def scenarios(base) -> dict[str, set[tuple[str, date, str]]]: + """Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence).""" with base.motor.connect() as con: rows = con.execute(text( - "select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo, l.valor_numerico from cama_linea_de_tiempo l " + "select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l " "join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all() - found: dict[str, set[tuple[str, date, str, int]]] = {} + found: dict[str, set[tuple[str, date, str]]] = {} for r in rows: - found.setdefault(r.pac_id_hospital, set()).add( - (r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo, int(r.valor_numerico))) + found.setdefault(r.pac_id_hospital, set()).add((r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo)) return found @@ -58,51 +57,22 @@ def discharge(base, hospital_id: str) -> None: "where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id}) -def test_each_patient_s_scenario_follows_the_hierarchy(base): - """Pins down: a first mammogram starts screening only before a diagnosis; a dated C50 note, whoever wrote it, starts - control; an invasive biopsy alone doesn't (control asks for the ICD-10); an in situ carcinoma (D05) and a note - without a date start nothing; with no discharge note nobody is in post-treatment. Fails if `cama.escenarios` - changes an evidence list or a code, or screening stops ending at the diagnosis.""" - assert scenarios(base) == { - "H-001": {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1)}, - "H-003": {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1), - ("escenario_control", date(2025, 8, 4), "cie", 2)}, - "H-101": {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)}, - "H-102": {("escenario_tamizaje", date(2025, 2, 20), "mastografia", 1), - ("escenario_control", date(2025, 9, 30), "cie", 2)}, - "H-103": {("escenario_tamizaje", date(2025, 7, 1), "mastografia", 1), - ("escenario_control", date(2025, 7, 20), "cie", 2)}, - "H-104": {("escenario_tamizaje", date(2025, 11, 11), "mastografia", 1)}, - } +def test_without_a_discharge_every_patient_is_under_observation(base): + """Pins down: a mammogram, a malignant ICD-10 note (H-003, H-102, H-103) or an invasive biopsy (H-003) alone start + no scenario: with no discharge note nobody is in post-treatment and the timeline has no scenario fact, which reads as + under observation. Fails if screening or a diagnosis go back to being scenarios of their own.""" + assert scenarios(base) == {} def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base): - """Pins down: a discharge note that carries a malignant tumour's ICD-10 starts post-treatment at its date, at level 3, - above the control the same note starts. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops - reading the note's type.""" + """Pins down: a discharge note that carries a malignant tumour's ICD-10 puts H-003 in post-treatment from its date, + and only her. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops reading the note's type.""" discharge(base, "H-003") - assert scenarios(base)["H-003"] == {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1), - ("escenario_control", date(2025, 8, 4), "cie", 2), - ("escenario_postratamiento", date(2025, 8, 4), "egreso", 3)} + assert scenarios(base) == {"H-003": {("escenario_postratamiento", date(2025, 8, 4), "egreso")}} def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base): - """Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her in - screening: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it.""" + """Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her + under observation: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it.""" discharge(base, "H-101") - assert scenarios(base)["H-101"] == {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)} - - -def test_a_diagnosis_after_screening_keeps_both_levels(base): - """Pins down: a patient in screening whose malignant diagnosis comes later keeps both facts, so her timeline reads the - step from screening to control, the event that validates the screening models. Fails if a later diagnosis erases - the screening that preceded it.""" - with base.motor.begin() as con: - con.execute(text( - "update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and " - "pac_id = (select pac_id from paciente where pac_id_hospital = 'H-001')")) - con.execute(text( - "update procedimiento set fecha = '2025-06-01' where estudio_id = 'nota_medica' and pac_id = " - "(select pac_id from paciente where pac_id_hospital = 'H-001')")) - assert scenarios(base)["H-001"] == {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1), - ("escenario_control", date(2025, 6, 1), "cie", 2)} + assert scenarios(base) == {} diff --git a/webapi/cama_follow_up/cohort.py b/webapi/cama_follow_up/cohort.py index eb6932d..df7e8db 100644 --- a/webapi/cama_follow_up/cohort.py +++ b/webapi/cama_follow_up/cohort.py @@ -6,12 +6,14 @@ date taken, then the greatest source id, then the latest report date, then the g always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one (`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to. +Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on +or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise. Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off. """ from dataclasses import dataclass -from datetime import date +from datetime import date, timedelta from sqlalchemy import Date, Integer, String, column, func, inspect, select, table from sqlmodel import Session @@ -25,6 +27,8 @@ ESCENARIO = "diagnostico" VERSION = "0.1.0" SIN_DATO = "SIN_DATO" SIN_BIOPSIA = "SIN_BIOPSIA" +POST_TRATAMIENTO = "POST_TRATAMIENTO" +EN_OBSERVACION = "EN_OBSERVACION" # Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest. GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR") @@ -35,14 +39,17 @@ CANDIDATOS = table( column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String), column("biopsia_fecha_reporte", Date), column("biopsia_grado", String), ) +LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date)) class CohorteNoDisponible(RuntimeError): - """The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503).""" + """The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't + run (503).""" def disponible(sesion: Session) -> bool: - return inspect(sesion.get_bind()).has_table(CANDIDATOS.name) + inspector = inspect(sesion.get_bind()) + return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO)) @dataclass(frozen=True) @@ -58,6 +65,7 @@ class Fila: # The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`). primera_biopsia_fecha: date | None = None primer_maligno_fecha: date | None = None + escenario_clinico: str = EN_OBSERVACION @property def resultado(self) -> str: @@ -93,8 +101,17 @@ def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str: return SIN_DATO +def en_postratamiento(sesion: Session, corte: date) -> set[int]: + """The patients whose timeline puts them in post-treatment on or before `corte`.""" + linea = LINEA_DE_TIEMPO.c + # Before the next day, so a date stored with a time still counts on its own day. + return set(sesion.execute(select(linea.pac_id).distinct().where( + linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars()) + + def cohorte_al(sesion: Session, corte: date) -> list[Fila]: """The cohort at `corte`, latest mammogram first, then by `pac_id`.""" + postratamiento = en_postratamiento(sesion, corte) admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS)) malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS)) grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS) @@ -133,6 +150,7 @@ def cohorte_al(sesion: Session, corte: date) -> list[Fila]: biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None, primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None), primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None), + escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION, )) return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id)) diff --git a/webapi/cama_follow_up/listing.py b/webapi/cama_follow_up/listing.py index e45911e..3c8a9e0 100644 --- a/webapi/cama_follow_up/listing.py +++ b/webapi/cama_follow_up/listing.py @@ -14,7 +14,7 @@ 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, + COHORTE, EN_OBSERVACION, ESCENARIO, POST_TRATAMIENTO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion, disponible, grupos_de_edad, ) from webapi.orchestration.reference.rules import valor_de @@ -25,11 +25,13 @@ VENTANA_POR_OMISION = 3 PAGINA_MAXIMA = 200 EXPORTACION_MAXIMA = 5000 GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"} +ESCENARIOS_CLINICOS = {POST_TRATAMIENTO: "Post-tratamiento", EN_OBSERVACION: "En observación"} COLUMNAS = [ {"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}, + {"clave": "escenario_clinico", "etiqueta": "Escenario clínico"}, ] @@ -80,6 +82,8 @@ def filtros_disponibles(sesion: Session) -> list[dict]: *({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()), {"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]}, + {"clave": "escenario_clinico", "etiqueta": "Escenario clínico", "opciones": [ + {"codigo": c, "etiqueta": e} for c, e in ESCENARIOS_CLINICOS.items()]}, ] @@ -114,7 +118,8 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict) 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} + "biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None, + "escenario_clinico": f.escenario_clinico} def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]: diff --git a/webapi/cama_follow_up/routes.py b/webapi/cama_follow_up/routes.py index 22d412b..112894c 100644 --- a/webapi/cama_follow_up/routes.py +++ b/webapi/cama_follow_up/routes.py @@ -15,7 +15,7 @@ from webapi.cama_follow_up.listing import ( ) FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") -FILTROS = ("birads", "grupo_edad", "biopsia") +FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico") CONTEXTO = ("cohorte", "escenario", "revision") ENTEROS = ("meses", "page", "page_size")